pandaphd commited on
Commit
a7d4f3d
·
1 Parent(s): 1201269

fix 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. app_wget.py +0 -172
  2. diffusers/__init__.py +748 -0
  3. diffusers/commands/__init__.py +27 -0
  4. diffusers/commands/diffusers_cli.py +43 -0
  5. diffusers/commands/env.py +84 -0
  6. diffusers/commands/fp16_safetensors.py +133 -0
  7. diffusers/configuration_utils.py +695 -0
  8. diffusers/dependency_versions_check.py +34 -0
  9. diffusers/dependency_versions_table.py +45 -0
  10. diffusers/experimental/README.md +5 -0
  11. diffusers/experimental/__init__.py +1 -0
  12. diffusers/experimental/rl/__init__.py +1 -0
  13. diffusers/experimental/rl/value_guided_sampling.py +154 -0
  14. diffusers/image_processor.py +648 -0
  15. diffusers/loaders/__init__.py +82 -0
  16. diffusers/loaders/ip_adapter.py +157 -0
  17. diffusers/loaders/lora.py +1415 -0
  18. diffusers/loaders/lora_conversion_utils.py +284 -0
  19. diffusers/loaders/single_file.py +631 -0
  20. diffusers/loaders/textual_inversion.py +459 -0
  21. diffusers/loaders/unet.py +735 -0
  22. diffusers/loaders/utils.py +59 -0
  23. diffusers/models/README.md +3 -0
  24. diffusers/models/__init__.py +88 -0
  25. diffusers/models/activations.py +120 -0
  26. diffusers/models/adapter.py +584 -0
  27. diffusers/models/attention.py +547 -0
  28. diffusers/models/attention_flax.py +494 -0
  29. diffusers/models/attention_processor.py +2305 -0
  30. diffusers/models/autoencoder_asym_kl.py +186 -0
  31. {diffuserss → diffusers}/models/autoencoder_kl.py +1 -1
  32. diffusers/models/autoencoder_kl_temporal_decoder.py +402 -0
  33. diffusers/models/autoencoder_tiny.py +345 -0
  34. diffusers/models/consistency_decoder_vae.py +437 -0
  35. diffusers/models/controlnet.py +864 -0
  36. diffusers/models/controlnet_flax.py +395 -0
  37. diffusers/models/dual_transformer_2d.py +155 -0
  38. diffusers/models/embeddings.py +792 -0
  39. diffusers/models/embeddings_flax.py +97 -0
  40. diffusers/models/lora.py +434 -0
  41. diffusers/models/modeling_flax_pytorch_utils.py +134 -0
  42. diffusers/models/modeling_flax_utils.py +561 -0
  43. diffusers/models/modeling_outputs.py +17 -0
  44. diffusers/models/modeling_pytorch_flax_utils.py +161 -0
  45. diffusers/models/modeling_utils.py +1166 -0
  46. diffusers/models/normalization.py +148 -0
  47. diffusers/models/prior_transformer.py +382 -0
  48. diffusers/models/resnet.py +1368 -0
  49. diffusers/models/resnet_flax.py +124 -0
  50. diffusers/models/t5_film_transformer.py +438 -0
app_wget.py DELETED
@@ -1,172 +0,0 @@
1
- import spaces
2
- import os
3
- import json
4
- import torch
5
- import requests
6
- import subprocess
7
- import gradio as gr
8
- from omegaconf import OmegaConf
9
-
10
-
11
- model_path = "ckpts"
12
- os.makedirs(model_path, exist_ok=True)
13
-
14
- # Download files from Hugging Face repository using wget
15
- def download_huggingface_files():
16
- # URL to the Hugging Face repository
17
- repo_url = "https://huggingface.co/pandaphd/generative_photography/tree/main/"
18
- # Using wget to download all the files from the given Hugging Face repository
19
- subprocess.run(["wget", "-r", "-np", "-nH", "--cut-dirs=3", "-P", model_path, repo_url])
20
-
21
- print("Downloading models from Hugging Face...")
22
- download_huggingface_files()
23
-
24
-
25
- torch.manual_seed(42)
26
-
27
- bokeh_cfg = OmegaConf.load("configs/inference_genphoto/adv3_256_384_genphoto_relora_bokehK.yaml")
28
- bokeh_pipeline, bokeh_device = load_bokeh_models(bokeh_cfg)
29
-
30
- focal_cfg = OmegaConf.load("configs/inference_genphoto/adv3_256_384_genphoto_relora_focal_length.yaml")
31
- focal_pipeline, focal_device = load_focal_models(focal_cfg)
32
-
33
- shutter_cfg = OmegaConf.load("configs/inference_genphoto/adv3_256_384_genphoto_relora_shutter_speed.yaml")
34
- shutter_pipeline, shutter_device = load_shutter_models(shutter_cfg)
35
-
36
- color_cfg = OmegaConf.load("configs/inference_genphoto/adv3_256_384_genphoto_relora_color_temperature.yaml")
37
- color_pipeline, color_device = load_color_models(color_cfg)
38
-
39
- @spaces.GPU(duration=30)
40
- def generate_bokeh_video(base_scene, bokehK_list):
41
- try:
42
- torch.manual_seed(42)
43
- if len(json.loads(bokehK_list)) != 5:
44
- raise ValueError("Exactly 5 Bokeh K values required")
45
- return run_bokeh_inference(
46
- pipeline=bokeh_pipeline, tokenizer=bokeh_pipeline.tokenizer,
47
- text_encoder=bokeh_pipeline.text_encoder, base_scene=base_scene,
48
- bokehK_list=bokehK_list, device=bokeh_device
49
- )
50
- except Exception as e:
51
- return f"Error: {str(e)}"
52
-
53
- @spaces.GPU(duration=30)
54
- def generate_focal_video(base_scene, focal_length_list):
55
- try:
56
- torch.manual_seed(42)
57
- if len(json.loads(focal_length_list)) != 5:
58
- raise ValueError("Exactly 5 focal length values required")
59
- return run_focal_inference(
60
- pipeline=focal_pipeline, tokenizer=focal_pipeline.tokenizer,
61
- text_encoder=focal_pipeline.text_encoder, base_scene=base_scene,
62
- focal_length_list=focal_length_list, device=focal_device
63
- )
64
- except Exception as e:
65
- return f"Error: {str(e)}"
66
-
67
- @spaces.GPU(duration=30)
68
- def generate_shutter_video(base_scene, shutter_speed_list):
69
- try:
70
- torch.manual_seed(42)
71
- if len(json.loads(shutter_speed_list)) != 5:
72
- raise ValueError("Exactly 5 shutter speed values required")
73
- return run_shutter_inference(
74
- pipeline=shutter_pipeline, tokenizer=shutter_pipeline.tokenizer,
75
- text_encoder=shutter_pipeline.text_encoder, base_scene=base_scene,
76
- shutter_speed_list=shutter_speed_list, device=shutter_device
77
- )
78
- except Exception as e:
79
- return f"Error: {str(e)}"
80
-
81
-
82
- @spaces.GPU(duration=30)
83
- def generate_color_video(base_scene, color_temperature_list):
84
- try:
85
- torch.manual_seed(42)
86
- if len(json.loads(color_temperature_list)) != 5:
87
- raise ValueError("Exactly 5 color temperature values required")
88
- return run_color_inference(
89
- pipeline=color_pipeline, tokenizer=color_pipeline.tokenizer,
90
- text_encoder=color_pipeline.text_encoder, base_scene=base_scene,
91
- color_temperature_list=color_temperature_list, device=color_device
92
- )
93
- except Exception as e:
94
- return f"Error: {str(e)}"
95
-
96
-
97
-
98
- bokeh_examples = [
99
- ["A variety of potted plants are displayed on a window sill, with some of them placed in yellow and white cups. The plants are arranged in different sizes and shapes, creating a visually appealing display.", "[18.0, 14.0, 10.0, 6.0, 2.0]"],
100
- ["A colorful backpack with a floral pattern is sitting on a table next to a computer monitor.", "[2.3, 5.8, 10.2, 14.8, 24.9]"]
101
- ]
102
-
103
- focal_examples = [
104
- ["A small office cubicle with a desk.", "[25.1, 36.1, 47.1, 58.1, 69.1]"],
105
- ["A large white couch in a living room.", "[55.0, 46.0, 37.0, 28.0, 25.0]"]
106
- ]
107
-
108
- shutter_examples = [
109
- ["A brown and orange leather handbag.", "[0.11, 0.22, 0.33, 0.44, 0.55]"],
110
- ["A variety of potted plants.", "[0.2, 0.49, 0.69, 0.75, 0.89]"]
111
- ]
112
-
113
- color_examples = [
114
- ["A blue sky with mountains.", "[5455.0, 5155.0, 5555.0, 6555.0, 7555.0]"],
115
- ["A red couch in front of a window.", "[3500.0, 5500.0, 6500.0, 7500.0, 8500.0]"]
116
- ]
117
-
118
-
119
- with gr.Blocks(title="Generative Photography") as demo:
120
- gr.Markdown("# **Generative Photography: Scene-Consistent Camera Control for Realistic Text-to-Image Synthesis** ")
121
-
122
- with gr.Tabs():
123
- with gr.Tab("BokehK Effect"):
124
- gr.Markdown("### Generate Frames with Bokeh Blur Effect")
125
- with gr.Row():
126
- with gr.Column():
127
- scene_input_bokeh = gr.Textbox(label="Scene Description", placeholder="Describe the scene you want to generate...")
128
- bokeh_input = gr.Textbox(label="Bokeh Blur Values", placeholder="Enter 5 comma-separated values from 1-30, e.g., [2.44, 8.3, 10.1, 17.2, 24.0]")
129
- submit_bokeh = gr.Button("Generate Video")
130
- with gr.Column():
131
- video_output_bokeh = gr.Video(label="Generated Video")
132
- gr.Examples(bokeh_examples, [scene_input_bokeh, bokeh_input], [video_output_bokeh], generate_bokeh_video)
133
- submit_bokeh.click(generate_bokeh_video, [scene_input_bokeh, bokeh_input], [video_output_bokeh])
134
-
135
- with gr.Tab("Focal Length Effect"):
136
- gr.Markdown("### Generate Frames with Focal Length Effect")
137
- with gr.Row():
138
- with gr.Column():
139
- scene_input_focal = gr.Textbox(label="Scene Description", placeholder="Describe the scene you want to generate...")
140
- focal_input = gr.Textbox(label="Focal Length Values", placeholder="Enter 5 comma-separated values from 24-70, e.g., [25.1, 30.2, 33.3, 40.8, 54.0]")
141
- submit_focal = gr.Button("Generate Video")
142
- with gr.Column():
143
- video_output_focal = gr.Video(label="Generated Video")
144
- gr.Examples(focal_examples, [scene_input_focal, focal_input], [video_output_focal], generate_focal_video)
145
- submit_focal.click(generate_focal_video, [scene_input_focal, focal_input], [video_output_focal])
146
-
147
- with gr.Tab("Shutter Speed Effect"):
148
- gr.Markdown("### Generate Frames with Shutter Speed Effect")
149
- with gr.Row():
150
- with gr.Column():
151
- scene_input_shutter = gr.Textbox(label="Scene Description", placeholder="Describe the scene you want to generate...")
152
- shutter_input = gr.Textbox(label="Shutter Speed Values", placeholder="Enter 5 comma-separated values from 0.1-1.0, e.g., [0.15, 0.32, 0.53, 0.62, 0.82]")
153
- submit_shutter = gr.Button("Generate Video")
154
- with gr.Column():
155
- video_output_shutter = gr.Video(label="Generated Video")
156
- gr.Examples(shutter_examples, [scene_input_shutter, shutter_input], [video_output_shutter], generate_shutter_video)
157
- submit_shutter.click(generate_shutter_video, [scene_input_shutter, shutter_input], [video_output_shutter])
158
-
159
- with gr.Tab("Color Temperature Effect"):
160
- gr.Markdown("### Generate Frames with Color Temperature Effect")
161
- with gr.Row():
162
- with gr.Column():
163
- scene_input_color = gr.Textbox(label="Scene Description", placeholder="Describe the scene you want to generate...")
164
- color_input = gr.Textbox(label="Color Temperature Values", placeholder="Enter 5 comma-separated values from 2000-10000, e.g., [3001.3, 4000.2, 4400.34, 5488.23, 8888.82]")
165
- submit_color = gr.Button("Generate Video")
166
- with gr.Column():
167
- video_output_color = gr.Video(label="Generated Video")
168
- gr.Examples(color_examples, [scene_input_color, color_input], [video_output_color], generate_color_video)
169
- submit_color.click(generate_color_video, [scene_input_color, color_input], [video_output_color])
170
-
171
- if __name__ == "__main__":
172
- demo.launch(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/__init__.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __version__ = "0.24.0"
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from .utils import (
6
+ DIFFUSERS_SLOW_IMPORT,
7
+ OptionalDependencyNotAvailable,
8
+ _LazyModule,
9
+ is_flax_available,
10
+ is_k_diffusion_available,
11
+ is_librosa_available,
12
+ is_note_seq_available,
13
+ is_onnx_available,
14
+ is_scipy_available,
15
+ is_torch_available,
16
+ is_torchsde_available,
17
+ is_transformers_available,
18
+ )
19
+
20
+
21
+ # Lazy Import based on
22
+ # https://github.com/huggingface/transformers/blob/main/src/transformers/__init__.py
23
+
24
+ # When adding a new object to this init, please add it to `_import_structure`. The `_import_structure` is a dictionary submodule to list of object names,
25
+ # and is used to defer the actual importing for when the objects are requested.
26
+ # This way `import diffusers` provides the names in the namespace without actually importing anything (and especially none of the backends).
27
+
28
+ _import_structure = {
29
+ "configuration_utils": ["ConfigMixin"],
30
+ "models": [],
31
+ "pipelines": [],
32
+ "schedulers": [],
33
+ "utils": [
34
+ "OptionalDependencyNotAvailable",
35
+ "is_flax_available",
36
+ "is_inflect_available",
37
+ "is_invisible_watermark_available",
38
+ "is_k_diffusion_available",
39
+ "is_k_diffusion_version",
40
+ "is_librosa_available",
41
+ "is_note_seq_available",
42
+ "is_onnx_available",
43
+ "is_scipy_available",
44
+ "is_torch_available",
45
+ "is_torchsde_available",
46
+ "is_transformers_available",
47
+ "is_transformers_version",
48
+ "is_unidecode_available",
49
+ "logging",
50
+ ],
51
+ }
52
+
53
+ try:
54
+ if not is_onnx_available():
55
+ raise OptionalDependencyNotAvailable()
56
+ except OptionalDependencyNotAvailable:
57
+ from .utils import dummy_onnx_objects # noqa F403
58
+
59
+ _import_structure["utils.dummy_onnx_objects"] = [
60
+ name for name in dir(dummy_onnx_objects) if not name.startswith("_")
61
+ ]
62
+
63
+ else:
64
+ _import_structure["pipelines"].extend(["OnnxRuntimeModel"])
65
+
66
+ try:
67
+ if not is_torch_available():
68
+ raise OptionalDependencyNotAvailable()
69
+ except OptionalDependencyNotAvailable:
70
+ from .utils import dummy_pt_objects # noqa F403
71
+
72
+ _import_structure["utils.dummy_pt_objects"] = [name for name in dir(dummy_pt_objects) if not name.startswith("_")]
73
+
74
+ else:
75
+ _import_structure["models"].extend(
76
+ [
77
+ "AsymmetricAutoencoderKL",
78
+ "AutoencoderKL",
79
+ "AutoencoderKLTemporalDecoder",
80
+ "AutoencoderTiny",
81
+ "ConsistencyDecoderVAE",
82
+ "ControlNetModel",
83
+ "Kandinsky3UNet",
84
+ "ModelMixin",
85
+ "MotionAdapter",
86
+ "MultiAdapter",
87
+ "PriorTransformer",
88
+ "T2IAdapter",
89
+ "T5FilmDecoder",
90
+ "Transformer2DModel",
91
+ "UNet1DModel",
92
+ "UNet2DConditionModel",
93
+ "UNet2DModel",
94
+ "UNet3DConditionModel",
95
+ "UNetMotionModel",
96
+ "UNetSpatioTemporalConditionModel",
97
+ "VQModel",
98
+ ]
99
+ )
100
+
101
+ _import_structure["optimization"] = [
102
+ "get_constant_schedule",
103
+ "get_constant_schedule_with_warmup",
104
+ "get_cosine_schedule_with_warmup",
105
+ "get_cosine_with_hard_restarts_schedule_with_warmup",
106
+ "get_linear_schedule_with_warmup",
107
+ "get_polynomial_decay_schedule_with_warmup",
108
+ "get_scheduler",
109
+ ]
110
+ _import_structure["pipelines"].extend(
111
+ [
112
+ "AudioPipelineOutput",
113
+ "AutoPipelineForImage2Image",
114
+ "AutoPipelineForInpainting",
115
+ "AutoPipelineForText2Image",
116
+ "ConsistencyModelPipeline",
117
+ "DanceDiffusionPipeline",
118
+ "DDIMPipeline",
119
+ "DDPMPipeline",
120
+ "DiffusionPipeline",
121
+ "DiTPipeline",
122
+ "ImagePipelineOutput",
123
+ "KarrasVePipeline",
124
+ "LDMPipeline",
125
+ "LDMSuperResolutionPipeline",
126
+ "PNDMPipeline",
127
+ "RePaintPipeline",
128
+ "ScoreSdeVePipeline",
129
+ ]
130
+ )
131
+ _import_structure["schedulers"].extend(
132
+ [
133
+ "CMStochasticIterativeScheduler",
134
+ "DDIMInverseScheduler",
135
+ "DDIMParallelScheduler",
136
+ "DDIMScheduler",
137
+ "DDPMParallelScheduler",
138
+ "DDPMScheduler",
139
+ "DDPMWuerstchenScheduler",
140
+ "DEISMultistepScheduler",
141
+ "DPMSolverMultistepInverseScheduler",
142
+ "DPMSolverMultistepScheduler",
143
+ "DPMSolverSinglestepScheduler",
144
+ "EulerAncestralDiscreteScheduler",
145
+ "EulerDiscreteScheduler",
146
+ "HeunDiscreteScheduler",
147
+ "IPNDMScheduler",
148
+ "KarrasVeScheduler",
149
+ "KDPM2AncestralDiscreteScheduler",
150
+ "KDPM2DiscreteScheduler",
151
+ "LCMScheduler",
152
+ "PNDMScheduler",
153
+ "RePaintScheduler",
154
+ "SchedulerMixin",
155
+ "ScoreSdeVeScheduler",
156
+ "UnCLIPScheduler",
157
+ "UniPCMultistepScheduler",
158
+ "VQDiffusionScheduler",
159
+ ]
160
+ )
161
+ _import_structure["training_utils"] = ["EMAModel"]
162
+
163
+ try:
164
+ if not (is_torch_available() and is_scipy_available()):
165
+ raise OptionalDependencyNotAvailable()
166
+ except OptionalDependencyNotAvailable:
167
+ from .utils import dummy_torch_and_scipy_objects # noqa F403
168
+
169
+ _import_structure["utils.dummy_torch_and_scipy_objects"] = [
170
+ name for name in dir(dummy_torch_and_scipy_objects) if not name.startswith("_")
171
+ ]
172
+
173
+ else:
174
+ _import_structure["schedulers"].extend(["LMSDiscreteScheduler"])
175
+
176
+ try:
177
+ if not (is_torch_available() and is_torchsde_available()):
178
+ raise OptionalDependencyNotAvailable()
179
+ except OptionalDependencyNotAvailable:
180
+ from .utils import dummy_torch_and_torchsde_objects # noqa F403
181
+
182
+ _import_structure["utils.dummy_torch_and_torchsde_objects"] = [
183
+ name for name in dir(dummy_torch_and_torchsde_objects) if not name.startswith("_")
184
+ ]
185
+
186
+ else:
187
+ _import_structure["schedulers"].extend(["DPMSolverSDEScheduler"])
188
+
189
+ try:
190
+ if not (is_torch_available() and is_transformers_available()):
191
+ raise OptionalDependencyNotAvailable()
192
+ except OptionalDependencyNotAvailable:
193
+ from .utils import dummy_torch_and_transformers_objects # noqa F403
194
+
195
+ _import_structure["utils.dummy_torch_and_transformers_objects"] = [
196
+ name for name in dir(dummy_torch_and_transformers_objects) if not name.startswith("_")
197
+ ]
198
+
199
+ else:
200
+ _import_structure["pipelines"].extend(
201
+ [
202
+ "AltDiffusionImg2ImgPipeline",
203
+ "AltDiffusionPipeline",
204
+ "AnimateDiffPipeline",
205
+ "AudioLDM2Pipeline",
206
+ "AudioLDM2ProjectionModel",
207
+ "AudioLDM2UNet2DConditionModel",
208
+ "AudioLDMPipeline",
209
+ "BlipDiffusionControlNetPipeline",
210
+ "BlipDiffusionPipeline",
211
+ "CLIPImageProjection",
212
+ "CycleDiffusionPipeline",
213
+ "IFImg2ImgPipeline",
214
+ "IFImg2ImgSuperResolutionPipeline",
215
+ "IFInpaintingPipeline",
216
+ "IFInpaintingSuperResolutionPipeline",
217
+ "IFPipeline",
218
+ "IFSuperResolutionPipeline",
219
+ "ImageTextPipelineOutput",
220
+ "Kandinsky3Img2ImgPipeline",
221
+ "Kandinsky3Pipeline",
222
+ "KandinskyCombinedPipeline",
223
+ "KandinskyImg2ImgCombinedPipeline",
224
+ "KandinskyImg2ImgPipeline",
225
+ "KandinskyInpaintCombinedPipeline",
226
+ "KandinskyInpaintPipeline",
227
+ "KandinskyPipeline",
228
+ "KandinskyPriorPipeline",
229
+ "KandinskyV22CombinedPipeline",
230
+ "KandinskyV22ControlnetImg2ImgPipeline",
231
+ "KandinskyV22ControlnetPipeline",
232
+ "KandinskyV22Img2ImgCombinedPipeline",
233
+ "KandinskyV22Img2ImgPipeline",
234
+ "KandinskyV22InpaintCombinedPipeline",
235
+ "KandinskyV22InpaintPipeline",
236
+ "KandinskyV22Pipeline",
237
+ "KandinskyV22PriorEmb2EmbPipeline",
238
+ "KandinskyV22PriorPipeline",
239
+ "LatentConsistencyModelImg2ImgPipeline",
240
+ "LatentConsistencyModelPipeline",
241
+ "LDMTextToImagePipeline",
242
+ "MusicLDMPipeline",
243
+ "PaintByExamplePipeline",
244
+ "PixArtAlphaPipeline",
245
+ "SemanticStableDiffusionPipeline",
246
+ "ShapEImg2ImgPipeline",
247
+ "ShapEPipeline",
248
+ "StableDiffusionAdapterPipeline",
249
+ "StableDiffusionAttendAndExcitePipeline",
250
+ "StableDiffusionControlNetImg2ImgPipeline",
251
+ "StableDiffusionControlNetInpaintPipeline",
252
+ "StableDiffusionControlNetPipeline",
253
+ "StableDiffusionDepth2ImgPipeline",
254
+ "StableDiffusionDiffEditPipeline",
255
+ "StableDiffusionGLIGENPipeline",
256
+ "StableDiffusionGLIGENTextImagePipeline",
257
+ "StableDiffusionImageVariationPipeline",
258
+ "StableDiffusionImg2ImgPipeline",
259
+ "StableDiffusionInpaintPipeline",
260
+ "StableDiffusionInpaintPipelineLegacy",
261
+ "StableDiffusionInstructPix2PixPipeline",
262
+ "StableDiffusionLatentUpscalePipeline",
263
+ "StableDiffusionLDM3DPipeline",
264
+ "StableDiffusionModelEditingPipeline",
265
+ "StableDiffusionPanoramaPipeline",
266
+ "StableDiffusionParadigmsPipeline",
267
+ "StableDiffusionPipeline",
268
+ "StableDiffusionPipelineSafe",
269
+ "StableDiffusionPix2PixZeroPipeline",
270
+ "StableDiffusionSAGPipeline",
271
+ "StableDiffusionUpscalePipeline",
272
+ "StableDiffusionXLAdapterPipeline",
273
+ "StableDiffusionXLControlNetImg2ImgPipeline",
274
+ "StableDiffusionXLControlNetInpaintPipeline",
275
+ "StableDiffusionXLControlNetPipeline",
276
+ "StableDiffusionXLImg2ImgPipeline",
277
+ "StableDiffusionXLInpaintPipeline",
278
+ "StableDiffusionXLInstructPix2PixPipeline",
279
+ "StableDiffusionXLPipeline",
280
+ "StableUnCLIPImg2ImgPipeline",
281
+ "StableUnCLIPPipeline",
282
+ "StableVideoDiffusionPipeline",
283
+ "TextToVideoSDPipeline",
284
+ "TextToVideoZeroPipeline",
285
+ "TextToVideoZeroSDXLPipeline",
286
+ "UnCLIPImageVariationPipeline",
287
+ "UnCLIPPipeline",
288
+ "UniDiffuserModel",
289
+ "UniDiffuserPipeline",
290
+ "UniDiffuserTextDecoder",
291
+ "VersatileDiffusionDualGuidedPipeline",
292
+ "VersatileDiffusionImageVariationPipeline",
293
+ "VersatileDiffusionPipeline",
294
+ "VersatileDiffusionTextToImagePipeline",
295
+ "VideoToVideoSDPipeline",
296
+ "VQDiffusionPipeline",
297
+ "WuerstchenCombinedPipeline",
298
+ "WuerstchenDecoderPipeline",
299
+ "WuerstchenPriorPipeline",
300
+ ]
301
+ )
302
+
303
+ try:
304
+ if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
305
+ raise OptionalDependencyNotAvailable()
306
+ except OptionalDependencyNotAvailable:
307
+ from .utils import dummy_torch_and_transformers_and_k_diffusion_objects # noqa F403
308
+
309
+ _import_structure["utils.dummy_torch_and_transformers_and_k_diffusion_objects"] = [
310
+ name for name in dir(dummy_torch_and_transformers_and_k_diffusion_objects) if not name.startswith("_")
311
+ ]
312
+
313
+ else:
314
+ _import_structure["pipelines"].extend(["StableDiffusionKDiffusionPipeline"])
315
+
316
+ try:
317
+ if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
318
+ raise OptionalDependencyNotAvailable()
319
+ except OptionalDependencyNotAvailable:
320
+ from .utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
321
+
322
+ _import_structure["utils.dummy_torch_and_transformers_and_onnx_objects"] = [
323
+ name for name in dir(dummy_torch_and_transformers_and_onnx_objects) if not name.startswith("_")
324
+ ]
325
+
326
+ else:
327
+ _import_structure["pipelines"].extend(
328
+ [
329
+ "OnnxStableDiffusionImg2ImgPipeline",
330
+ "OnnxStableDiffusionInpaintPipeline",
331
+ "OnnxStableDiffusionInpaintPipelineLegacy",
332
+ "OnnxStableDiffusionPipeline",
333
+ "OnnxStableDiffusionUpscalePipeline",
334
+ "StableDiffusionOnnxPipeline",
335
+ ]
336
+ )
337
+
338
+ try:
339
+ if not (is_torch_available() and is_librosa_available()):
340
+ raise OptionalDependencyNotAvailable()
341
+ except OptionalDependencyNotAvailable:
342
+ from .utils import dummy_torch_and_librosa_objects # noqa F403
343
+
344
+ _import_structure["utils.dummy_torch_and_librosa_objects"] = [
345
+ name for name in dir(dummy_torch_and_librosa_objects) if not name.startswith("_")
346
+ ]
347
+
348
+ else:
349
+ _import_structure["pipelines"].extend(["AudioDiffusionPipeline", "Mel"])
350
+
351
+ try:
352
+ if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
353
+ raise OptionalDependencyNotAvailable()
354
+ except OptionalDependencyNotAvailable:
355
+ from .utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
356
+
357
+ _import_structure["utils.dummy_transformers_and_torch_and_note_seq_objects"] = [
358
+ name for name in dir(dummy_transformers_and_torch_and_note_seq_objects) if not name.startswith("_")
359
+ ]
360
+
361
+
362
+ else:
363
+ _import_structure["pipelines"].extend(["SpectrogramDiffusionPipeline"])
364
+
365
+ try:
366
+ if not is_flax_available():
367
+ raise OptionalDependencyNotAvailable()
368
+ except OptionalDependencyNotAvailable:
369
+ from .utils import dummy_flax_objects # noqa F403
370
+
371
+ _import_structure["utils.dummy_flax_objects"] = [
372
+ name for name in dir(dummy_flax_objects) if not name.startswith("_")
373
+ ]
374
+
375
+
376
+ else:
377
+ _import_structure["models.controlnet_flax"] = ["FlaxControlNetModel"]
378
+ _import_structure["models.modeling_flax_utils"] = ["FlaxModelMixin"]
379
+ _import_structure["models.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
380
+ _import_structure["models.vae_flax"] = ["FlaxAutoencoderKL"]
381
+ _import_structure["pipelines"].extend(["FlaxDiffusionPipeline"])
382
+ _import_structure["schedulers"].extend(
383
+ [
384
+ "FlaxDDIMScheduler",
385
+ "FlaxDDPMScheduler",
386
+ "FlaxDPMSolverMultistepScheduler",
387
+ "FlaxEulerDiscreteScheduler",
388
+ "FlaxKarrasVeScheduler",
389
+ "FlaxLMSDiscreteScheduler",
390
+ "FlaxPNDMScheduler",
391
+ "FlaxSchedulerMixin",
392
+ "FlaxScoreSdeVeScheduler",
393
+ ]
394
+ )
395
+
396
+
397
+ try:
398
+ if not (is_flax_available() and is_transformers_available()):
399
+ raise OptionalDependencyNotAvailable()
400
+ except OptionalDependencyNotAvailable:
401
+ from .utils import dummy_flax_and_transformers_objects # noqa F403
402
+
403
+ _import_structure["utils.dummy_flax_and_transformers_objects"] = [
404
+ name for name in dir(dummy_flax_and_transformers_objects) if not name.startswith("_")
405
+ ]
406
+
407
+
408
+ else:
409
+ _import_structure["pipelines"].extend(
410
+ [
411
+ "FlaxStableDiffusionControlNetPipeline",
412
+ "FlaxStableDiffusionImg2ImgPipeline",
413
+ "FlaxStableDiffusionInpaintPipeline",
414
+ "FlaxStableDiffusionPipeline",
415
+ "FlaxStableDiffusionXLPipeline",
416
+ ]
417
+ )
418
+
419
+ try:
420
+ if not (is_note_seq_available()):
421
+ raise OptionalDependencyNotAvailable()
422
+ except OptionalDependencyNotAvailable:
423
+ from .utils import dummy_note_seq_objects # noqa F403
424
+
425
+ _import_structure["utils.dummy_note_seq_objects"] = [
426
+ name for name in dir(dummy_note_seq_objects) if not name.startswith("_")
427
+ ]
428
+
429
+
430
+ else:
431
+ _import_structure["pipelines"].extend(["MidiProcessor"])
432
+
433
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
434
+ from .configuration_utils import ConfigMixin
435
+
436
+ try:
437
+ if not is_onnx_available():
438
+ raise OptionalDependencyNotAvailable()
439
+ except OptionalDependencyNotAvailable:
440
+ from .utils.dummy_onnx_objects import * # noqa F403
441
+ else:
442
+ from .pipelines import OnnxRuntimeModel
443
+
444
+ try:
445
+ if not is_torch_available():
446
+ raise OptionalDependencyNotAvailable()
447
+ except OptionalDependencyNotAvailable:
448
+ from .utils.dummy_pt_objects import * # noqa F403
449
+ else:
450
+ from .models import (
451
+ AsymmetricAutoencoderKL,
452
+ AutoencoderKL,
453
+ AutoencoderKLTemporalDecoder,
454
+ AutoencoderTiny,
455
+ ConsistencyDecoderVAE,
456
+ ControlNetModel,
457
+ Kandinsky3UNet,
458
+ ModelMixin,
459
+ MotionAdapter,
460
+ MultiAdapter,
461
+ PriorTransformer,
462
+ T2IAdapter,
463
+ T5FilmDecoder,
464
+ Transformer2DModel,
465
+ UNet1DModel,
466
+ UNet2DConditionModel,
467
+ UNet2DModel,
468
+ UNet3DConditionModel,
469
+ UNetMotionModel,
470
+ UNetSpatioTemporalConditionModel,
471
+ VQModel,
472
+ )
473
+ from .optimization import (
474
+ get_constant_schedule,
475
+ get_constant_schedule_with_warmup,
476
+ get_cosine_schedule_with_warmup,
477
+ get_cosine_with_hard_restarts_schedule_with_warmup,
478
+ get_linear_schedule_with_warmup,
479
+ get_polynomial_decay_schedule_with_warmup,
480
+ get_scheduler,
481
+ )
482
+ from .pipelines import (
483
+ AudioPipelineOutput,
484
+ AutoPipelineForImage2Image,
485
+ AutoPipelineForInpainting,
486
+ AutoPipelineForText2Image,
487
+ BlipDiffusionControlNetPipeline,
488
+ BlipDiffusionPipeline,
489
+ CLIPImageProjection,
490
+ ConsistencyModelPipeline,
491
+ DanceDiffusionPipeline,
492
+ DDIMPipeline,
493
+ DDPMPipeline,
494
+ DiffusionPipeline,
495
+ DiTPipeline,
496
+ ImagePipelineOutput,
497
+ KarrasVePipeline,
498
+ LDMPipeline,
499
+ LDMSuperResolutionPipeline,
500
+ PNDMPipeline,
501
+ RePaintPipeline,
502
+ ScoreSdeVePipeline,
503
+ )
504
+ from .schedulers import (
505
+ CMStochasticIterativeScheduler,
506
+ DDIMInverseScheduler,
507
+ DDIMParallelScheduler,
508
+ DDIMScheduler,
509
+ DDPMParallelScheduler,
510
+ DDPMScheduler,
511
+ DDPMWuerstchenScheduler,
512
+ DEISMultistepScheduler,
513
+ DPMSolverMultistepInverseScheduler,
514
+ DPMSolverMultistepScheduler,
515
+ DPMSolverSinglestepScheduler,
516
+ EulerAncestralDiscreteScheduler,
517
+ EulerDiscreteScheduler,
518
+ HeunDiscreteScheduler,
519
+ IPNDMScheduler,
520
+ KarrasVeScheduler,
521
+ KDPM2AncestralDiscreteScheduler,
522
+ KDPM2DiscreteScheduler,
523
+ LCMScheduler,
524
+ PNDMScheduler,
525
+ RePaintScheduler,
526
+ SchedulerMixin,
527
+ ScoreSdeVeScheduler,
528
+ UnCLIPScheduler,
529
+ UniPCMultistepScheduler,
530
+ VQDiffusionScheduler,
531
+ )
532
+ from .training_utils import EMAModel
533
+
534
+ try:
535
+ if not (is_torch_available() and is_scipy_available()):
536
+ raise OptionalDependencyNotAvailable()
537
+ except OptionalDependencyNotAvailable:
538
+ from .utils.dummy_torch_and_scipy_objects import * # noqa F403
539
+ else:
540
+ from .schedulers import LMSDiscreteScheduler
541
+
542
+ try:
543
+ if not (is_torch_available() and is_torchsde_available()):
544
+ raise OptionalDependencyNotAvailable()
545
+ except OptionalDependencyNotAvailable:
546
+ from .utils.dummy_torch_and_torchsde_objects import * # noqa F403
547
+ else:
548
+ from .schedulers import DPMSolverSDEScheduler
549
+
550
+ try:
551
+ if not (is_torch_available() and is_transformers_available()):
552
+ raise OptionalDependencyNotAvailable()
553
+ except OptionalDependencyNotAvailable:
554
+ from .utils.dummy_torch_and_transformers_objects import * # noqa F403
555
+ else:
556
+ from .pipelines import (
557
+ AltDiffusionImg2ImgPipeline,
558
+ AltDiffusionPipeline,
559
+ AnimateDiffPipeline,
560
+ AudioLDM2Pipeline,
561
+ AudioLDM2ProjectionModel,
562
+ AudioLDM2UNet2DConditionModel,
563
+ AudioLDMPipeline,
564
+ CLIPImageProjection,
565
+ CycleDiffusionPipeline,
566
+ IFImg2ImgPipeline,
567
+ IFImg2ImgSuperResolutionPipeline,
568
+ IFInpaintingPipeline,
569
+ IFInpaintingSuperResolutionPipeline,
570
+ IFPipeline,
571
+ IFSuperResolutionPipeline,
572
+ ImageTextPipelineOutput,
573
+ Kandinsky3Img2ImgPipeline,
574
+ Kandinsky3Pipeline,
575
+ KandinskyCombinedPipeline,
576
+ KandinskyImg2ImgCombinedPipeline,
577
+ KandinskyImg2ImgPipeline,
578
+ KandinskyInpaintCombinedPipeline,
579
+ KandinskyInpaintPipeline,
580
+ KandinskyPipeline,
581
+ KandinskyPriorPipeline,
582
+ KandinskyV22CombinedPipeline,
583
+ KandinskyV22ControlnetImg2ImgPipeline,
584
+ KandinskyV22ControlnetPipeline,
585
+ KandinskyV22Img2ImgCombinedPipeline,
586
+ KandinskyV22Img2ImgPipeline,
587
+ KandinskyV22InpaintCombinedPipeline,
588
+ KandinskyV22InpaintPipeline,
589
+ KandinskyV22Pipeline,
590
+ KandinskyV22PriorEmb2EmbPipeline,
591
+ KandinskyV22PriorPipeline,
592
+ LatentConsistencyModelImg2ImgPipeline,
593
+ LatentConsistencyModelPipeline,
594
+ LDMTextToImagePipeline,
595
+ MusicLDMPipeline,
596
+ PaintByExamplePipeline,
597
+ PixArtAlphaPipeline,
598
+ SemanticStableDiffusionPipeline,
599
+ ShapEImg2ImgPipeline,
600
+ ShapEPipeline,
601
+ StableDiffusionAdapterPipeline,
602
+ StableDiffusionAttendAndExcitePipeline,
603
+ StableDiffusionControlNetImg2ImgPipeline,
604
+ StableDiffusionControlNetInpaintPipeline,
605
+ StableDiffusionControlNetPipeline,
606
+ StableDiffusionDepth2ImgPipeline,
607
+ StableDiffusionDiffEditPipeline,
608
+ StableDiffusionGLIGENPipeline,
609
+ StableDiffusionGLIGENTextImagePipeline,
610
+ StableDiffusionImageVariationPipeline,
611
+ StableDiffusionImg2ImgPipeline,
612
+ StableDiffusionInpaintPipeline,
613
+ StableDiffusionInpaintPipelineLegacy,
614
+ StableDiffusionInstructPix2PixPipeline,
615
+ StableDiffusionLatentUpscalePipeline,
616
+ StableDiffusionLDM3DPipeline,
617
+ StableDiffusionModelEditingPipeline,
618
+ StableDiffusionPanoramaPipeline,
619
+ StableDiffusionParadigmsPipeline,
620
+ StableDiffusionPipeline,
621
+ StableDiffusionPipelineSafe,
622
+ StableDiffusionPix2PixZeroPipeline,
623
+ StableDiffusionSAGPipeline,
624
+ StableDiffusionUpscalePipeline,
625
+ StableDiffusionXLAdapterPipeline,
626
+ StableDiffusionXLControlNetImg2ImgPipeline,
627
+ StableDiffusionXLControlNetInpaintPipeline,
628
+ StableDiffusionXLControlNetPipeline,
629
+ StableDiffusionXLImg2ImgPipeline,
630
+ StableDiffusionXLInpaintPipeline,
631
+ StableDiffusionXLInstructPix2PixPipeline,
632
+ StableDiffusionXLPipeline,
633
+ StableUnCLIPImg2ImgPipeline,
634
+ StableUnCLIPPipeline,
635
+ StableVideoDiffusionPipeline,
636
+ TextToVideoSDPipeline,
637
+ TextToVideoZeroPipeline,
638
+ TextToVideoZeroSDXLPipeline,
639
+ UnCLIPImageVariationPipeline,
640
+ UnCLIPPipeline,
641
+ UniDiffuserModel,
642
+ UniDiffuserPipeline,
643
+ UniDiffuserTextDecoder,
644
+ VersatileDiffusionDualGuidedPipeline,
645
+ VersatileDiffusionImageVariationPipeline,
646
+ VersatileDiffusionPipeline,
647
+ VersatileDiffusionTextToImagePipeline,
648
+ VideoToVideoSDPipeline,
649
+ VQDiffusionPipeline,
650
+ WuerstchenCombinedPipeline,
651
+ WuerstchenDecoderPipeline,
652
+ WuerstchenPriorPipeline,
653
+ )
654
+
655
+ try:
656
+ if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
657
+ raise OptionalDependencyNotAvailable()
658
+ except OptionalDependencyNotAvailable:
659
+ from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
660
+ else:
661
+ from .pipelines import StableDiffusionKDiffusionPipeline
662
+
663
+ try:
664
+ if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
665
+ raise OptionalDependencyNotAvailable()
666
+ except OptionalDependencyNotAvailable:
667
+ from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
668
+ else:
669
+ from .pipelines import (
670
+ OnnxStableDiffusionImg2ImgPipeline,
671
+ OnnxStableDiffusionInpaintPipeline,
672
+ OnnxStableDiffusionInpaintPipelineLegacy,
673
+ OnnxStableDiffusionPipeline,
674
+ OnnxStableDiffusionUpscalePipeline,
675
+ StableDiffusionOnnxPipeline,
676
+ )
677
+
678
+ try:
679
+ if not (is_torch_available() and is_librosa_available()):
680
+ raise OptionalDependencyNotAvailable()
681
+ except OptionalDependencyNotAvailable:
682
+ from .utils.dummy_torch_and_librosa_objects import * # noqa F403
683
+ else:
684
+ from .pipelines import AudioDiffusionPipeline, Mel
685
+
686
+ try:
687
+ if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
688
+ raise OptionalDependencyNotAvailable()
689
+ except OptionalDependencyNotAvailable:
690
+ from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
691
+ else:
692
+ from .pipelines import SpectrogramDiffusionPipeline
693
+
694
+ try:
695
+ if not is_flax_available():
696
+ raise OptionalDependencyNotAvailable()
697
+ except OptionalDependencyNotAvailable:
698
+ from .utils.dummy_flax_objects import * # noqa F403
699
+ else:
700
+ from .models.controlnet_flax import FlaxControlNetModel
701
+ from .models.modeling_flax_utils import FlaxModelMixin
702
+ from .models.unet_2d_condition_flax import FlaxUNet2DConditionModel
703
+ from .models.vae_flax import FlaxAutoencoderKL
704
+ from .pipelines import FlaxDiffusionPipeline
705
+ from .schedulers import (
706
+ FlaxDDIMScheduler,
707
+ FlaxDDPMScheduler,
708
+ FlaxDPMSolverMultistepScheduler,
709
+ FlaxEulerDiscreteScheduler,
710
+ FlaxKarrasVeScheduler,
711
+ FlaxLMSDiscreteScheduler,
712
+ FlaxPNDMScheduler,
713
+ FlaxSchedulerMixin,
714
+ FlaxScoreSdeVeScheduler,
715
+ )
716
+
717
+ try:
718
+ if not (is_flax_available() and is_transformers_available()):
719
+ raise OptionalDependencyNotAvailable()
720
+ except OptionalDependencyNotAvailable:
721
+ from .utils.dummy_flax_and_transformers_objects import * # noqa F403
722
+ else:
723
+ from .pipelines import (
724
+ FlaxStableDiffusionControlNetPipeline,
725
+ FlaxStableDiffusionImg2ImgPipeline,
726
+ FlaxStableDiffusionInpaintPipeline,
727
+ FlaxStableDiffusionPipeline,
728
+ FlaxStableDiffusionXLPipeline,
729
+ )
730
+
731
+ try:
732
+ if not (is_note_seq_available()):
733
+ raise OptionalDependencyNotAvailable()
734
+ except OptionalDependencyNotAvailable:
735
+ from .utils.dummy_note_seq_objects import * # noqa F403
736
+ else:
737
+ from .pipelines import MidiProcessor
738
+
739
+ else:
740
+ import sys
741
+
742
+ sys.modules[__name__] = _LazyModule(
743
+ __name__,
744
+ globals()["__file__"],
745
+ _import_structure,
746
+ module_spec=__spec__,
747
+ extra_objects={"__version__": __version__},
748
+ )
diffusers/commands/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 abc import ABC, abstractmethod
16
+ from argparse import ArgumentParser
17
+
18
+
19
+ class BaseDiffusersCLICommand(ABC):
20
+ @staticmethod
21
+ @abstractmethod
22
+ def register_subcommand(parser: ArgumentParser):
23
+ raise NotImplementedError()
24
+
25
+ @abstractmethod
26
+ def run(self):
27
+ raise NotImplementedError()
diffusers/commands/diffusers_cli.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2023 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 2023 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,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ from argparse import ArgumentParser, Namespace
23
+ from importlib import import_module
24
+
25
+ import huggingface_hub
26
+ import torch
27
+ from huggingface_hub import hf_hub_download
28
+ from packaging import version
29
+
30
+ from ..utils import logging
31
+ from . import BaseDiffusersCLICommand
32
+
33
+
34
+ def conversion_command_factory(args: Namespace):
35
+ return FP16SafetensorsCommand(
36
+ args.ckpt_id,
37
+ args.fp16,
38
+ args.use_safetensors,
39
+ args.use_auth_token,
40
+ )
41
+
42
+
43
+ class FP16SafetensorsCommand(BaseDiffusersCLICommand):
44
+ @staticmethod
45
+ def register_subcommand(parser: ArgumentParser):
46
+ conversion_parser = parser.add_parser("fp16_safetensors")
47
+ conversion_parser.add_argument(
48
+ "--ckpt_id",
49
+ type=str,
50
+ help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
51
+ )
52
+ conversion_parser.add_argument(
53
+ "--fp16", action="store_true", help="If serializing the variables in FP16 precision."
54
+ )
55
+ conversion_parser.add_argument(
56
+ "--use_safetensors", action="store_true", help="If serializing in the safetensors format."
57
+ )
58
+ conversion_parser.add_argument(
59
+ "--use_auth_token",
60
+ action="store_true",
61
+ help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
62
+ )
63
+ conversion_parser.set_defaults(func=conversion_command_factory)
64
+
65
+ def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool, use_auth_token: bool):
66
+ self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
67
+ self.ckpt_id = ckpt_id
68
+ self.local_ckpt_dir = f"/tmp/{ckpt_id}"
69
+ self.fp16 = fp16
70
+
71
+ self.use_safetensors = use_safetensors
72
+
73
+ if not self.use_safetensors and not self.fp16:
74
+ raise NotImplementedError(
75
+ "When `use_safetensors` and `fp16` both are False, then this command is of no use."
76
+ )
77
+
78
+ self.use_auth_token = use_auth_token
79
+
80
+ def run(self):
81
+ if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
82
+ raise ImportError(
83
+ "The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
84
+ " installation."
85
+ )
86
+ else:
87
+ from huggingface_hub import create_commit
88
+ from huggingface_hub._commit_api import CommitOperationAdd
89
+
90
+ model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json", token=self.use_auth_token)
91
+ with open(model_index, "r") as f:
92
+ pipeline_class_name = json.load(f)["_class_name"]
93
+ pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
94
+ self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
95
+
96
+ # Load the appropriate pipeline. We could have use `DiffusionPipeline`
97
+ # here, but just to avoid any rough edge cases.
98
+ pipeline = pipeline_class.from_pretrained(
99
+ self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32, use_auth_token=self.use_auth_token
100
+ )
101
+ pipeline.save_pretrained(
102
+ self.local_ckpt_dir,
103
+ safe_serialization=True if self.use_safetensors else False,
104
+ variant="fp16" if self.fp16 else None,
105
+ )
106
+ self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
107
+
108
+ # Fetch all the paths.
109
+ if self.fp16:
110
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
111
+ elif self.use_safetensors:
112
+ modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
113
+
114
+ # Prepare for the PR.
115
+ commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
116
+ operations = []
117
+ for path in modified_paths:
118
+ operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
119
+
120
+ # Open the PR.
121
+ commit_description = (
122
+ "Variables converted by the [`diffusers`' `fp16_safetensors`"
123
+ " CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
124
+ )
125
+ hub_pr_url = create_commit(
126
+ repo_id=self.ckpt_id,
127
+ operations=operations,
128
+ commit_message=commit_message,
129
+ commit_description=commit_description,
130
+ repo_type="model",
131
+ create_pr=True,
132
+ ).pr_url
133
+ self.logger.info(f"PR created here: {hub_pr_url}.")
diffusers/configuration_utils.py ADDED
@@ -0,0 +1,695 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ import dataclasses
18
+ import functools
19
+ import importlib
20
+ import inspect
21
+ import json
22
+ import os
23
+ import re
24
+ from collections import OrderedDict
25
+ from pathlib import PosixPath
26
+ from typing import Any, Dict, Tuple, Union
27
+
28
+ import numpy as np
29
+ from huggingface_hub import create_repo, hf_hub_download
30
+ from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
31
+ from requests import HTTPError
32
+
33
+ from . import __version__
34
+ from .utils import (
35
+ DIFFUSERS_CACHE,
36
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
37
+ DummyObject,
38
+ deprecate,
39
+ extract_commit_hash,
40
+ http_user_agent,
41
+ logging,
42
+ )
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _re_configuration_file = re.compile(r"config\.(.*)\.json")
48
+
49
+
50
+ class FrozenDict(OrderedDict):
51
+ def __init__(self, *args, **kwargs):
52
+ super().__init__(*args, **kwargs)
53
+
54
+ for key, value in self.items():
55
+ setattr(self, key, value)
56
+
57
+ self.__frozen = True
58
+
59
+ def __delitem__(self, *args, **kwargs):
60
+ raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
61
+
62
+ def setdefault(self, *args, **kwargs):
63
+ raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
64
+
65
+ def pop(self, *args, **kwargs):
66
+ raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
67
+
68
+ def update(self, *args, **kwargs):
69
+ raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
70
+
71
+ def __setattr__(self, name, value):
72
+ if hasattr(self, "__frozen") and self.__frozen:
73
+ raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
74
+ super().__setattr__(name, value)
75
+
76
+ def __setitem__(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().__setitem__(name, value)
80
+
81
+
82
+ class ConfigMixin:
83
+ r"""
84
+ Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
85
+ provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
86
+ saving classes that inherit from [`ConfigMixin`].
87
+
88
+ Class attributes:
89
+ - **config_name** (`str`) -- A filename under which the config should stored when calling
90
+ [`~ConfigMixin.save_config`] (should be overridden by parent class).
91
+ - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
92
+ overridden by subclass).
93
+ - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
94
+ - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
95
+ should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
96
+ subclass).
97
+ """
98
+
99
+ config_name = None
100
+ ignore_for_config = []
101
+ has_compatibles = False
102
+
103
+ _deprecated_kwargs = []
104
+
105
+ def register_to_config(self, **kwargs):
106
+ if self.config_name is None:
107
+ raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
108
+ # Special case for `kwargs` used in deprecation warning added to schedulers
109
+ # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
110
+ # or solve in a more general way.
111
+ kwargs.pop("kwargs", None)
112
+
113
+ if not hasattr(self, "_internal_dict"):
114
+ internal_dict = kwargs
115
+ else:
116
+ previous_dict = dict(self._internal_dict)
117
+ internal_dict = {**self._internal_dict, **kwargs}
118
+ logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
119
+
120
+ self._internal_dict = FrozenDict(internal_dict)
121
+
122
+ def __getattr__(self, name: str) -> Any:
123
+ """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
124
+ config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
125
+
126
+ Tihs funtion is mostly copied from PyTorch's __getattr__ overwrite:
127
+ https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
128
+ """
129
+
130
+ is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
131
+ is_attribute = name in self.__dict__
132
+
133
+ if is_in_config and not is_attribute:
134
+ 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}'."
135
+ deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
136
+ return self._internal_dict[name]
137
+
138
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
139
+
140
+ def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
141
+ """
142
+ Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
143
+ [`~ConfigMixin.from_config`] class method.
144
+
145
+ Args:
146
+ save_directory (`str` or `os.PathLike`):
147
+ Directory where the configuration JSON file is saved (will be created if it does not exist).
148
+ push_to_hub (`bool`, *optional*, defaults to `False`):
149
+ Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
150
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
151
+ namespace).
152
+ kwargs (`Dict[str, Any]`, *optional*):
153
+ Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
154
+ """
155
+ if os.path.isfile(save_directory):
156
+ raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
157
+
158
+ os.makedirs(save_directory, exist_ok=True)
159
+
160
+ # If we save using the predefined names, we can load using `from_config`
161
+ output_config_file = os.path.join(save_directory, self.config_name)
162
+
163
+ self.to_json_file(output_config_file)
164
+ logger.info(f"Configuration saved in {output_config_file}")
165
+
166
+ if push_to_hub:
167
+ commit_message = kwargs.pop("commit_message", None)
168
+ private = kwargs.pop("private", False)
169
+ create_pr = kwargs.pop("create_pr", False)
170
+ token = kwargs.pop("token", None)
171
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
172
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
173
+
174
+ self._upload_folder(
175
+ save_directory,
176
+ repo_id,
177
+ token=token,
178
+ commit_message=commit_message,
179
+ create_pr=create_pr,
180
+ )
181
+
182
+ @classmethod
183
+ def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
184
+ r"""
185
+ Instantiate a Python class from a config dictionary.
186
+
187
+ Parameters:
188
+ config (`Dict[str, Any]`):
189
+ A config dictionary from which the Python class is instantiated. Make sure to only load configuration
190
+ files of compatible classes.
191
+ return_unused_kwargs (`bool`, *optional*, defaults to `False`):
192
+ Whether kwargs that are not consumed by the Python class should be returned or not.
193
+ kwargs (remaining dictionary of keyword arguments, *optional*):
194
+ Can be used to update the configuration object (after it is loaded) and initiate the Python class.
195
+ `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
196
+ overwrite the same named arguments in `config`.
197
+
198
+ Returns:
199
+ [`ModelMixin`] or [`SchedulerMixin`]:
200
+ A model or scheduler object instantiated from a config dictionary.
201
+
202
+ Examples:
203
+
204
+ ```python
205
+ >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
206
+
207
+ >>> # Download scheduler from huggingface.co and cache.
208
+ >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
209
+
210
+ >>> # Instantiate DDIM scheduler class with same config as DDPM
211
+ >>> scheduler = DDIMScheduler.from_config(scheduler.config)
212
+
213
+ >>> # Instantiate PNDM scheduler class with same config as DDPM
214
+ >>> scheduler = PNDMScheduler.from_config(scheduler.config)
215
+ ```
216
+ """
217
+ # <===== TO BE REMOVED WITH DEPRECATION
218
+ # TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
219
+ if "pretrained_model_name_or_path" in kwargs:
220
+ config = kwargs.pop("pretrained_model_name_or_path")
221
+
222
+ if config is None:
223
+ raise ValueError("Please make sure to provide a config as the first positional argument.")
224
+ # ======>
225
+
226
+ if not isinstance(config, dict):
227
+ deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
228
+ if "Scheduler" in cls.__name__:
229
+ deprecation_message += (
230
+ f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
231
+ " Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
232
+ " be removed in v1.0.0."
233
+ )
234
+ elif "Model" in cls.__name__:
235
+ deprecation_message += (
236
+ f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
237
+ f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
238
+ " instead. This functionality will be removed in v1.0.0."
239
+ )
240
+ deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
241
+ config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
242
+
243
+ init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
244
+
245
+ # Allow dtype to be specified on initialization
246
+ if "dtype" in unused_kwargs:
247
+ init_dict["dtype"] = unused_kwargs.pop("dtype")
248
+
249
+ # add possible deprecated kwargs
250
+ for deprecated_kwarg in cls._deprecated_kwargs:
251
+ if deprecated_kwarg in unused_kwargs:
252
+ init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
253
+
254
+ # Return model and optionally state and/or unused_kwargs
255
+ model = cls(**init_dict)
256
+
257
+ # make sure to also save config parameters that might be used for compatible classes
258
+ model.register_to_config(**hidden_dict)
259
+
260
+ # add hidden kwargs of compatible classes to unused_kwargs
261
+ unused_kwargs = {**unused_kwargs, **hidden_dict}
262
+
263
+ if return_unused_kwargs:
264
+ return (model, unused_kwargs)
265
+ else:
266
+ return model
267
+
268
+ @classmethod
269
+ def get_config_dict(cls, *args, **kwargs):
270
+ deprecation_message = (
271
+ f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
272
+ " removed in version v1.0.0"
273
+ )
274
+ deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
275
+ return cls.load_config(*args, **kwargs)
276
+
277
+ @classmethod
278
+ def load_config(
279
+ cls,
280
+ pretrained_model_name_or_path: Union[str, os.PathLike],
281
+ return_unused_kwargs=False,
282
+ return_commit_hash=False,
283
+ **kwargs,
284
+ ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
285
+ r"""
286
+ Load a model or scheduler configuration.
287
+
288
+ Parameters:
289
+ pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
290
+ Can be either:
291
+
292
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
293
+ the Hub.
294
+ - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
295
+ [`~ConfigMixin.save_config`].
296
+
297
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
298
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
299
+ is not used.
300
+ force_download (`bool`, *optional*, defaults to `False`):
301
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
302
+ cached versions if they exist.
303
+ resume_download (`bool`, *optional*, defaults to `False`):
304
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
305
+ incompletely downloaded files are deleted.
306
+ proxies (`Dict[str, str]`, *optional*):
307
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
308
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
309
+ output_loading_info(`bool`, *optional*, defaults to `False`):
310
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
311
+ local_files_only (`bool`, *optional*, defaults to `False`):
312
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
313
+ won't be downloaded from the Hub.
314
+ use_auth_token (`str` or *bool*, *optional*):
315
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
316
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
317
+ revision (`str`, *optional*, defaults to `"main"`):
318
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
319
+ allowed by Git.
320
+ subfolder (`str`, *optional*, defaults to `""`):
321
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
322
+ return_unused_kwargs (`bool`, *optional*, defaults to `False):
323
+ Whether unused keyword arguments of the config are returned.
324
+ return_commit_hash (`bool`, *optional*, defaults to `False):
325
+ Whether the `commit_hash` of the loaded configuration are returned.
326
+
327
+ Returns:
328
+ `dict`:
329
+ A dictionary of all the parameters stored in a JSON configuration file.
330
+
331
+ """
332
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
333
+ force_download = kwargs.pop("force_download", False)
334
+ resume_download = kwargs.pop("resume_download", False)
335
+ proxies = kwargs.pop("proxies", None)
336
+ use_auth_token = kwargs.pop("use_auth_token", None)
337
+ local_files_only = kwargs.pop("local_files_only", False)
338
+ revision = kwargs.pop("revision", None)
339
+ _ = kwargs.pop("mirror", None)
340
+ subfolder = kwargs.pop("subfolder", None)
341
+ user_agent = kwargs.pop("user_agent", {})
342
+
343
+ user_agent = {**user_agent, "file_type": "config"}
344
+ user_agent = http_user_agent(user_agent)
345
+
346
+ pretrained_model_name_or_path = str(pretrained_model_name_or_path)
347
+
348
+ if cls.config_name is None:
349
+ raise ValueError(
350
+ "`self.config_name` is not defined. Note that one should not load a config from "
351
+ "`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
352
+ )
353
+
354
+ if os.path.isfile(pretrained_model_name_or_path):
355
+ config_file = pretrained_model_name_or_path
356
+ elif os.path.isdir(pretrained_model_name_or_path):
357
+ if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
358
+ # Load from a PyTorch checkpoint
359
+ config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
360
+ elif subfolder is not None and os.path.isfile(
361
+ os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
362
+ ):
363
+ config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
364
+ else:
365
+ raise EnvironmentError(
366
+ f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
367
+ )
368
+ else:
369
+ try:
370
+ # Load from URL or cache if already cached
371
+ config_file = hf_hub_download(
372
+ pretrained_model_name_or_path,
373
+ filename=cls.config_name,
374
+ cache_dir=cache_dir,
375
+ force_download=force_download,
376
+ proxies=proxies,
377
+ resume_download=resume_download,
378
+ local_files_only=local_files_only,
379
+ use_auth_token=use_auth_token,
380
+ user_agent=user_agent,
381
+ subfolder=subfolder,
382
+ revision=revision,
383
+ )
384
+ except RepositoryNotFoundError:
385
+ raise EnvironmentError(
386
+ f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
387
+ " listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
388
+ " token having permission to this repo with `use_auth_token` or log in with `huggingface-cli"
389
+ " login`."
390
+ )
391
+ except RevisionNotFoundError:
392
+ raise EnvironmentError(
393
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
394
+ " this model name. Check the model page at"
395
+ f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
396
+ )
397
+ except EntryNotFoundError:
398
+ raise EnvironmentError(
399
+ f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
400
+ )
401
+ except HTTPError as err:
402
+ raise EnvironmentError(
403
+ "There was a specific connection error when trying to load"
404
+ f" {pretrained_model_name_or_path}:\n{err}"
405
+ )
406
+ except ValueError:
407
+ raise EnvironmentError(
408
+ f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
409
+ f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
410
+ f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
411
+ " run the library in offline mode at"
412
+ " 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
413
+ )
414
+ except EnvironmentError:
415
+ raise EnvironmentError(
416
+ f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
417
+ "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
418
+ f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
419
+ f"containing a {cls.config_name} file"
420
+ )
421
+
422
+ try:
423
+ # Load config dict
424
+ config_dict = cls._dict_from_json_file(config_file)
425
+
426
+ commit_hash = extract_commit_hash(config_file)
427
+ except (json.JSONDecodeError, UnicodeDecodeError):
428
+ raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
429
+
430
+ if not (return_unused_kwargs or return_commit_hash):
431
+ return config_dict
432
+
433
+ outputs = (config_dict,)
434
+
435
+ if return_unused_kwargs:
436
+ outputs += (kwargs,)
437
+
438
+ if return_commit_hash:
439
+ outputs += (commit_hash,)
440
+
441
+ return outputs
442
+
443
+ @staticmethod
444
+ def _get_init_keys(cls):
445
+ return set(dict(inspect.signature(cls.__init__).parameters).keys())
446
+
447
+ @classmethod
448
+ def extract_init_dict(cls, config_dict, **kwargs):
449
+ # Skip keys that were not present in the original config, so default __init__ values were used
450
+ used_defaults = config_dict.get("_use_default_values", [])
451
+ config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
452
+
453
+ # 0. Copy origin config dict
454
+ original_dict = dict(config_dict.items())
455
+
456
+ # 1. Retrieve expected config attributes from __init__ signature
457
+ expected_keys = cls._get_init_keys(cls)
458
+ expected_keys.remove("self")
459
+ # remove general kwargs if present in dict
460
+ if "kwargs" in expected_keys:
461
+ expected_keys.remove("kwargs")
462
+ # remove flax internal keys
463
+ if hasattr(cls, "_flax_internal_args"):
464
+ for arg in cls._flax_internal_args:
465
+ expected_keys.remove(arg)
466
+
467
+ # 2. Remove attributes that cannot be expected from expected config attributes
468
+ # remove keys to be ignored
469
+ if len(cls.ignore_for_config) > 0:
470
+ expected_keys = expected_keys - set(cls.ignore_for_config)
471
+
472
+ # load diffusers library to import compatible and original scheduler
473
+ diffusers_library = importlib.import_module(__name__.split(".")[0])
474
+
475
+ if cls.has_compatibles:
476
+ compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
477
+ else:
478
+ compatible_classes = []
479
+
480
+ expected_keys_comp_cls = set()
481
+ for c in compatible_classes:
482
+ expected_keys_c = cls._get_init_keys(c)
483
+ expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
484
+ expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
485
+ config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
486
+
487
+ # remove attributes from orig class that cannot be expected
488
+ orig_cls_name = config_dict.pop("_class_name", cls.__name__)
489
+ if (
490
+ isinstance(orig_cls_name, str)
491
+ and orig_cls_name != cls.__name__
492
+ and hasattr(diffusers_library, orig_cls_name)
493
+ ):
494
+ orig_cls = getattr(diffusers_library, orig_cls_name)
495
+ unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
496
+ config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
497
+ elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
498
+ raise ValueError(
499
+ "Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
500
+ )
501
+
502
+ # remove private attributes
503
+ config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
504
+
505
+ # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
506
+ init_dict = {}
507
+ for key in expected_keys:
508
+ # if config param is passed to kwarg and is present in config dict
509
+ # it should overwrite existing config dict key
510
+ if key in kwargs and key in config_dict:
511
+ config_dict[key] = kwargs.pop(key)
512
+
513
+ if key in kwargs:
514
+ # overwrite key
515
+ init_dict[key] = kwargs.pop(key)
516
+ elif key in config_dict:
517
+ # use value from config dict
518
+ init_dict[key] = config_dict.pop(key)
519
+
520
+ # 4. Give nice warning if unexpected values have been passed
521
+ if len(config_dict) > 0:
522
+ logger.warning(
523
+ f"The config attributes {config_dict} were passed to {cls.__name__}, "
524
+ "but are not expected and will be ignored. Please verify your "
525
+ f"{cls.config_name} configuration file."
526
+ )
527
+
528
+ # 5. Give nice info if config attributes are initiliazed to default because they have not been passed
529
+ passed_keys = set(init_dict.keys())
530
+ if len(expected_keys - passed_keys) > 0:
531
+ logger.info(
532
+ f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
533
+ )
534
+
535
+ # 6. Define unused keyword arguments
536
+ unused_kwargs = {**config_dict, **kwargs}
537
+
538
+ # 7. Define "hidden" config parameters that were saved for compatible classes
539
+ hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
540
+
541
+ return init_dict, unused_kwargs, hidden_config_dict
542
+
543
+ @classmethod
544
+ def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
545
+ with open(json_file, "r", encoding="utf-8") as reader:
546
+ text = reader.read()
547
+ return json.loads(text)
548
+
549
+ def __repr__(self):
550
+ return f"{self.__class__.__name__} {self.to_json_string()}"
551
+
552
+ @property
553
+ def config(self) -> Dict[str, Any]:
554
+ """
555
+ Returns the config of the class as a frozen dictionary
556
+
557
+ Returns:
558
+ `Dict[str, Any]`: Config of the class.
559
+ """
560
+ return self._internal_dict
561
+
562
+ def to_json_string(self) -> str:
563
+ """
564
+ Serializes the configuration instance to a JSON string.
565
+
566
+ Returns:
567
+ `str`:
568
+ String containing all the attributes that make up the configuration instance in JSON format.
569
+ """
570
+ config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
571
+ config_dict["_class_name"] = self.__class__.__name__
572
+ config_dict["_diffusers_version"] = __version__
573
+
574
+ def to_json_saveable(value):
575
+ if isinstance(value, np.ndarray):
576
+ value = value.tolist()
577
+ elif isinstance(value, PosixPath):
578
+ value = str(value)
579
+ return value
580
+
581
+ config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
582
+ # Don't save "_ignore_files" or "_use_default_values"
583
+ config_dict.pop("_ignore_files", None)
584
+ config_dict.pop("_use_default_values", None)
585
+
586
+ return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
587
+
588
+ def to_json_file(self, json_file_path: Union[str, os.PathLike]):
589
+ """
590
+ Save the configuration instance's parameters to a JSON file.
591
+
592
+ Args:
593
+ json_file_path (`str` or `os.PathLike`):
594
+ Path to the JSON file to save a configuration instance's parameters.
595
+ """
596
+ with open(json_file_path, "w", encoding="utf-8") as writer:
597
+ writer.write(self.to_json_string())
598
+
599
+
600
+ def register_to_config(init):
601
+ r"""
602
+ Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
603
+ automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
604
+ shouldn't be registered in the config, use the `ignore_for_config` class variable
605
+
606
+ Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
607
+ """
608
+
609
+ @functools.wraps(init)
610
+ def inner_init(self, *args, **kwargs):
611
+ # Ignore private kwargs in the init.
612
+ init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
613
+ config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
614
+ if not isinstance(self, ConfigMixin):
615
+ raise RuntimeError(
616
+ f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
617
+ "not inherit from `ConfigMixin`."
618
+ )
619
+
620
+ ignore = getattr(self, "ignore_for_config", [])
621
+ # Get positional arguments aligned with kwargs
622
+ new_kwargs = {}
623
+ signature = inspect.signature(init)
624
+ parameters = {
625
+ name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
626
+ }
627
+ for arg, name in zip(args, parameters.keys()):
628
+ new_kwargs[name] = arg
629
+
630
+ # Then add all kwargs
631
+ new_kwargs.update(
632
+ {
633
+ k: init_kwargs.get(k, default)
634
+ for k, default in parameters.items()
635
+ if k not in ignore and k not in new_kwargs
636
+ }
637
+ )
638
+
639
+ # Take note of the parameters that were not present in the loaded config
640
+ if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
641
+ new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
642
+
643
+ new_kwargs = {**config_init_kwargs, **new_kwargs}
644
+ getattr(self, "register_to_config")(**new_kwargs)
645
+ init(self, *args, **init_kwargs)
646
+
647
+ return inner_init
648
+
649
+
650
+ def flax_register_to_config(cls):
651
+ original_init = cls.__init__
652
+
653
+ @functools.wraps(original_init)
654
+ def init(self, *args, **kwargs):
655
+ if not isinstance(self, ConfigMixin):
656
+ raise RuntimeError(
657
+ f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
658
+ "not inherit from `ConfigMixin`."
659
+ )
660
+
661
+ # Ignore private kwargs in the init. Retrieve all passed attributes
662
+ init_kwargs = dict(kwargs.items())
663
+
664
+ # Retrieve default values
665
+ fields = dataclasses.fields(self)
666
+ default_kwargs = {}
667
+ for field in fields:
668
+ # ignore flax specific attributes
669
+ if field.name in self._flax_internal_args:
670
+ continue
671
+ if type(field.default) == dataclasses._MISSING_TYPE:
672
+ default_kwargs[field.name] = None
673
+ else:
674
+ default_kwargs[field.name] = getattr(self, field.name)
675
+
676
+ # Make sure init_kwargs override default kwargs
677
+ new_kwargs = {**default_kwargs, **init_kwargs}
678
+ # dtype should be part of `init_kwargs`, but not `new_kwargs`
679
+ if "dtype" in new_kwargs:
680
+ new_kwargs.pop("dtype")
681
+
682
+ # Get positional arguments aligned with kwargs
683
+ for i, arg in enumerate(args):
684
+ name = fields[i].name
685
+ new_kwargs[name] = arg
686
+
687
+ # Take note of the parameters that were not present in the loaded config
688
+ if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
689
+ new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
690
+
691
+ getattr(self, "register_to_config")(**new_kwargs)
692
+ original_init(self, *args, **kwargs)
693
+
694
+ cls.__init__ = init
695
+ return cls
diffusers/dependency_versions_check.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.11.0",
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.19.4",
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
+ "omegaconf": "omegaconf",
26
+ "parameterized": "parameterized",
27
+ "peft": "peft>=0.6.0",
28
+ "protobuf": "protobuf>=3.20.3,<4",
29
+ "pytest": "pytest",
30
+ "pytest-timeout": "pytest-timeout",
31
+ "pytest-xdist": "pytest-xdist",
32
+ "python": "python>=3.8.0",
33
+ "ruff": "ruff>=0.1.5,<=0.2",
34
+ "safetensors": "safetensors>=0.3.1",
35
+ "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
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
+ }
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/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .rl import ValueGuidedRLPipeline
diffusers/experimental/rl/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .value_guided_sampling import ValueGuidedRLPipeline
diffusers/experimental/rl/value_guided_sampling.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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.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
+ self.value_function = value_function
53
+ self.unet = unet
54
+ self.scheduler = scheduler
55
+ self.env = env
56
+ self.data = env.get_dataset()
57
+ self.means = {}
58
+ for key in self.data.keys():
59
+ try:
60
+ self.means[key] = self.data[key].mean()
61
+ except: # noqa: E722
62
+ pass
63
+ self.stds = {}
64
+ for key in self.data.keys():
65
+ try:
66
+ self.stds[key] = self.data[key].std()
67
+ except: # noqa: E722
68
+ pass
69
+ self.state_dim = env.observation_space.shape[0]
70
+ self.action_dim = env.action_space.shape[0]
71
+
72
+ def normalize(self, x_in, key):
73
+ return (x_in - self.means[key]) / self.stds[key]
74
+
75
+ def de_normalize(self, x_in, key):
76
+ return x_in * self.stds[key] + self.means[key]
77
+
78
+ def to_torch(self, x_in):
79
+ if isinstance(x_in, dict):
80
+ return {k: self.to_torch(v) for k, v in x_in.items()}
81
+ elif torch.is_tensor(x_in):
82
+ return x_in.to(self.unet.device)
83
+ return torch.tensor(x_in, device=self.unet.device)
84
+
85
+ def reset_x0(self, x_in, cond, act_dim):
86
+ for key, val in cond.items():
87
+ x_in[:, key, act_dim:] = val.clone()
88
+ return x_in
89
+
90
+ def run_diffusion(self, x, conditions, n_guide_steps, scale):
91
+ batch_size = x.shape[0]
92
+ y = None
93
+ for i in tqdm.tqdm(self.scheduler.timesteps):
94
+ # create batch of timesteps to pass into model
95
+ timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
96
+ for _ in range(n_guide_steps):
97
+ with torch.enable_grad():
98
+ x.requires_grad_()
99
+
100
+ # permute to match dimension for pre-trained models
101
+ y = self.value_function(x.permute(0, 2, 1), timesteps).sample
102
+ grad = torch.autograd.grad([y.sum()], [x])[0]
103
+
104
+ posterior_variance = self.scheduler._get_variance(i)
105
+ model_std = torch.exp(0.5 * posterior_variance)
106
+ grad = model_std * grad
107
+
108
+ grad[timesteps < 2] = 0
109
+ x = x.detach()
110
+ x = x + scale * grad
111
+ x = self.reset_x0(x, conditions, self.action_dim)
112
+
113
+ prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
114
+
115
+ # TODO: verify deprecation of this kwarg
116
+ x = self.scheduler.step(prev_x, i, x, predict_epsilon=False)["prev_sample"]
117
+
118
+ # apply conditions to the trajectory (set the initial state)
119
+ x = self.reset_x0(x, conditions, self.action_dim)
120
+ x = self.to_torch(x)
121
+ return x, y
122
+
123
+ def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
124
+ # normalize the observations and create batch dimension
125
+ obs = self.normalize(obs, "observations")
126
+ obs = obs[None].repeat(batch_size, axis=0)
127
+
128
+ conditions = {0: self.to_torch(obs)}
129
+ shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
130
+
131
+ # generate initial noise and apply our conditions (to make the trajectories start at current state)
132
+ x1 = randn_tensor(shape, device=self.unet.device)
133
+ x = self.reset_x0(x1, conditions, self.action_dim)
134
+ x = self.to_torch(x)
135
+
136
+ # run the diffusion process
137
+ x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
138
+
139
+ # sort output trajectories by value
140
+ sorted_idx = y.argsort(0, descending=True).squeeze()
141
+ sorted_values = x[sorted_idx]
142
+ actions = sorted_values[:, :, : self.action_dim]
143
+ actions = actions.detach().cpu().numpy()
144
+ denorm_actions = self.de_normalize(actions, key="actions")
145
+
146
+ # select the action with the highest value
147
+ if y is not None:
148
+ selected_index = 0
149
+ else:
150
+ # if we didn't run value guiding, select a random action
151
+ selected_index = np.random.randint(0, batch_size)
152
+
153
+ denorm_actions = denorm_actions[selected_index, 0]
154
+ return denorm_actions
diffusers/image_processor.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 warnings
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import PIL.Image
20
+ import torch
21
+ from PIL import Image
22
+
23
+ from .configuration_utils import ConfigMixin, register_to_config
24
+ from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
25
+
26
+
27
+ PipelineImageInput = Union[
28
+ PIL.Image.Image,
29
+ np.ndarray,
30
+ torch.FloatTensor,
31
+ List[PIL.Image.Image],
32
+ List[np.ndarray],
33
+ List[torch.FloatTensor],
34
+ ]
35
+
36
+ PipelineDepthInput = Union[
37
+ PIL.Image.Image,
38
+ np.ndarray,
39
+ torch.FloatTensor,
40
+ List[PIL.Image.Image],
41
+ List[np.ndarray],
42
+ List[torch.FloatTensor],
43
+ ]
44
+
45
+
46
+ class VaeImageProcessor(ConfigMixin):
47
+ """
48
+ Image processor for VAE.
49
+
50
+ Args:
51
+ do_resize (`bool`, *optional*, defaults to `True`):
52
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
53
+ `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
54
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
55
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
56
+ resample (`str`, *optional*, defaults to `lanczos`):
57
+ Resampling filter to use when resizing the image.
58
+ do_normalize (`bool`, *optional*, defaults to `True`):
59
+ Whether to normalize the image to [-1,1].
60
+ do_binarize (`bool`, *optional*, defaults to `False`):
61
+ Whether to binarize the image to 0/1.
62
+ do_convert_rgb (`bool`, *optional*, defaults to be `False`):
63
+ Whether to convert the images to RGB format.
64
+ do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
65
+ Whether to convert the images to grayscale format.
66
+ """
67
+
68
+ config_name = CONFIG_NAME
69
+
70
+ @register_to_config
71
+ def __init__(
72
+ self,
73
+ do_resize: bool = True,
74
+ vae_scale_factor: int = 8,
75
+ resample: str = "lanczos",
76
+ do_normalize: bool = True,
77
+ do_binarize: bool = False,
78
+ do_convert_rgb: bool = False,
79
+ do_convert_grayscale: bool = False,
80
+ ):
81
+ super().__init__()
82
+ if do_convert_rgb and do_convert_grayscale:
83
+ raise ValueError(
84
+ "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
85
+ " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
86
+ " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
87
+ )
88
+ self.config.do_convert_rgb = False
89
+
90
+ @staticmethod
91
+ def numpy_to_pil(images: np.ndarray) -> PIL.Image.Image:
92
+ """
93
+ Convert a numpy image or a batch of images to a PIL image.
94
+ """
95
+ if images.ndim == 3:
96
+ images = images[None, ...]
97
+ images = (images * 255).round().astype("uint8")
98
+ if images.shape[-1] == 1:
99
+ # special case for grayscale (single channel) images
100
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
101
+ else:
102
+ pil_images = [Image.fromarray(image) for image in images]
103
+
104
+ return pil_images
105
+
106
+ @staticmethod
107
+ def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
108
+ """
109
+ Convert a PIL image or a list of PIL images to NumPy arrays.
110
+ """
111
+ if not isinstance(images, list):
112
+ images = [images]
113
+ images = [np.array(image).astype(np.float32) / 255.0 for image in images]
114
+ images = np.stack(images, axis=0)
115
+
116
+ return images
117
+
118
+ @staticmethod
119
+ def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
120
+ """
121
+ Convert a NumPy image to a PyTorch tensor.
122
+ """
123
+ if images.ndim == 3:
124
+ images = images[..., None]
125
+
126
+ images = torch.from_numpy(images.transpose(0, 3, 1, 2))
127
+ return images
128
+
129
+ @staticmethod
130
+ def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
131
+ """
132
+ Convert a PyTorch tensor to a NumPy image.
133
+ """
134
+ images = images.cpu().permute(0, 2, 3, 1).float().numpy()
135
+ return images
136
+
137
+ @staticmethod
138
+ def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
139
+ """
140
+ Normalize an image array to [-1,1].
141
+ """
142
+ return 2.0 * images - 1.0
143
+
144
+ @staticmethod
145
+ def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
146
+ """
147
+ Denormalize an image array to [0,1].
148
+ """
149
+ return (images / 2 + 0.5).clamp(0, 1)
150
+
151
+ @staticmethod
152
+ def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
153
+ """
154
+ Converts a PIL image to RGB format.
155
+ """
156
+ image = image.convert("RGB")
157
+
158
+ return image
159
+
160
+ @staticmethod
161
+ def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
162
+ """
163
+ Converts a PIL image to grayscale format.
164
+ """
165
+ image = image.convert("L")
166
+
167
+ return image
168
+
169
+ def get_default_height_width(
170
+ self,
171
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
172
+ height: Optional[int] = None,
173
+ width: Optional[int] = None,
174
+ ) -> Tuple[int, int]:
175
+ """
176
+ This function return the height and width that are downscaled to the next integer multiple of
177
+ `vae_scale_factor`.
178
+
179
+ Args:
180
+ image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
181
+ The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
182
+ shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
183
+ have shape `[batch, channel, height, width]`.
184
+ height (`int`, *optional*, defaults to `None`):
185
+ The height in preprocessed image. If `None`, will use the height of `image` input.
186
+ width (`int`, *optional*`, defaults to `None`):
187
+ The width in preprocessed. If `None`, will use the width of the `image` input.
188
+ """
189
+
190
+ if height is None:
191
+ if isinstance(image, PIL.Image.Image):
192
+ height = image.height
193
+ elif isinstance(image, torch.Tensor):
194
+ height = image.shape[2]
195
+ else:
196
+ height = image.shape[1]
197
+
198
+ if width is None:
199
+ if isinstance(image, PIL.Image.Image):
200
+ width = image.width
201
+ elif isinstance(image, torch.Tensor):
202
+ width = image.shape[3]
203
+ else:
204
+ width = image.shape[2]
205
+
206
+ width, height = (
207
+ x - x % self.config.vae_scale_factor for x in (width, height)
208
+ ) # resize to integer multiple of vae_scale_factor
209
+
210
+ return height, width
211
+
212
+ def resize(
213
+ self,
214
+ image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
215
+ height: Optional[int] = None,
216
+ width: Optional[int] = None,
217
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
218
+ """
219
+ Resize image.
220
+
221
+ Args:
222
+ image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
223
+ The image input, can be a PIL image, numpy array or pytorch tensor.
224
+ height (`int`, *optional*, defaults to `None`):
225
+ The height to resize to.
226
+ width (`int`, *optional*`, defaults to `None`):
227
+ The width to resize to.
228
+
229
+ Returns:
230
+ `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
231
+ The resized image.
232
+ """
233
+ if isinstance(image, PIL.Image.Image):
234
+ image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
235
+ elif isinstance(image, torch.Tensor):
236
+ image = torch.nn.functional.interpolate(
237
+ image,
238
+ size=(height, width),
239
+ )
240
+ elif isinstance(image, np.ndarray):
241
+ image = self.numpy_to_pt(image)
242
+ image = torch.nn.functional.interpolate(
243
+ image,
244
+ size=(height, width),
245
+ )
246
+ image = self.pt_to_numpy(image)
247
+ return image
248
+
249
+ def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
250
+ """
251
+ Create a mask.
252
+
253
+ Args:
254
+ image (`PIL.Image.Image`):
255
+ The image input, should be a PIL image.
256
+
257
+ Returns:
258
+ `PIL.Image.Image`:
259
+ The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
260
+ """
261
+ image[image < 0.5] = 0
262
+ image[image >= 0.5] = 1
263
+ return image
264
+
265
+ def preprocess(
266
+ self,
267
+ image: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
268
+ height: Optional[int] = None,
269
+ width: Optional[int] = None,
270
+ ) -> torch.Tensor:
271
+ """
272
+ Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
273
+ """
274
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
275
+
276
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
277
+ if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
278
+ if isinstance(image, torch.Tensor):
279
+ # if image is a pytorch tensor could have 2 possible shapes:
280
+ # 1. batch x height x width: we should insert the channel dimension at position 1
281
+ # 2. channnel x height x width: we should insert batch dimension at position 0,
282
+ # however, since both channel and batch dimension has same size 1, it is same to insert at position 1
283
+ # for simplicity, we insert a dimension of size 1 at position 1 for both cases
284
+ image = image.unsqueeze(1)
285
+ else:
286
+ # if it is a numpy array, it could have 2 possible shapes:
287
+ # 1. batch x height x width: insert channel dimension on last position
288
+ # 2. height x width x channel: insert batch dimension on first position
289
+ if image.shape[-1] == 1:
290
+ image = np.expand_dims(image, axis=0)
291
+ else:
292
+ image = np.expand_dims(image, axis=-1)
293
+
294
+ if isinstance(image, supported_formats):
295
+ image = [image]
296
+ elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
297
+ raise ValueError(
298
+ f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
299
+ )
300
+
301
+ if isinstance(image[0], PIL.Image.Image):
302
+ if self.config.do_convert_rgb:
303
+ image = [self.convert_to_rgb(i) for i in image]
304
+ elif self.config.do_convert_grayscale:
305
+ image = [self.convert_to_grayscale(i) for i in image]
306
+ if self.config.do_resize:
307
+ height, width = self.get_default_height_width(image[0], height, width)
308
+ image = [self.resize(i, height, width) for i in image]
309
+ image = self.pil_to_numpy(image) # to np
310
+ image = self.numpy_to_pt(image) # to pt
311
+
312
+ elif isinstance(image[0], np.ndarray):
313
+ image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
314
+
315
+ image = self.numpy_to_pt(image)
316
+
317
+ height, width = self.get_default_height_width(image, height, width)
318
+ if self.config.do_resize:
319
+ image = self.resize(image, height, width)
320
+
321
+ elif isinstance(image[0], torch.Tensor):
322
+ image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
323
+
324
+ if self.config.do_convert_grayscale and image.ndim == 3:
325
+ image = image.unsqueeze(1)
326
+
327
+ channel = image.shape[1]
328
+ # don't need any preprocess if the image is latents
329
+ if channel == 4:
330
+ return image
331
+
332
+ height, width = self.get_default_height_width(image, height, width)
333
+ if self.config.do_resize:
334
+ image = self.resize(image, height, width)
335
+
336
+ # expected range [0,1], normalize to [-1,1]
337
+ do_normalize = self.config.do_normalize
338
+ if do_normalize and image.min() < 0:
339
+ warnings.warn(
340
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
341
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
342
+ FutureWarning,
343
+ )
344
+ do_normalize = False
345
+
346
+ if do_normalize:
347
+ image = self.normalize(image)
348
+
349
+ if self.config.do_binarize:
350
+ image = self.binarize(image)
351
+
352
+ return image
353
+
354
+ def postprocess(
355
+ self,
356
+ image: torch.FloatTensor,
357
+ output_type: str = "pil",
358
+ do_denormalize: Optional[List[bool]] = None,
359
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
360
+ """
361
+ Postprocess the image output from tensor to `output_type`.
362
+
363
+ Args:
364
+ image (`torch.FloatTensor`):
365
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
366
+ output_type (`str`, *optional*, defaults to `pil`):
367
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
368
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
369
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
370
+ `VaeImageProcessor` config.
371
+
372
+ Returns:
373
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
374
+ The postprocessed image.
375
+ """
376
+ if not isinstance(image, torch.Tensor):
377
+ raise ValueError(
378
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
379
+ )
380
+ if output_type not in ["latent", "pt", "np", "pil"]:
381
+ deprecation_message = (
382
+ 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: "
383
+ "`pil`, `np`, `pt`, `latent`"
384
+ )
385
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
386
+ output_type = "np"
387
+
388
+ if output_type == "latent":
389
+ return image
390
+
391
+ if do_denormalize is None:
392
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
393
+
394
+ image = torch.stack(
395
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
396
+ )
397
+
398
+ if output_type == "pt":
399
+ return image
400
+
401
+ image = self.pt_to_numpy(image)
402
+
403
+ if output_type == "np":
404
+ return image
405
+
406
+ if output_type == "pil":
407
+ return self.numpy_to_pil(image)
408
+
409
+
410
+ class VaeImageProcessorLDM3D(VaeImageProcessor):
411
+ """
412
+ Image processor for VAE LDM3D.
413
+
414
+ Args:
415
+ do_resize (`bool`, *optional*, defaults to `True`):
416
+ Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
417
+ vae_scale_factor (`int`, *optional*, defaults to `8`):
418
+ VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
419
+ resample (`str`, *optional*, defaults to `lanczos`):
420
+ Resampling filter to use when resizing the image.
421
+ do_normalize (`bool`, *optional*, defaults to `True`):
422
+ Whether to normalize the image to [-1,1].
423
+ """
424
+
425
+ config_name = CONFIG_NAME
426
+
427
+ @register_to_config
428
+ def __init__(
429
+ self,
430
+ do_resize: bool = True,
431
+ vae_scale_factor: int = 8,
432
+ resample: str = "lanczos",
433
+ do_normalize: bool = True,
434
+ ):
435
+ super().__init__()
436
+
437
+ @staticmethod
438
+ def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
439
+ """
440
+ Convert a NumPy image or a batch of images to a PIL image.
441
+ """
442
+ if images.ndim == 3:
443
+ images = images[None, ...]
444
+ images = (images * 255).round().astype("uint8")
445
+ if images.shape[-1] == 1:
446
+ # special case for grayscale (single channel) images
447
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
448
+ else:
449
+ pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
450
+
451
+ return pil_images
452
+
453
+ @staticmethod
454
+ def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
455
+ """
456
+ Convert a PIL image or a list of PIL images to NumPy arrays.
457
+ """
458
+ if not isinstance(images, list):
459
+ images = [images]
460
+
461
+ images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
462
+ images = np.stack(images, axis=0)
463
+ return images
464
+
465
+ @staticmethod
466
+ def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
467
+ """
468
+ Args:
469
+ image: RGB-like depth image
470
+
471
+ Returns: depth map
472
+
473
+ """
474
+ return image[:, :, 1] * 2**8 + image[:, :, 2]
475
+
476
+ def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
477
+ """
478
+ Convert a NumPy depth image or a batch of images to a PIL image.
479
+ """
480
+ if images.ndim == 3:
481
+ images = images[None, ...]
482
+ images_depth = images[:, :, :, 3:]
483
+ if images.shape[-1] == 6:
484
+ images_depth = (images_depth * 255).round().astype("uint8")
485
+ pil_images = [
486
+ Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
487
+ ]
488
+ elif images.shape[-1] == 4:
489
+ images_depth = (images_depth * 65535.0).astype(np.uint16)
490
+ pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
491
+ else:
492
+ raise Exception("Not supported")
493
+
494
+ return pil_images
495
+
496
+ def postprocess(
497
+ self,
498
+ image: torch.FloatTensor,
499
+ output_type: str = "pil",
500
+ do_denormalize: Optional[List[bool]] = None,
501
+ ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
502
+ """
503
+ Postprocess the image output from tensor to `output_type`.
504
+
505
+ Args:
506
+ image (`torch.FloatTensor`):
507
+ The image input, should be a pytorch tensor with shape `B x C x H x W`.
508
+ output_type (`str`, *optional*, defaults to `pil`):
509
+ The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
510
+ do_denormalize (`List[bool]`, *optional*, defaults to `None`):
511
+ Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
512
+ `VaeImageProcessor` config.
513
+
514
+ Returns:
515
+ `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
516
+ The postprocessed image.
517
+ """
518
+ if not isinstance(image, torch.Tensor):
519
+ raise ValueError(
520
+ f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
521
+ )
522
+ if output_type not in ["latent", "pt", "np", "pil"]:
523
+ deprecation_message = (
524
+ 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: "
525
+ "`pil`, `np`, `pt`, `latent`"
526
+ )
527
+ deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
528
+ output_type = "np"
529
+
530
+ if do_denormalize is None:
531
+ do_denormalize = [self.config.do_normalize] * image.shape[0]
532
+
533
+ image = torch.stack(
534
+ [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
535
+ )
536
+
537
+ image = self.pt_to_numpy(image)
538
+
539
+ if output_type == "np":
540
+ if image.shape[-1] == 6:
541
+ image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
542
+ else:
543
+ image_depth = image[:, :, :, 3:]
544
+ return image[:, :, :, :3], image_depth
545
+
546
+ if output_type == "pil":
547
+ return self.numpy_to_pil(image), self.numpy_to_depth(image)
548
+ else:
549
+ raise Exception(f"This type {output_type} is not supported")
550
+
551
+ def preprocess(
552
+ self,
553
+ rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
554
+ depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
555
+ height: Optional[int] = None,
556
+ width: Optional[int] = None,
557
+ target_res: Optional[int] = None,
558
+ ) -> torch.Tensor:
559
+ """
560
+ Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
561
+ """
562
+ supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
563
+
564
+ # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
565
+ if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
566
+ raise Exception("This is not yet supported")
567
+
568
+ if isinstance(rgb, supported_formats):
569
+ rgb = [rgb]
570
+ depth = [depth]
571
+ elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
572
+ raise ValueError(
573
+ f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
574
+ )
575
+
576
+ if isinstance(rgb[0], PIL.Image.Image):
577
+ if self.config.do_convert_rgb:
578
+ raise Exception("This is not yet supported")
579
+ # rgb = [self.convert_to_rgb(i) for i in rgb]
580
+ # depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
581
+ if self.config.do_resize or target_res:
582
+ height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
583
+ rgb = [self.resize(i, height, width) for i in rgb]
584
+ depth = [self.resize(i, height, width) for i in depth]
585
+ rgb = self.pil_to_numpy(rgb) # to np
586
+ rgb = self.numpy_to_pt(rgb) # to pt
587
+
588
+ depth = self.depth_pil_to_numpy(depth) # to np
589
+ depth = self.numpy_to_pt(depth) # to pt
590
+
591
+ elif isinstance(rgb[0], np.ndarray):
592
+ rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
593
+ rgb = self.numpy_to_pt(rgb)
594
+ height, width = self.get_default_height_width(rgb, height, width)
595
+ if self.config.do_resize:
596
+ rgb = self.resize(rgb, height, width)
597
+
598
+ depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
599
+ depth = self.numpy_to_pt(depth)
600
+ height, width = self.get_default_height_width(depth, height, width)
601
+ if self.config.do_resize:
602
+ depth = self.resize(depth, height, width)
603
+
604
+ elif isinstance(rgb[0], torch.Tensor):
605
+ raise Exception("This is not yet supported")
606
+ # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
607
+
608
+ # if self.config.do_convert_grayscale and rgb.ndim == 3:
609
+ # rgb = rgb.unsqueeze(1)
610
+
611
+ # channel = rgb.shape[1]
612
+
613
+ # height, width = self.get_default_height_width(rgb, height, width)
614
+ # if self.config.do_resize:
615
+ # rgb = self.resize(rgb, height, width)
616
+
617
+ # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
618
+
619
+ # if self.config.do_convert_grayscale and depth.ndim == 3:
620
+ # depth = depth.unsqueeze(1)
621
+
622
+ # channel = depth.shape[1]
623
+ # # don't need any preprocess if the image is latents
624
+ # if depth == 4:
625
+ # return rgb, depth
626
+
627
+ # height, width = self.get_default_height_width(depth, height, width)
628
+ # if self.config.do_resize:
629
+ # depth = self.resize(depth, height, width)
630
+ # expected range [0,1], normalize to [-1,1]
631
+ do_normalize = self.config.do_normalize
632
+ if rgb.min() < 0 and do_normalize:
633
+ warnings.warn(
634
+ "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
635
+ f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
636
+ FutureWarning,
637
+ )
638
+ do_normalize = False
639
+
640
+ if do_normalize:
641
+ rgb = self.normalize(rgb)
642
+ depth = self.normalize(depth)
643
+
644
+ if self.config.do_binarize:
645
+ rgb = self.binarize(rgb)
646
+ depth = self.binarize(depth)
647
+
648
+ return rgb, depth
diffusers/loaders/__init__.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TYPE_CHECKING
2
+
3
+ from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
4
+ from ..utils.import_utils import is_torch_available, is_transformers_available
5
+
6
+
7
+ def text_encoder_lora_state_dict(text_encoder):
8
+ deprecate(
9
+ "text_encoder_load_state_dict in `models`",
10
+ "0.27.0",
11
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
12
+ )
13
+ state_dict = {}
14
+
15
+ for name, module in text_encoder_attn_modules(text_encoder):
16
+ for k, v in module.q_proj.lora_linear_layer.state_dict().items():
17
+ state_dict[f"{name}.q_proj.lora_linear_layer.{k}"] = v
18
+
19
+ for k, v in module.k_proj.lora_linear_layer.state_dict().items():
20
+ state_dict[f"{name}.k_proj.lora_linear_layer.{k}"] = v
21
+
22
+ for k, v in module.v_proj.lora_linear_layer.state_dict().items():
23
+ state_dict[f"{name}.v_proj.lora_linear_layer.{k}"] = v
24
+
25
+ for k, v in module.out_proj.lora_linear_layer.state_dict().items():
26
+ state_dict[f"{name}.out_proj.lora_linear_layer.{k}"] = v
27
+
28
+ return state_dict
29
+
30
+
31
+ if is_transformers_available():
32
+
33
+ def text_encoder_attn_modules(text_encoder):
34
+ deprecate(
35
+ "text_encoder_attn_modules in `models`",
36
+ "0.27.0",
37
+ "`text_encoder_lora_state_dict` is deprecated and will be removed in 0.27.0. Make sure to retrieve the weights using `get_peft_model`. See https://huggingface.co/docs/peft/v0.6.2/en/quicktour#peftmodel for more information.",
38
+ )
39
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
40
+
41
+ attn_modules = []
42
+
43
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
44
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
45
+ name = f"text_model.encoder.layers.{i}.self_attn"
46
+ mod = layer.self_attn
47
+ attn_modules.append((name, mod))
48
+ else:
49
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
50
+
51
+ return attn_modules
52
+
53
+
54
+ _import_structure = {}
55
+
56
+ if is_torch_available():
57
+ _import_structure["single_file"] = ["FromOriginalControlnetMixin", "FromOriginalVAEMixin"]
58
+ _import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
59
+ _import_structure["utils"] = ["AttnProcsLayers"]
60
+
61
+ if is_transformers_available():
62
+ _import_structure["single_file"].extend(["FromSingleFileMixin"])
63
+ _import_structure["lora"] = ["LoraLoaderMixin", "StableDiffusionXLLoraLoaderMixin"]
64
+ _import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
65
+ _import_structure["ip_adapter"] = ["IPAdapterMixin"]
66
+
67
+
68
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
69
+ if is_torch_available():
70
+ from .single_file import FromOriginalControlnetMixin, FromOriginalVAEMixin
71
+ from .unet import UNet2DConditionLoadersMixin
72
+ from .utils import AttnProcsLayers
73
+
74
+ if is_transformers_available():
75
+ from .ip_adapter import IPAdapterMixin
76
+ from .lora import LoraLoaderMixin, StableDiffusionXLLoraLoaderMixin
77
+ from .single_file import FromSingleFileMixin
78
+ from .textual_inversion import TextualInversionLoaderMixin
79
+ else:
80
+ import sys
81
+
82
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diffusers/loaders/ip_adapter.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 os
15
+ from typing import Dict, Union
16
+
17
+ import torch
18
+ from safetensors import safe_open
19
+
20
+ from ..utils import (
21
+ DIFFUSERS_CACHE,
22
+ HF_HUB_OFFLINE,
23
+ _get_model_file,
24
+ is_transformers_available,
25
+ logging,
26
+ )
27
+
28
+
29
+ if is_transformers_available():
30
+ from transformers import (
31
+ CLIPImageProcessor,
32
+ CLIPVisionModelWithProjection,
33
+ )
34
+
35
+ from ..models.attention_processor import (
36
+ IPAdapterAttnProcessor,
37
+ IPAdapterAttnProcessor2_0,
38
+ )
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class IPAdapterMixin:
44
+ """Mixin for handling IP Adapters."""
45
+
46
+ def load_ip_adapter(
47
+ self,
48
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
49
+ subfolder: str,
50
+ weight_name: str,
51
+ **kwargs,
52
+ ):
53
+ """
54
+ Parameters:
55
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
56
+ Can be either:
57
+
58
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
59
+ the Hub.
60
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
61
+ with [`ModelMixin.save_pretrained`].
62
+ - A [torch state
63
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
64
+
65
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
66
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
67
+ is not used.
68
+ force_download (`bool`, *optional*, defaults to `False`):
69
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
70
+ cached versions if they exist.
71
+ resume_download (`bool`, *optional*, defaults to `False`):
72
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
73
+ incompletely downloaded files are deleted.
74
+ proxies (`Dict[str, str]`, *optional*):
75
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
76
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
77
+ local_files_only (`bool`, *optional*, defaults to `False`):
78
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
79
+ won't be downloaded from the Hub.
80
+ use_auth_token (`str` or *bool*, *optional*):
81
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
82
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
83
+ revision (`str`, *optional*, defaults to `"main"`):
84
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
85
+ allowed by Git.
86
+ subfolder (`str`, *optional*, defaults to `""`):
87
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
88
+ """
89
+
90
+ # Load the main state dict first.
91
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
92
+ force_download = kwargs.pop("force_download", False)
93
+ resume_download = kwargs.pop("resume_download", False)
94
+ proxies = kwargs.pop("proxies", None)
95
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
96
+ use_auth_token = kwargs.pop("use_auth_token", None)
97
+ revision = kwargs.pop("revision", None)
98
+
99
+ user_agent = {
100
+ "file_type": "attn_procs_weights",
101
+ "framework": "pytorch",
102
+ }
103
+
104
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
105
+ model_file = _get_model_file(
106
+ pretrained_model_name_or_path_or_dict,
107
+ weights_name=weight_name,
108
+ cache_dir=cache_dir,
109
+ force_download=force_download,
110
+ resume_download=resume_download,
111
+ proxies=proxies,
112
+ local_files_only=local_files_only,
113
+ use_auth_token=use_auth_token,
114
+ revision=revision,
115
+ subfolder=subfolder,
116
+ user_agent=user_agent,
117
+ )
118
+ if weight_name.endswith(".safetensors"):
119
+ state_dict = {"image_proj": {}, "ip_adapter": {}}
120
+ with safe_open(model_file, framework="pt", device="cpu") as f:
121
+ for key in f.keys():
122
+ if key.startswith("image_proj."):
123
+ state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
124
+ elif key.startswith("ip_adapter."):
125
+ state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
126
+ else:
127
+ state_dict = torch.load(model_file, map_location="cpu")
128
+ else:
129
+ state_dict = pretrained_model_name_or_path_or_dict
130
+
131
+ keys = list(state_dict.keys())
132
+ if keys != ["image_proj", "ip_adapter"]:
133
+ raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
134
+
135
+ # load CLIP image encoer here if it has not been registered to the pipeline yet
136
+ if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
137
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
138
+ logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
139
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
140
+ pretrained_model_name_or_path_or_dict,
141
+ subfolder=os.path.join(subfolder, "image_encoder"),
142
+ ).to(self.device, dtype=self.dtype)
143
+ self.image_encoder = image_encoder
144
+ else:
145
+ raise ValueError("`image_encoder` cannot be None when using IP Adapters.")
146
+
147
+ # create feature extractor if it has not been registered to the pipeline yet
148
+ if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
149
+ self.feature_extractor = CLIPImageProcessor()
150
+
151
+ # load ip-adapter into unet
152
+ self.unet._load_ip_adapter_weights(state_dict)
153
+
154
+ def set_ip_adapter_scale(self, scale):
155
+ for attn_processor in self.unet.attn_processors.values():
156
+ if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
157
+ attn_processor.scale = scale
diffusers/loaders/lora.py ADDED
@@ -0,0 +1,1415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 os
15
+ from contextlib import nullcontext
16
+ from typing import Callable, Dict, List, Optional, Union
17
+
18
+ import safetensors
19
+ import torch
20
+ from huggingface_hub import model_info
21
+ from packaging import version
22
+ from torch import nn
23
+
24
+ from .. import __version__
25
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
26
+ from ..utils import (
27
+ DIFFUSERS_CACHE,
28
+ HF_HUB_OFFLINE,
29
+ USE_PEFT_BACKEND,
30
+ _get_model_file,
31
+ convert_state_dict_to_diffusers,
32
+ convert_state_dict_to_peft,
33
+ convert_unet_state_dict_to_peft,
34
+ delete_adapter_layers,
35
+ deprecate,
36
+ get_adapter_name,
37
+ get_peft_kwargs,
38
+ is_accelerate_available,
39
+ is_transformers_available,
40
+ logging,
41
+ recurse_remove_peft_layers,
42
+ scale_lora_layers,
43
+ set_adapter_layers,
44
+ set_weights_and_activate_adapters,
45
+ )
46
+ from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
47
+
48
+
49
+ if is_transformers_available():
50
+ from transformers import PreTrainedModel
51
+
52
+ from ..models.lora import PatchedLoraProjection, text_encoder_attn_modules, text_encoder_mlp_modules
53
+
54
+ if is_accelerate_available():
55
+ from accelerate import init_empty_weights
56
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
57
+
58
+ logger = logging.get_logger(__name__)
59
+
60
+ TEXT_ENCODER_NAME = "text_encoder"
61
+ UNET_NAME = "unet"
62
+
63
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
64
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
65
+
66
+ 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."
67
+
68
+
69
+ class LoraLoaderMixin:
70
+ r"""
71
+ Load LoRA layers into [`UNet2DConditionModel`] and
72
+ [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
73
+ """
74
+
75
+ text_encoder_name = TEXT_ENCODER_NAME
76
+ unet_name = UNET_NAME
77
+ num_fused_loras = 0
78
+
79
+ def load_lora_weights(
80
+ self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
81
+ ):
82
+ """
83
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
84
+ `self.text_encoder`.
85
+
86
+ All kwargs are forwarded to `self.lora_state_dict`.
87
+
88
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
89
+
90
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
91
+ `self.unet`.
92
+
93
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
94
+ into `self.text_encoder`.
95
+
96
+ Parameters:
97
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
98
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
99
+ kwargs (`dict`, *optional*):
100
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
101
+ adapter_name (`str`, *optional*):
102
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
103
+ `default_{i}` where i is the total number of adapters being loaded.
104
+ """
105
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
106
+ state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
107
+
108
+ is_correct_format = all("lora" in key for key in state_dict.keys())
109
+ if not is_correct_format:
110
+ raise ValueError("Invalid LoRA checkpoint.")
111
+
112
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
113
+
114
+ self.load_lora_into_unet(
115
+ state_dict,
116
+ network_alphas=network_alphas,
117
+ unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
118
+ low_cpu_mem_usage=low_cpu_mem_usage,
119
+ adapter_name=adapter_name,
120
+ _pipeline=self,
121
+ )
122
+ self.load_lora_into_text_encoder(
123
+ state_dict,
124
+ network_alphas=network_alphas,
125
+ text_encoder=getattr(self, self.text_encoder_name)
126
+ if not hasattr(self, "text_encoder")
127
+ else self.text_encoder,
128
+ lora_scale=self.lora_scale,
129
+ low_cpu_mem_usage=low_cpu_mem_usage,
130
+ adapter_name=adapter_name,
131
+ _pipeline=self,
132
+ )
133
+
134
+ @classmethod
135
+ def lora_state_dict(
136
+ cls,
137
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
138
+ **kwargs,
139
+ ):
140
+ r"""
141
+ Return state dict for lora weights and the network alphas.
142
+
143
+ <Tip warning={true}>
144
+
145
+ We support loading A1111 formatted LoRA checkpoints in a limited capacity.
146
+
147
+ This function is experimental and might change in the future.
148
+
149
+ </Tip>
150
+
151
+ Parameters:
152
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
153
+ Can be either:
154
+
155
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
156
+ the Hub.
157
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
158
+ with [`ModelMixin.save_pretrained`].
159
+ - A [torch state
160
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
161
+
162
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
163
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
164
+ is not used.
165
+ force_download (`bool`, *optional*, defaults to `False`):
166
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
167
+ cached versions if they exist.
168
+ resume_download (`bool`, *optional*, defaults to `False`):
169
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
170
+ incompletely downloaded files are deleted.
171
+ proxies (`Dict[str, str]`, *optional*):
172
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
173
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
174
+ local_files_only (`bool`, *optional*, defaults to `False`):
175
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
176
+ won't be downloaded from the Hub.
177
+ use_auth_token (`str` or *bool*, *optional*):
178
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
179
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
180
+ revision (`str`, *optional*, defaults to `"main"`):
181
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
182
+ allowed by Git.
183
+ subfolder (`str`, *optional*, defaults to `""`):
184
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
185
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
186
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
187
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
188
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
189
+ argument to `True` will raise an error.
190
+ mirror (`str`, *optional*):
191
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
192
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
193
+ information.
194
+
195
+ """
196
+ # Load the main state dict first which has the LoRA layers for either of
197
+ # UNet and text encoder or both.
198
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
199
+ force_download = kwargs.pop("force_download", False)
200
+ resume_download = kwargs.pop("resume_download", False)
201
+ proxies = kwargs.pop("proxies", None)
202
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
203
+ use_auth_token = kwargs.pop("use_auth_token", None)
204
+ revision = kwargs.pop("revision", None)
205
+ subfolder = kwargs.pop("subfolder", None)
206
+ weight_name = kwargs.pop("weight_name", None)
207
+ unet_config = kwargs.pop("unet_config", None)
208
+ use_safetensors = kwargs.pop("use_safetensors", None)
209
+
210
+ allow_pickle = False
211
+ if use_safetensors is None:
212
+ use_safetensors = True
213
+ allow_pickle = True
214
+
215
+ user_agent = {
216
+ "file_type": "attn_procs_weights",
217
+ "framework": "pytorch",
218
+ }
219
+
220
+ model_file = None
221
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
222
+ # Let's first try to load .safetensors weights
223
+ if (use_safetensors and weight_name is None) or (
224
+ weight_name is not None and weight_name.endswith(".safetensors")
225
+ ):
226
+ try:
227
+ # Here we're relaxing the loading check to enable more Inference API
228
+ # friendliness where sometimes, it's not at all possible to automatically
229
+ # determine `weight_name`.
230
+ if weight_name is None:
231
+ weight_name = cls._best_guess_weight_name(
232
+ pretrained_model_name_or_path_or_dict, file_extension=".safetensors"
233
+ )
234
+ model_file = _get_model_file(
235
+ pretrained_model_name_or_path_or_dict,
236
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
237
+ cache_dir=cache_dir,
238
+ force_download=force_download,
239
+ resume_download=resume_download,
240
+ proxies=proxies,
241
+ local_files_only=local_files_only,
242
+ use_auth_token=use_auth_token,
243
+ revision=revision,
244
+ subfolder=subfolder,
245
+ user_agent=user_agent,
246
+ )
247
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
248
+ except (IOError, safetensors.SafetensorError) as e:
249
+ if not allow_pickle:
250
+ raise e
251
+ # try loading non-safetensors weights
252
+ model_file = None
253
+ pass
254
+
255
+ if model_file is None:
256
+ if weight_name is None:
257
+ weight_name = cls._best_guess_weight_name(
258
+ pretrained_model_name_or_path_or_dict, file_extension=".bin"
259
+ )
260
+ model_file = _get_model_file(
261
+ pretrained_model_name_or_path_or_dict,
262
+ weights_name=weight_name or LORA_WEIGHT_NAME,
263
+ cache_dir=cache_dir,
264
+ force_download=force_download,
265
+ resume_download=resume_download,
266
+ proxies=proxies,
267
+ local_files_only=local_files_only,
268
+ use_auth_token=use_auth_token,
269
+ revision=revision,
270
+ subfolder=subfolder,
271
+ user_agent=user_agent,
272
+ )
273
+ state_dict = torch.load(model_file, map_location="cpu")
274
+ else:
275
+ state_dict = pretrained_model_name_or_path_or_dict
276
+
277
+ network_alphas = None
278
+ # TODO: replace it with a method from `state_dict_utils`
279
+ if all(
280
+ (
281
+ k.startswith("lora_te_")
282
+ or k.startswith("lora_unet_")
283
+ or k.startswith("lora_te1_")
284
+ or k.startswith("lora_te2_")
285
+ )
286
+ for k in state_dict.keys()
287
+ ):
288
+ # Map SDXL blocks correctly.
289
+ if unet_config is not None:
290
+ # use unet config to remap block numbers
291
+ state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
292
+ state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
293
+
294
+ return state_dict, network_alphas
295
+
296
+ @classmethod
297
+ def _best_guess_weight_name(cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors"):
298
+ targeted_files = []
299
+
300
+ if os.path.isfile(pretrained_model_name_or_path_or_dict):
301
+ return
302
+ elif os.path.isdir(pretrained_model_name_or_path_or_dict):
303
+ targeted_files = [
304
+ f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
305
+ ]
306
+ else:
307
+ files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
308
+ targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
309
+ if len(targeted_files) == 0:
310
+ return
311
+
312
+ # "scheduler" does not correspond to a LoRA checkpoint.
313
+ # "optimizer" does not correspond to a LoRA checkpoint
314
+ # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
315
+ unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
316
+ targeted_files = list(
317
+ filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
318
+ )
319
+
320
+ if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
321
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
322
+ elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
323
+ targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
324
+
325
+ if len(targeted_files) > 1:
326
+ raise ValueError(
327
+ 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}."
328
+ )
329
+ weight_name = targeted_files[0]
330
+ return weight_name
331
+
332
+ @classmethod
333
+ def _optionally_disable_offloading(cls, _pipeline):
334
+ """
335
+ Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
336
+
337
+ Args:
338
+ _pipeline (`DiffusionPipeline`):
339
+ The pipeline to disable offloading for.
340
+
341
+ Returns:
342
+ tuple:
343
+ A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
344
+ """
345
+ is_model_cpu_offload = False
346
+ is_sequential_cpu_offload = False
347
+
348
+ if _pipeline is not None:
349
+ for _, component in _pipeline.components.items():
350
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
351
+ if not is_model_cpu_offload:
352
+ is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
353
+ if not is_sequential_cpu_offload:
354
+ is_sequential_cpu_offload = isinstance(component._hf_hook, AlignDevicesHook)
355
+
356
+ logger.info(
357
+ "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."
358
+ )
359
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
360
+
361
+ return (is_model_cpu_offload, is_sequential_cpu_offload)
362
+
363
+ @classmethod
364
+ def load_lora_into_unet(
365
+ cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
366
+ ):
367
+ """
368
+ This will load the LoRA layers specified in `state_dict` into `unet`.
369
+
370
+ Parameters:
371
+ state_dict (`dict`):
372
+ A standard state dict containing the lora layer parameters. The keys can either be indexed directly
373
+ into the unet or prefixed with an additional `unet` which can be used to distinguish between text
374
+ encoder lora layers.
375
+ network_alphas (`Dict[str, float]`):
376
+ See `LoRALinearLayer` for more details.
377
+ unet (`UNet2DConditionModel`):
378
+ The UNet model to load the LoRA layers into.
379
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
380
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
381
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
382
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
383
+ argument to `True` will raise an error.
384
+ adapter_name (`str`, *optional*):
385
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
386
+ `default_{i}` where i is the total number of adapters being loaded.
387
+ """
388
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
389
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
390
+ # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
391
+ # their prefixes.
392
+ keys = list(state_dict.keys())
393
+
394
+ if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
395
+ # Load the layers corresponding to UNet.
396
+ logger.info(f"Loading {cls.unet_name}.")
397
+
398
+ unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
399
+ state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
400
+
401
+ if network_alphas is not None:
402
+ alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
403
+ network_alphas = {
404
+ k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
405
+ }
406
+
407
+ else:
408
+ # Otherwise, we're dealing with the old format. This means the `state_dict` should only
409
+ # contain the module names of the `unet` as its keys WITHOUT any prefix.
410
+ 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()}`."
411
+ logger.warn(warn_message)
412
+
413
+ if USE_PEFT_BACKEND and len(state_dict.keys()) > 0:
414
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
415
+
416
+ if adapter_name in getattr(unet, "peft_config", {}):
417
+ raise ValueError(
418
+ f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
419
+ )
420
+
421
+ state_dict = convert_unet_state_dict_to_peft(state_dict)
422
+
423
+ if network_alphas is not None:
424
+ # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
425
+ # `convert_unet_state_dict_to_peft` method.
426
+ network_alphas = convert_unet_state_dict_to_peft(network_alphas)
427
+
428
+ rank = {}
429
+ for key, val in state_dict.items():
430
+ if "lora_B" in key:
431
+ rank[key] = val.shape[1]
432
+
433
+ lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
434
+ lora_config = LoraConfig(**lora_config_kwargs)
435
+
436
+ # adapter_name
437
+ if adapter_name is None:
438
+ adapter_name = get_adapter_name(unet)
439
+
440
+ # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
441
+ # otherwise loading LoRA weights will lead to an error
442
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
443
+
444
+ inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
445
+ incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
446
+
447
+ if incompatible_keys is not None:
448
+ # check only for unexpected keys
449
+ unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
450
+ if unexpected_keys:
451
+ logger.warning(
452
+ f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
453
+ f" {unexpected_keys}. "
454
+ )
455
+
456
+ # Offload back.
457
+ if is_model_cpu_offload:
458
+ _pipeline.enable_model_cpu_offload()
459
+ elif is_sequential_cpu_offload:
460
+ _pipeline.enable_sequential_cpu_offload()
461
+ # Unsafe code />
462
+
463
+ unet.load_attn_procs(
464
+ state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
465
+ )
466
+
467
+ @classmethod
468
+ def load_lora_into_text_encoder(
469
+ cls,
470
+ state_dict,
471
+ network_alphas,
472
+ text_encoder,
473
+ prefix=None,
474
+ lora_scale=1.0,
475
+ low_cpu_mem_usage=None,
476
+ adapter_name=None,
477
+ _pipeline=None,
478
+ ):
479
+ """
480
+ This will load the LoRA layers specified in `state_dict` into `text_encoder`
481
+
482
+ Parameters:
483
+ state_dict (`dict`):
484
+ A standard state dict containing the lora layer parameters. The key should be prefixed with an
485
+ additional `text_encoder` to distinguish between unet lora layers.
486
+ network_alphas (`Dict[str, float]`):
487
+ See `LoRALinearLayer` for more details.
488
+ text_encoder (`CLIPTextModel`):
489
+ The text encoder model to load the LoRA layers into.
490
+ prefix (`str`):
491
+ Expected prefix of the `text_encoder` in the `state_dict`.
492
+ lora_scale (`float`):
493
+ How much to scale the output of the lora linear layer before it is added with the output of the regular
494
+ lora layer.
495
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
496
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
497
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
498
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
499
+ argument to `True` will raise an error.
500
+ adapter_name (`str`, *optional*):
501
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
502
+ `default_{i}` where i is the total number of adapters being loaded.
503
+ """
504
+ low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
505
+
506
+ # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
507
+ # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
508
+ # their prefixes.
509
+ keys = list(state_dict.keys())
510
+ prefix = cls.text_encoder_name if prefix is None else prefix
511
+
512
+ # Safe prefix to check with.
513
+ if any(cls.text_encoder_name in key for key in keys):
514
+ # Load the layers corresponding to text encoder and make necessary adjustments.
515
+ text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
516
+ text_encoder_lora_state_dict = {
517
+ k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
518
+ }
519
+
520
+ if len(text_encoder_lora_state_dict) > 0:
521
+ logger.info(f"Loading {prefix}.")
522
+ rank = {}
523
+ text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
524
+
525
+ if USE_PEFT_BACKEND:
526
+ # convert state dict
527
+ text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
528
+
529
+ for name, _ in text_encoder_attn_modules(text_encoder):
530
+ rank_key = f"{name}.out_proj.lora_B.weight"
531
+ rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
532
+
533
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
534
+ if patch_mlp:
535
+ for name, _ in text_encoder_mlp_modules(text_encoder):
536
+ rank_key_fc1 = f"{name}.fc1.lora_B.weight"
537
+ rank_key_fc2 = f"{name}.fc2.lora_B.weight"
538
+
539
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
540
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
541
+ else:
542
+ for name, _ in text_encoder_attn_modules(text_encoder):
543
+ rank_key = f"{name}.out_proj.lora_linear_layer.up.weight"
544
+ rank.update({rank_key: text_encoder_lora_state_dict[rank_key].shape[1]})
545
+
546
+ patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
547
+ if patch_mlp:
548
+ for name, _ in text_encoder_mlp_modules(text_encoder):
549
+ rank_key_fc1 = f"{name}.fc1.lora_linear_layer.up.weight"
550
+ rank_key_fc2 = f"{name}.fc2.lora_linear_layer.up.weight"
551
+ rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
552
+ rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
553
+
554
+ if network_alphas is not None:
555
+ alpha_keys = [
556
+ k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
557
+ ]
558
+ network_alphas = {
559
+ k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
560
+ }
561
+
562
+ if USE_PEFT_BACKEND:
563
+ from peft import LoraConfig
564
+
565
+ lora_config_kwargs = get_peft_kwargs(
566
+ rank, network_alphas, text_encoder_lora_state_dict, is_unet=False
567
+ )
568
+
569
+ lora_config = LoraConfig(**lora_config_kwargs)
570
+
571
+ # adapter_name
572
+ if adapter_name is None:
573
+ adapter_name = get_adapter_name(text_encoder)
574
+
575
+ is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
576
+
577
+ # inject LoRA layers and load the state dict
578
+ # in transformers we automatically check whether the adapter name is already in use or not
579
+ text_encoder.load_adapter(
580
+ adapter_name=adapter_name,
581
+ adapter_state_dict=text_encoder_lora_state_dict,
582
+ peft_config=lora_config,
583
+ )
584
+
585
+ # scale LoRA layers with `lora_scale`
586
+ scale_lora_layers(text_encoder, weight=lora_scale)
587
+ else:
588
+ cls._modify_text_encoder(
589
+ text_encoder,
590
+ lora_scale,
591
+ network_alphas,
592
+ rank=rank,
593
+ patch_mlp=patch_mlp,
594
+ low_cpu_mem_usage=low_cpu_mem_usage,
595
+ )
596
+
597
+ is_pipeline_offloaded = _pipeline is not None and any(
598
+ isinstance(c, torch.nn.Module) and hasattr(c, "_hf_hook")
599
+ for c in _pipeline.components.values()
600
+ )
601
+ if is_pipeline_offloaded and low_cpu_mem_usage:
602
+ low_cpu_mem_usage = True
603
+ logger.info(
604
+ f"Pipeline {_pipeline.__class__} is offloaded. Therefore low cpu mem usage loading is forced."
605
+ )
606
+
607
+ if low_cpu_mem_usage:
608
+ device = next(iter(text_encoder_lora_state_dict.values())).device
609
+ dtype = next(iter(text_encoder_lora_state_dict.values())).dtype
610
+ unexpected_keys = load_model_dict_into_meta(
611
+ text_encoder, text_encoder_lora_state_dict, device=device, dtype=dtype
612
+ )
613
+ else:
614
+ load_state_dict_results = text_encoder.load_state_dict(
615
+ text_encoder_lora_state_dict, strict=False
616
+ )
617
+ unexpected_keys = load_state_dict_results.unexpected_keys
618
+
619
+ if len(unexpected_keys) != 0:
620
+ raise ValueError(
621
+ f"failed to load text encoder state dict, unexpected keys: {load_state_dict_results.unexpected_keys}"
622
+ )
623
+
624
+ # <Unsafe code
625
+ # We can be sure that the following works as all we do is change the dtype and device of the text encoder
626
+ # Now we remove any existing hooks to
627
+ is_model_cpu_offload = False
628
+ is_sequential_cpu_offload = False
629
+ if _pipeline is not None:
630
+ for _, component in _pipeline.components.items():
631
+ if isinstance(component, torch.nn.Module):
632
+ if hasattr(component, "_hf_hook"):
633
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
634
+ is_sequential_cpu_offload = isinstance(
635
+ getattr(component, "_hf_hook"), AlignDevicesHook
636
+ )
637
+ logger.info(
638
+ "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."
639
+ )
640
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
641
+
642
+ text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
643
+
644
+ # Offload back.
645
+ if is_model_cpu_offload:
646
+ _pipeline.enable_model_cpu_offload()
647
+ elif is_sequential_cpu_offload:
648
+ _pipeline.enable_sequential_cpu_offload()
649
+ # Unsafe code />
650
+
651
+ @property
652
+ def lora_scale(self) -> float:
653
+ # property function that returns the lora scale which can be set at run time by the pipeline.
654
+ # if _lora_scale has not been set, return 1
655
+ return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
656
+
657
+ def _remove_text_encoder_monkey_patch(self):
658
+ if USE_PEFT_BACKEND:
659
+ remove_method = recurse_remove_peft_layers
660
+ else:
661
+ remove_method = self._remove_text_encoder_monkey_patch_classmethod
662
+
663
+ if hasattr(self, "text_encoder"):
664
+ remove_method(self.text_encoder)
665
+
666
+ # In case text encoder have no Lora attached
667
+ if USE_PEFT_BACKEND and getattr(self.text_encoder, "peft_config", None) is not None:
668
+ del self.text_encoder.peft_config
669
+ self.text_encoder._hf_peft_config_loaded = None
670
+ if hasattr(self, "text_encoder_2"):
671
+ remove_method(self.text_encoder_2)
672
+ if USE_PEFT_BACKEND:
673
+ del self.text_encoder_2.peft_config
674
+ self.text_encoder_2._hf_peft_config_loaded = None
675
+
676
+ @classmethod
677
+ def _remove_text_encoder_monkey_patch_classmethod(cls, text_encoder):
678
+ if version.parse(__version__) > version.parse("0.23"):
679
+ deprecate("_remove_text_encoder_monkey_patch_classmethod", "0.25", LORA_DEPRECATION_MESSAGE)
680
+
681
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
682
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
683
+ attn_module.q_proj.lora_linear_layer = None
684
+ attn_module.k_proj.lora_linear_layer = None
685
+ attn_module.v_proj.lora_linear_layer = None
686
+ attn_module.out_proj.lora_linear_layer = None
687
+
688
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
689
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
690
+ mlp_module.fc1.lora_linear_layer = None
691
+ mlp_module.fc2.lora_linear_layer = None
692
+
693
+ @classmethod
694
+ def _modify_text_encoder(
695
+ cls,
696
+ text_encoder,
697
+ lora_scale=1,
698
+ network_alphas=None,
699
+ rank: Union[Dict[str, int], int] = 4,
700
+ dtype=None,
701
+ patch_mlp=False,
702
+ low_cpu_mem_usage=False,
703
+ ):
704
+ r"""
705
+ Monkey-patches the forward passes of attention modules of the text encoder.
706
+ """
707
+ if version.parse(__version__) > version.parse("0.23"):
708
+ deprecate("_modify_text_encoder", "0.25", LORA_DEPRECATION_MESSAGE)
709
+
710
+ def create_patched_linear_lora(model, network_alpha, rank, dtype, lora_parameters):
711
+ linear_layer = model.regular_linear_layer if isinstance(model, PatchedLoraProjection) else model
712
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
713
+ with ctx():
714
+ model = PatchedLoraProjection(linear_layer, lora_scale, network_alpha, rank, dtype=dtype)
715
+
716
+ lora_parameters.extend(model.lora_linear_layer.parameters())
717
+ return model
718
+
719
+ # First, remove any monkey-patch that might have been applied before
720
+ cls._remove_text_encoder_monkey_patch_classmethod(text_encoder)
721
+
722
+ lora_parameters = []
723
+ network_alphas = {} if network_alphas is None else network_alphas
724
+ is_network_alphas_populated = len(network_alphas) > 0
725
+
726
+ for name, attn_module in text_encoder_attn_modules(text_encoder):
727
+ query_alpha = network_alphas.pop(name + ".to_q_lora.down.weight.alpha", None)
728
+ key_alpha = network_alphas.pop(name + ".to_k_lora.down.weight.alpha", None)
729
+ value_alpha = network_alphas.pop(name + ".to_v_lora.down.weight.alpha", None)
730
+ out_alpha = network_alphas.pop(name + ".to_out_lora.down.weight.alpha", None)
731
+
732
+ if isinstance(rank, dict):
733
+ current_rank = rank.pop(f"{name}.out_proj.lora_linear_layer.up.weight")
734
+ else:
735
+ current_rank = rank
736
+
737
+ attn_module.q_proj = create_patched_linear_lora(
738
+ attn_module.q_proj, query_alpha, current_rank, dtype, lora_parameters
739
+ )
740
+ attn_module.k_proj = create_patched_linear_lora(
741
+ attn_module.k_proj, key_alpha, current_rank, dtype, lora_parameters
742
+ )
743
+ attn_module.v_proj = create_patched_linear_lora(
744
+ attn_module.v_proj, value_alpha, current_rank, dtype, lora_parameters
745
+ )
746
+ attn_module.out_proj = create_patched_linear_lora(
747
+ attn_module.out_proj, out_alpha, current_rank, dtype, lora_parameters
748
+ )
749
+
750
+ if patch_mlp:
751
+ for name, mlp_module in text_encoder_mlp_modules(text_encoder):
752
+ fc1_alpha = network_alphas.pop(name + ".fc1.lora_linear_layer.down.weight.alpha", None)
753
+ fc2_alpha = network_alphas.pop(name + ".fc2.lora_linear_layer.down.weight.alpha", None)
754
+
755
+ current_rank_fc1 = rank.pop(f"{name}.fc1.lora_linear_layer.up.weight")
756
+ current_rank_fc2 = rank.pop(f"{name}.fc2.lora_linear_layer.up.weight")
757
+
758
+ mlp_module.fc1 = create_patched_linear_lora(
759
+ mlp_module.fc1, fc1_alpha, current_rank_fc1, dtype, lora_parameters
760
+ )
761
+ mlp_module.fc2 = create_patched_linear_lora(
762
+ mlp_module.fc2, fc2_alpha, current_rank_fc2, dtype, lora_parameters
763
+ )
764
+
765
+ if is_network_alphas_populated and len(network_alphas) > 0:
766
+ raise ValueError(
767
+ f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
768
+ )
769
+
770
+ return lora_parameters
771
+
772
+ @classmethod
773
+ def save_lora_weights(
774
+ cls,
775
+ save_directory: Union[str, os.PathLike],
776
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
777
+ text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
778
+ is_main_process: bool = True,
779
+ weight_name: str = None,
780
+ save_function: Callable = None,
781
+ safe_serialization: bool = True,
782
+ ):
783
+ r"""
784
+ Save the LoRA parameters corresponding to the UNet and text encoder.
785
+
786
+ Arguments:
787
+ save_directory (`str` or `os.PathLike`):
788
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
789
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
790
+ State dict of the LoRA layers corresponding to the `unet`.
791
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
792
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
793
+ encoder LoRA state dict because it comes from 🤗 Transformers.
794
+ is_main_process (`bool`, *optional*, defaults to `True`):
795
+ Whether the process calling this is the main process or not. Useful during distributed training and you
796
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
797
+ process to avoid race conditions.
798
+ save_function (`Callable`):
799
+ The function to use to save the state dictionary. Useful during distributed training when you need to
800
+ replace `torch.save` with another method. Can be configured with the environment variable
801
+ `DIFFUSERS_SAVE_MODE`.
802
+ safe_serialization (`bool`, *optional*, defaults to `True`):
803
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
804
+ """
805
+ # Create a flat dictionary.
806
+ state_dict = {}
807
+
808
+ # Populate the dictionary.
809
+ if unet_lora_layers is not None:
810
+ weights = (
811
+ unet_lora_layers.state_dict() if isinstance(unet_lora_layers, torch.nn.Module) else unet_lora_layers
812
+ )
813
+
814
+ unet_lora_state_dict = {f"{cls.unet_name}.{module_name}": param for module_name, param in weights.items()}
815
+ state_dict.update(unet_lora_state_dict)
816
+
817
+ if text_encoder_lora_layers is not None:
818
+ weights = (
819
+ text_encoder_lora_layers.state_dict()
820
+ if isinstance(text_encoder_lora_layers, torch.nn.Module)
821
+ else text_encoder_lora_layers
822
+ )
823
+
824
+ text_encoder_lora_state_dict = {
825
+ f"{cls.text_encoder_name}.{module_name}": param for module_name, param in weights.items()
826
+ }
827
+ state_dict.update(text_encoder_lora_state_dict)
828
+
829
+ # Save the model
830
+ cls.write_lora_layers(
831
+ state_dict=state_dict,
832
+ save_directory=save_directory,
833
+ is_main_process=is_main_process,
834
+ weight_name=weight_name,
835
+ save_function=save_function,
836
+ safe_serialization=safe_serialization,
837
+ )
838
+
839
+ @staticmethod
840
+ def write_lora_layers(
841
+ state_dict: Dict[str, torch.Tensor],
842
+ save_directory: str,
843
+ is_main_process: bool,
844
+ weight_name: str,
845
+ save_function: Callable,
846
+ safe_serialization: bool,
847
+ ):
848
+ if os.path.isfile(save_directory):
849
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
850
+ return
851
+
852
+ if save_function is None:
853
+ if safe_serialization:
854
+
855
+ def save_function(weights, filename):
856
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
857
+
858
+ else:
859
+ save_function = torch.save
860
+
861
+ os.makedirs(save_directory, exist_ok=True)
862
+
863
+ if weight_name is None:
864
+ if safe_serialization:
865
+ weight_name = LORA_WEIGHT_NAME_SAFE
866
+ else:
867
+ weight_name = LORA_WEIGHT_NAME
868
+
869
+ save_function(state_dict, os.path.join(save_directory, weight_name))
870
+ logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
871
+
872
+ def unload_lora_weights(self):
873
+ """
874
+ Unloads the LoRA parameters.
875
+
876
+ Examples:
877
+
878
+ ```python
879
+ >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
880
+ >>> pipeline.unload_lora_weights()
881
+ >>> ...
882
+ ```
883
+ """
884
+ if not USE_PEFT_BACKEND:
885
+ if version.parse(__version__) > version.parse("0.23"):
886
+ logger.warn(
887
+ "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
888
+ "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
889
+ )
890
+
891
+ for _, module in self.unet.named_modules():
892
+ if hasattr(module, "set_lora_layer"):
893
+ module.set_lora_layer(None)
894
+ else:
895
+ recurse_remove_peft_layers(self.unet)
896
+ if hasattr(self.unet, "peft_config"):
897
+ del self.unet.peft_config
898
+
899
+ # Safe to call the following regardless of LoRA.
900
+ self._remove_text_encoder_monkey_patch()
901
+
902
+ def fuse_lora(
903
+ self,
904
+ fuse_unet: bool = True,
905
+ fuse_text_encoder: bool = True,
906
+ lora_scale: float = 1.0,
907
+ safe_fusing: bool = False,
908
+ ):
909
+ r"""
910
+ Fuses the LoRA parameters into the original parameters of the corresponding blocks.
911
+
912
+ <Tip warning={true}>
913
+
914
+ This is an experimental API.
915
+
916
+ </Tip>
917
+
918
+ Args:
919
+ fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
920
+ fuse_text_encoder (`bool`, defaults to `True`):
921
+ Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
922
+ LoRA parameters then it won't have any effect.
923
+ lora_scale (`float`, defaults to 1.0):
924
+ Controls how much to influence the outputs with the LoRA parameters.
925
+ safe_fusing (`bool`, defaults to `False`):
926
+ Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
927
+ """
928
+ if fuse_unet or fuse_text_encoder:
929
+ self.num_fused_loras += 1
930
+ if self.num_fused_loras > 1:
931
+ logger.warn(
932
+ "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.",
933
+ )
934
+
935
+ if fuse_unet:
936
+ self.unet.fuse_lora(lora_scale, safe_fusing=safe_fusing)
937
+
938
+ if USE_PEFT_BACKEND:
939
+ from peft.tuners.tuners_utils import BaseTunerLayer
940
+
941
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
942
+ # TODO(Patrick, Younes): enable "safe" fusing
943
+ for module in text_encoder.modules():
944
+ if isinstance(module, BaseTunerLayer):
945
+ if lora_scale != 1.0:
946
+ module.scale_layer(lora_scale)
947
+
948
+ module.merge()
949
+
950
+ else:
951
+ if version.parse(__version__) > version.parse("0.23"):
952
+ deprecate("fuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
953
+
954
+ def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False):
955
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
956
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
957
+ attn_module.q_proj._fuse_lora(lora_scale, safe_fusing)
958
+ attn_module.k_proj._fuse_lora(lora_scale, safe_fusing)
959
+ attn_module.v_proj._fuse_lora(lora_scale, safe_fusing)
960
+ attn_module.out_proj._fuse_lora(lora_scale, safe_fusing)
961
+
962
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
963
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
964
+ mlp_module.fc1._fuse_lora(lora_scale, safe_fusing)
965
+ mlp_module.fc2._fuse_lora(lora_scale, safe_fusing)
966
+
967
+ if fuse_text_encoder:
968
+ if hasattr(self, "text_encoder"):
969
+ fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing)
970
+ if hasattr(self, "text_encoder_2"):
971
+ fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing)
972
+
973
+ def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
974
+ r"""
975
+ Reverses the effect of
976
+ [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
977
+
978
+ <Tip warning={true}>
979
+
980
+ This is an experimental API.
981
+
982
+ </Tip>
983
+
984
+ Args:
985
+ unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
986
+ unfuse_text_encoder (`bool`, defaults to `True`):
987
+ Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
988
+ LoRA parameters then it won't have any effect.
989
+ """
990
+ if unfuse_unet:
991
+ if not USE_PEFT_BACKEND:
992
+ self.unet.unfuse_lora()
993
+ else:
994
+ from peft.tuners.tuners_utils import BaseTunerLayer
995
+
996
+ for module in self.unet.modules():
997
+ if isinstance(module, BaseTunerLayer):
998
+ module.unmerge()
999
+
1000
+ if USE_PEFT_BACKEND:
1001
+ from peft.tuners.tuners_utils import BaseTunerLayer
1002
+
1003
+ def unfuse_text_encoder_lora(text_encoder):
1004
+ for module in text_encoder.modules():
1005
+ if isinstance(module, BaseTunerLayer):
1006
+ module.unmerge()
1007
+
1008
+ else:
1009
+ if version.parse(__version__) > version.parse("0.23"):
1010
+ deprecate("unfuse_text_encoder_lora", "0.25", LORA_DEPRECATION_MESSAGE)
1011
+
1012
+ def unfuse_text_encoder_lora(text_encoder):
1013
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
1014
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
1015
+ attn_module.q_proj._unfuse_lora()
1016
+ attn_module.k_proj._unfuse_lora()
1017
+ attn_module.v_proj._unfuse_lora()
1018
+ attn_module.out_proj._unfuse_lora()
1019
+
1020
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
1021
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
1022
+ mlp_module.fc1._unfuse_lora()
1023
+ mlp_module.fc2._unfuse_lora()
1024
+
1025
+ if unfuse_text_encoder:
1026
+ if hasattr(self, "text_encoder"):
1027
+ unfuse_text_encoder_lora(self.text_encoder)
1028
+ if hasattr(self, "text_encoder_2"):
1029
+ unfuse_text_encoder_lora(self.text_encoder_2)
1030
+
1031
+ self.num_fused_loras -= 1
1032
+
1033
+ def set_adapters_for_text_encoder(
1034
+ self,
1035
+ adapter_names: Union[List[str], str],
1036
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
1037
+ text_encoder_weights: List[float] = None,
1038
+ ):
1039
+ """
1040
+ Sets the adapter layers for the text encoder.
1041
+
1042
+ Args:
1043
+ adapter_names (`List[str]` or `str`):
1044
+ The names of the adapters to use.
1045
+ text_encoder (`torch.nn.Module`, *optional*):
1046
+ The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
1047
+ attribute.
1048
+ text_encoder_weights (`List[float]`, *optional*):
1049
+ The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
1050
+ """
1051
+ if not USE_PEFT_BACKEND:
1052
+ raise ValueError("PEFT backend is required for this method.")
1053
+
1054
+ def process_weights(adapter_names, weights):
1055
+ if weights is None:
1056
+ weights = [1.0] * len(adapter_names)
1057
+ elif isinstance(weights, float):
1058
+ weights = [weights]
1059
+
1060
+ if len(adapter_names) != len(weights):
1061
+ raise ValueError(
1062
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
1063
+ )
1064
+ return weights
1065
+
1066
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1067
+ text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
1068
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1069
+ if text_encoder is None:
1070
+ raise ValueError(
1071
+ "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
1072
+ )
1073
+ set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
1074
+
1075
+ def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1076
+ """
1077
+ Disables the LoRA layers for the text encoder.
1078
+
1079
+ Args:
1080
+ text_encoder (`torch.nn.Module`, *optional*):
1081
+ The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1082
+ `text_encoder` attribute.
1083
+ """
1084
+ if not USE_PEFT_BACKEND:
1085
+ raise ValueError("PEFT backend is required for this method.")
1086
+
1087
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1088
+ if text_encoder is None:
1089
+ raise ValueError("Text Encoder not found.")
1090
+ set_adapter_layers(text_encoder, enabled=False)
1091
+
1092
+ def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1093
+ """
1094
+ Enables the LoRA layers for the text encoder.
1095
+
1096
+ Args:
1097
+ text_encoder (`torch.nn.Module`, *optional*):
1098
+ The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1099
+ attribute.
1100
+ """
1101
+ if not USE_PEFT_BACKEND:
1102
+ raise ValueError("PEFT backend is required for this method.")
1103
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
1104
+ if text_encoder is None:
1105
+ raise ValueError("Text Encoder not found.")
1106
+ set_adapter_layers(self.text_encoder, enabled=True)
1107
+
1108
+ def set_adapters(
1109
+ self,
1110
+ adapter_names: Union[List[str], str],
1111
+ adapter_weights: Optional[List[float]] = None,
1112
+ ):
1113
+ # Handle the UNET
1114
+ self.unet.set_adapters(adapter_names, adapter_weights)
1115
+
1116
+ # Handle the Text Encoder
1117
+ if hasattr(self, "text_encoder"):
1118
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, adapter_weights)
1119
+ if hasattr(self, "text_encoder_2"):
1120
+ self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, adapter_weights)
1121
+
1122
+ def disable_lora(self):
1123
+ if not USE_PEFT_BACKEND:
1124
+ raise ValueError("PEFT backend is required for this method.")
1125
+
1126
+ # Disable unet adapters
1127
+ self.unet.disable_lora()
1128
+
1129
+ # Disable text encoder adapters
1130
+ if hasattr(self, "text_encoder"):
1131
+ self.disable_lora_for_text_encoder(self.text_encoder)
1132
+ if hasattr(self, "text_encoder_2"):
1133
+ self.disable_lora_for_text_encoder(self.text_encoder_2)
1134
+
1135
+ def enable_lora(self):
1136
+ if not USE_PEFT_BACKEND:
1137
+ raise ValueError("PEFT backend is required for this method.")
1138
+
1139
+ # Enable unet adapters
1140
+ self.unet.enable_lora()
1141
+
1142
+ # Enable text encoder adapters
1143
+ if hasattr(self, "text_encoder"):
1144
+ self.enable_lora_for_text_encoder(self.text_encoder)
1145
+ if hasattr(self, "text_encoder_2"):
1146
+ self.enable_lora_for_text_encoder(self.text_encoder_2)
1147
+
1148
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
1149
+ """
1150
+ Args:
1151
+ Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1152
+ adapter_names (`Union[List[str], str]`):
1153
+ The names of the adapter to delete. Can be a single string or a list of strings
1154
+ """
1155
+ if not USE_PEFT_BACKEND:
1156
+ raise ValueError("PEFT backend is required for this method.")
1157
+
1158
+ if isinstance(adapter_names, str):
1159
+ adapter_names = [adapter_names]
1160
+
1161
+ # Delete unet adapters
1162
+ self.unet.delete_adapters(adapter_names)
1163
+
1164
+ for adapter_name in adapter_names:
1165
+ # Delete text encoder adapters
1166
+ if hasattr(self, "text_encoder"):
1167
+ delete_adapter_layers(self.text_encoder, adapter_name)
1168
+ if hasattr(self, "text_encoder_2"):
1169
+ delete_adapter_layers(self.text_encoder_2, adapter_name)
1170
+
1171
+ def get_active_adapters(self) -> List[str]:
1172
+ """
1173
+ Gets the list of the current active adapters.
1174
+
1175
+ Example:
1176
+
1177
+ ```python
1178
+ from diffusers import DiffusionPipeline
1179
+
1180
+ pipeline = DiffusionPipeline.from_pretrained(
1181
+ "stabilityai/stable-diffusion-xl-base-1.0",
1182
+ ).to("cuda")
1183
+ pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1184
+ pipeline.get_active_adapters()
1185
+ ```
1186
+ """
1187
+ if not USE_PEFT_BACKEND:
1188
+ raise ValueError(
1189
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1190
+ )
1191
+
1192
+ from peft.tuners.tuners_utils import BaseTunerLayer
1193
+
1194
+ active_adapters = []
1195
+
1196
+ for module in self.unet.modules():
1197
+ if isinstance(module, BaseTunerLayer):
1198
+ active_adapters = module.active_adapters
1199
+ break
1200
+
1201
+ return active_adapters
1202
+
1203
+ def get_list_adapters(self) -> Dict[str, List[str]]:
1204
+ """
1205
+ Gets the current list of all available adapters in the pipeline.
1206
+ """
1207
+ if not USE_PEFT_BACKEND:
1208
+ raise ValueError(
1209
+ "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1210
+ )
1211
+
1212
+ set_adapters = {}
1213
+
1214
+ if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1215
+ set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1216
+
1217
+ if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1218
+ set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1219
+
1220
+ if hasattr(self, "unet") and hasattr(self.unet, "peft_config"):
1221
+ set_adapters["unet"] = list(self.unet.peft_config.keys())
1222
+
1223
+ return set_adapters
1224
+
1225
+ def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1226
+ """
1227
+ Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1228
+ you want to load multiple adapters and free some GPU memory.
1229
+
1230
+ Args:
1231
+ adapter_names (`List[str]`):
1232
+ List of adapters to send device to.
1233
+ device (`Union[torch.device, str, int]`):
1234
+ Device to send the adapters to. Can be either a torch device, a str or an integer.
1235
+ """
1236
+ if not USE_PEFT_BACKEND:
1237
+ raise ValueError("PEFT backend is required for this method.")
1238
+
1239
+ from peft.tuners.tuners_utils import BaseTunerLayer
1240
+
1241
+ # Handle the UNET
1242
+ for unet_module in self.unet.modules():
1243
+ if isinstance(unet_module, BaseTunerLayer):
1244
+ for adapter_name in adapter_names:
1245
+ unet_module.lora_A[adapter_name].to(device)
1246
+ unet_module.lora_B[adapter_name].to(device)
1247
+
1248
+ # Handle the text encoder
1249
+ modules_to_process = []
1250
+ if hasattr(self, "text_encoder"):
1251
+ modules_to_process.append(self.text_encoder)
1252
+
1253
+ if hasattr(self, "text_encoder_2"):
1254
+ modules_to_process.append(self.text_encoder_2)
1255
+
1256
+ for text_encoder in modules_to_process:
1257
+ # loop over submodules
1258
+ for text_encoder_module in text_encoder.modules():
1259
+ if isinstance(text_encoder_module, BaseTunerLayer):
1260
+ for adapter_name in adapter_names:
1261
+ text_encoder_module.lora_A[adapter_name].to(device)
1262
+ text_encoder_module.lora_B[adapter_name].to(device)
1263
+
1264
+
1265
+ class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1266
+ """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1267
+
1268
+ # Overrride to properly handle the loading and unloading of the additional text encoder.
1269
+ def load_lora_weights(
1270
+ self,
1271
+ pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1272
+ adapter_name: Optional[str] = None,
1273
+ **kwargs,
1274
+ ):
1275
+ """
1276
+ Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1277
+ `self.text_encoder`.
1278
+
1279
+ All kwargs are forwarded to `self.lora_state_dict`.
1280
+
1281
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1282
+
1283
+ See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1284
+ `self.unet`.
1285
+
1286
+ See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1287
+ into `self.text_encoder`.
1288
+
1289
+ Parameters:
1290
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1291
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1292
+ adapter_name (`str`, *optional*):
1293
+ Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1294
+ `default_{i}` where i is the total number of adapters being loaded.
1295
+ kwargs (`dict`, *optional*):
1296
+ See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1297
+ """
1298
+ # We could have accessed the unet config from `lora_state_dict()` too. We pass
1299
+ # it here explicitly to be able to tell that it's coming from an SDXL
1300
+ # pipeline.
1301
+
1302
+ # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1303
+ state_dict, network_alphas = self.lora_state_dict(
1304
+ pretrained_model_name_or_path_or_dict,
1305
+ unet_config=self.unet.config,
1306
+ **kwargs,
1307
+ )
1308
+ is_correct_format = all("lora" in key for key in state_dict.keys())
1309
+ if not is_correct_format:
1310
+ raise ValueError("Invalid LoRA checkpoint.")
1311
+
1312
+ self.load_lora_into_unet(
1313
+ state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1314
+ )
1315
+ text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1316
+ if len(text_encoder_state_dict) > 0:
1317
+ self.load_lora_into_text_encoder(
1318
+ text_encoder_state_dict,
1319
+ network_alphas=network_alphas,
1320
+ text_encoder=self.text_encoder,
1321
+ prefix="text_encoder",
1322
+ lora_scale=self.lora_scale,
1323
+ adapter_name=adapter_name,
1324
+ _pipeline=self,
1325
+ )
1326
+
1327
+ text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1328
+ if len(text_encoder_2_state_dict) > 0:
1329
+ self.load_lora_into_text_encoder(
1330
+ text_encoder_2_state_dict,
1331
+ network_alphas=network_alphas,
1332
+ text_encoder=self.text_encoder_2,
1333
+ prefix="text_encoder_2",
1334
+ lora_scale=self.lora_scale,
1335
+ adapter_name=adapter_name,
1336
+ _pipeline=self,
1337
+ )
1338
+
1339
+ @classmethod
1340
+ def save_lora_weights(
1341
+ cls,
1342
+ save_directory: Union[str, os.PathLike],
1343
+ unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1344
+ text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1345
+ text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1346
+ is_main_process: bool = True,
1347
+ weight_name: str = None,
1348
+ save_function: Callable = None,
1349
+ safe_serialization: bool = True,
1350
+ ):
1351
+ r"""
1352
+ Save the LoRA parameters corresponding to the UNet and text encoder.
1353
+
1354
+ Arguments:
1355
+ save_directory (`str` or `os.PathLike`):
1356
+ Directory to save LoRA parameters to. Will be created if it doesn't exist.
1357
+ unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1358
+ State dict of the LoRA layers corresponding to the `unet`.
1359
+ text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1360
+ State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1361
+ encoder LoRA state dict because it comes from 🤗 Transformers.
1362
+ is_main_process (`bool`, *optional*, defaults to `True`):
1363
+ Whether the process calling this is the main process or not. Useful during distributed training and you
1364
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1365
+ process to avoid race conditions.
1366
+ save_function (`Callable`):
1367
+ The function to use to save the state dictionary. Useful during distributed training when you need to
1368
+ replace `torch.save` with another method. Can be configured with the environment variable
1369
+ `DIFFUSERS_SAVE_MODE`.
1370
+ safe_serialization (`bool`, *optional*, defaults to `True`):
1371
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1372
+ """
1373
+ state_dict = {}
1374
+
1375
+ def pack_weights(layers, prefix):
1376
+ layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1377
+ layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1378
+ return layers_state_dict
1379
+
1380
+ if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1381
+ raise ValueError(
1382
+ "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1383
+ )
1384
+
1385
+ if unet_lora_layers:
1386
+ state_dict.update(pack_weights(unet_lora_layers, "unet"))
1387
+
1388
+ if text_encoder_lora_layers and text_encoder_2_lora_layers:
1389
+ state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1390
+ state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1391
+
1392
+ cls.write_lora_layers(
1393
+ state_dict=state_dict,
1394
+ save_directory=save_directory,
1395
+ is_main_process=is_main_process,
1396
+ weight_name=weight_name,
1397
+ save_function=save_function,
1398
+ safe_serialization=safe_serialization,
1399
+ )
1400
+
1401
+ def _remove_text_encoder_monkey_patch(self):
1402
+ if USE_PEFT_BACKEND:
1403
+ recurse_remove_peft_layers(self.text_encoder)
1404
+ # TODO: @younesbelkada handle this in transformers side
1405
+ if getattr(self.text_encoder, "peft_config", None) is not None:
1406
+ del self.text_encoder.peft_config
1407
+ self.text_encoder._hf_peft_config_loaded = None
1408
+
1409
+ recurse_remove_peft_layers(self.text_encoder_2)
1410
+ if getattr(self.text_encoder_2, "peft_config", None) is not None:
1411
+ del self.text_encoder_2.peft_config
1412
+ self.text_encoder_2._hf_peft_config_loaded = None
1413
+ else:
1414
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder)
1415
+ self._remove_text_encoder_monkey_patch_classmethod(self.text_encoder_2)
diffusers/loaders/lora_conversion_utils.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 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
+
132
+ # every down weight has a corresponding up weight and potentially an alpha weight
133
+ lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
134
+ for key in lora_keys:
135
+ lora_name = key.split(".")[0]
136
+ lora_name_up = lora_name + ".lora_up.weight"
137
+ lora_name_alpha = lora_name + ".alpha"
138
+
139
+ if lora_name.startswith("lora_unet_"):
140
+ diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
141
+
142
+ if "input.blocks" in diffusers_name:
143
+ diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
144
+ else:
145
+ diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
146
+
147
+ if "middle.block" in diffusers_name:
148
+ diffusers_name = diffusers_name.replace("middle.block", "mid_block")
149
+ else:
150
+ diffusers_name = diffusers_name.replace("mid.block", "mid_block")
151
+ if "output.blocks" in diffusers_name:
152
+ diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
153
+ else:
154
+ diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
155
+
156
+ diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
157
+ diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
158
+ diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
159
+ diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
160
+ diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
161
+ diffusers_name = diffusers_name.replace("proj.in", "proj_in")
162
+ diffusers_name = diffusers_name.replace("proj.out", "proj_out")
163
+ diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
164
+
165
+ # SDXL specificity.
166
+ if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
167
+ pattern = r"\.\d+(?=\D*$)"
168
+ diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
169
+ if ".in." in diffusers_name:
170
+ diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
171
+ if ".out." in diffusers_name:
172
+ diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
173
+ if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
174
+ diffusers_name = diffusers_name.replace("op", "conv")
175
+ if "skip" in diffusers_name:
176
+ diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
177
+
178
+ # LyCORIS specificity.
179
+ if "time.emb.proj" in diffusers_name:
180
+ diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
181
+ if "conv.shortcut" in diffusers_name:
182
+ diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
183
+
184
+ # General coverage.
185
+ if "transformer_blocks" in diffusers_name:
186
+ if "attn1" in diffusers_name or "attn2" in diffusers_name:
187
+ diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
188
+ diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
189
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
190
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
191
+ elif "ff" in diffusers_name:
192
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
193
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
194
+ elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
195
+ unet_state_dict[diffusers_name] = state_dict.pop(key)
196
+ unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
197
+ else:
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
+
201
+ elif lora_name.startswith("lora_te_"):
202
+ diffusers_name = key.replace("lora_te_", "").replace("_", ".")
203
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
204
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
205
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
206
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
207
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
208
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
209
+ if "self_attn" in diffusers_name:
210
+ te_state_dict[diffusers_name] = state_dict.pop(key)
211
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
212
+ elif "mlp" in diffusers_name:
213
+ # Be aware that this is the new diffusers convention and the rest of the code might
214
+ # not utilize it yet.
215
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
216
+ te_state_dict[diffusers_name] = state_dict.pop(key)
217
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
218
+
219
+ # (sayakpaul): Duplicate code. Needs to be cleaned.
220
+ elif lora_name.startswith("lora_te1_"):
221
+ diffusers_name = key.replace("lora_te1_", "").replace("_", ".")
222
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
223
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
224
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
225
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
226
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
227
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
228
+ if "self_attn" in diffusers_name:
229
+ te_state_dict[diffusers_name] = state_dict.pop(key)
230
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
231
+ elif "mlp" in diffusers_name:
232
+ # Be aware that this is the new diffusers convention and the rest of the code might
233
+ # not utilize it yet.
234
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
235
+ te_state_dict[diffusers_name] = state_dict.pop(key)
236
+ te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
237
+
238
+ # (sayakpaul): Duplicate code. Needs to be cleaned.
239
+ elif lora_name.startswith("lora_te2_"):
240
+ diffusers_name = key.replace("lora_te2_", "").replace("_", ".")
241
+ diffusers_name = diffusers_name.replace("text.model", "text_model")
242
+ diffusers_name = diffusers_name.replace("self.attn", "self_attn")
243
+ diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
244
+ diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
245
+ diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
246
+ diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
247
+ if "self_attn" in diffusers_name:
248
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
249
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
250
+ elif "mlp" in diffusers_name:
251
+ # Be aware that this is the new diffusers convention and the rest of the code might
252
+ # not utilize it yet.
253
+ diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
254
+ te2_state_dict[diffusers_name] = state_dict.pop(key)
255
+ te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
256
+
257
+ # Rename the alphas so that they can be mapped appropriately.
258
+ if lora_name_alpha in state_dict:
259
+ alpha = state_dict.pop(lora_name_alpha).item()
260
+ if lora_name_alpha.startswith("lora_unet_"):
261
+ prefix = "unet."
262
+ elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
263
+ prefix = "text_encoder."
264
+ else:
265
+ prefix = "text_encoder_2."
266
+ new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
267
+ network_alphas.update({new_name: alpha})
268
+
269
+ if len(state_dict) > 0:
270
+ raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
271
+
272
+ logger.info("Kohya-style checkpoint detected.")
273
+ unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
274
+ te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
275
+ te2_state_dict = (
276
+ {f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
277
+ if len(te2_state_dict) > 0
278
+ else None
279
+ )
280
+ if te2_state_dict is not None:
281
+ te_state_dict.update(te2_state_dict)
282
+
283
+ new_state_dict = {**unet_state_dict, **te_state_dict}
284
+ return new_state_dict, network_alphas
diffusers/loaders/single_file.py ADDED
@@ -0,0 +1,631 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 contextlib import nullcontext
15
+ from io import BytesIO
16
+ from pathlib import Path
17
+
18
+ import requests
19
+ import torch
20
+ from huggingface_hub import hf_hub_download
21
+
22
+ from ..utils import (
23
+ DIFFUSERS_CACHE,
24
+ HF_HUB_OFFLINE,
25
+ deprecate,
26
+ is_accelerate_available,
27
+ is_omegaconf_available,
28
+ is_transformers_available,
29
+ logging,
30
+ )
31
+ from ..utils.import_utils import BACKENDS_MAPPING
32
+
33
+
34
+ if is_transformers_available():
35
+ pass
36
+
37
+ if is_accelerate_available():
38
+ from accelerate import init_empty_weights
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+
43
+ class FromSingleFileMixin:
44
+ """
45
+ Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
46
+ """
47
+
48
+ @classmethod
49
+ def from_ckpt(cls, *args, **kwargs):
50
+ deprecation_message = "The function `from_ckpt` is deprecated in favor of `from_single_file` and will be removed in diffusers v.0.21. Please make sure to use `StableDiffusionPipeline.from_single_file(...)` instead."
51
+ deprecate("from_ckpt", "0.21.0", deprecation_message, standard_warn=False)
52
+ return cls.from_single_file(*args, **kwargs)
53
+
54
+ @classmethod
55
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
56
+ r"""
57
+ Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
58
+ format. The pipeline is set in evaluation mode (`model.eval()`) by default.
59
+
60
+ Parameters:
61
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
62
+ Can be either:
63
+ - A link to the `.ckpt` file (for example
64
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
65
+ - A path to a *file* containing all pipeline weights.
66
+ torch_dtype (`str` or `torch.dtype`, *optional*):
67
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
68
+ dtype is automatically derived from the model's weights.
69
+ force_download (`bool`, *optional*, defaults to `False`):
70
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
71
+ cached versions if they exist.
72
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
73
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
74
+ is not used.
75
+ resume_download (`bool`, *optional*, defaults to `False`):
76
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
77
+ incompletely downloaded files are deleted.
78
+ proxies (`Dict[str, str]`, *optional*):
79
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
80
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
81
+ local_files_only (`bool`, *optional*, defaults to `False`):
82
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
83
+ won't be downloaded from the Hub.
84
+ use_auth_token (`str` or *bool*, *optional*):
85
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
86
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
87
+ revision (`str`, *optional*, defaults to `"main"`):
88
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
89
+ allowed by Git.
90
+ use_safetensors (`bool`, *optional*, defaults to `None`):
91
+ If set to `None`, the safetensors weights are downloaded if they're available **and** if the
92
+ safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
93
+ weights. If set to `False`, safetensors weights are not loaded.
94
+ extract_ema (`bool`, *optional*, defaults to `False`):
95
+ Whether to extract the EMA weights or not. Pass `True` to extract the EMA weights which usually yield
96
+ higher quality images for inference. Non-EMA weights are usually better for continuing finetuning.
97
+ upcast_attention (`bool`, *optional*, defaults to `None`):
98
+ Whether the attention computation should always be upcasted.
99
+ image_size (`int`, *optional*, defaults to 512):
100
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
101
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
102
+ prediction_type (`str`, *optional*):
103
+ The prediction type the model was trained on. Use `'epsilon'` for all Stable Diffusion v1 models and
104
+ the Stable Diffusion v2 base model. Use `'v_prediction'` for Stable Diffusion v2.
105
+ num_in_channels (`int`, *optional*, defaults to `None`):
106
+ The number of input channels. If `None`, it is automatically inferred.
107
+ scheduler_type (`str`, *optional*, defaults to `"pndm"`):
108
+ Type of scheduler to use. Should be one of `["pndm", "lms", "heun", "euler", "euler-ancestral", "dpm",
109
+ "ddim"]`.
110
+ load_safety_checker (`bool`, *optional*, defaults to `True`):
111
+ Whether to load the safety checker or not.
112
+ text_encoder ([`~transformers.CLIPTextModel`], *optional*, defaults to `None`):
113
+ An instance of `CLIPTextModel` to use, specifically the
114
+ [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. If this
115
+ parameter is `None`, the function loads a new instance of `CLIPTextModel` by itself if needed.
116
+ vae (`AutoencoderKL`, *optional*, defaults to `None`):
117
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. If
118
+ this parameter is `None`, the function will load a new instance of [CLIP] by itself, if needed.
119
+ tokenizer ([`~transformers.CLIPTokenizer`], *optional*, defaults to `None`):
120
+ An instance of `CLIPTokenizer` to use. If this parameter is `None`, the function loads a new instance
121
+ of `CLIPTokenizer` by itself if needed.
122
+ original_config_file (`str`):
123
+ Path to `.yaml` config file corresponding to the original architecture. If `None`, will be
124
+ automatically inferred by looking for a key that only exists in SD2.0 models.
125
+ kwargs (remaining dictionary of keyword arguments, *optional*):
126
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
127
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
128
+ method. See example below for more information.
129
+
130
+ Examples:
131
+
132
+ ```py
133
+ >>> from diffusers import StableDiffusionPipeline
134
+
135
+ >>> # Download pipeline from huggingface.co and cache.
136
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
137
+ ... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
138
+ ... )
139
+
140
+ >>> # Download pipeline from local file
141
+ >>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
142
+ >>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
143
+
144
+ >>> # Enable float16 and move to GPU
145
+ >>> pipeline = StableDiffusionPipeline.from_single_file(
146
+ ... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
147
+ ... torch_dtype=torch.float16,
148
+ ... )
149
+ >>> pipeline.to("cuda")
150
+ ```
151
+ """
152
+ # import here to avoid circular dependency
153
+ from ..pipelines.stable_diffusion.convert_from_ckpt import download_from_original_stable_diffusion_ckpt
154
+
155
+ original_config_file = kwargs.pop("original_config_file", None)
156
+ config_files = kwargs.pop("config_files", None)
157
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
158
+ resume_download = kwargs.pop("resume_download", False)
159
+ force_download = kwargs.pop("force_download", False)
160
+ proxies = kwargs.pop("proxies", None)
161
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
162
+ use_auth_token = kwargs.pop("use_auth_token", None)
163
+ revision = kwargs.pop("revision", None)
164
+ extract_ema = kwargs.pop("extract_ema", False)
165
+ image_size = kwargs.pop("image_size", None)
166
+ scheduler_type = kwargs.pop("scheduler_type", "pndm")
167
+ num_in_channels = kwargs.pop("num_in_channels", None)
168
+ upcast_attention = kwargs.pop("upcast_attention", None)
169
+ load_safety_checker = kwargs.pop("load_safety_checker", True)
170
+ prediction_type = kwargs.pop("prediction_type", None)
171
+ text_encoder = kwargs.pop("text_encoder", None)
172
+ vae = kwargs.pop("vae", None)
173
+ controlnet = kwargs.pop("controlnet", None)
174
+ adapter = kwargs.pop("adapter", None)
175
+ tokenizer = kwargs.pop("tokenizer", None)
176
+
177
+ torch_dtype = kwargs.pop("torch_dtype", None)
178
+
179
+ use_safetensors = kwargs.pop("use_safetensors", None)
180
+
181
+ pipeline_name = cls.__name__
182
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
183
+ from_safetensors = file_extension == "safetensors"
184
+
185
+ if from_safetensors and use_safetensors is False:
186
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
187
+
188
+ # TODO: For now we only support stable diffusion
189
+ stable_unclip = None
190
+ model_type = None
191
+
192
+ if pipeline_name in [
193
+ "StableDiffusionControlNetPipeline",
194
+ "StableDiffusionControlNetImg2ImgPipeline",
195
+ "StableDiffusionControlNetInpaintPipeline",
196
+ ]:
197
+ from ..models.controlnet import ControlNetModel
198
+ from ..pipelines.controlnet.multicontrolnet import MultiControlNetModel
199
+
200
+ # list/tuple or a single instance of ControlNetModel or MultiControlNetModel
201
+ if not (
202
+ isinstance(controlnet, (ControlNetModel, MultiControlNetModel))
203
+ or isinstance(controlnet, (list, tuple))
204
+ and isinstance(controlnet[0], ControlNetModel)
205
+ ):
206
+ raise ValueError("ControlNet needs to be passed if loading from ControlNet pipeline.")
207
+ elif "StableDiffusion" in pipeline_name:
208
+ # Model type will be inferred from the checkpoint.
209
+ pass
210
+ elif pipeline_name == "StableUnCLIPPipeline":
211
+ model_type = "FrozenOpenCLIPEmbedder"
212
+ stable_unclip = "txt2img"
213
+ elif pipeline_name == "StableUnCLIPImg2ImgPipeline":
214
+ model_type = "FrozenOpenCLIPEmbedder"
215
+ stable_unclip = "img2img"
216
+ elif pipeline_name == "PaintByExamplePipeline":
217
+ model_type = "PaintByExample"
218
+ elif pipeline_name == "LDMTextToImagePipeline":
219
+ model_type = "LDMTextToImage"
220
+ else:
221
+ raise ValueError(f"Unhandled pipeline class: {pipeline_name}")
222
+
223
+ # remove huggingface url
224
+ has_valid_url_prefix = False
225
+ valid_url_prefixes = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
226
+ for prefix in valid_url_prefixes:
227
+ if pretrained_model_link_or_path.startswith(prefix):
228
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
229
+ has_valid_url_prefix = True
230
+
231
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
232
+ ckpt_path = Path(pretrained_model_link_or_path)
233
+ if not ckpt_path.is_file():
234
+ if not has_valid_url_prefix:
235
+ raise ValueError(
236
+ f"The provided path is either not a file or a valid huggingface URL was not provided. Valid URLs begin with {', '.join(valid_url_prefixes)}"
237
+ )
238
+
239
+ # get repo_id and (potentially nested) file path of ckpt in repo
240
+ repo_id = "/".join(ckpt_path.parts[:2])
241
+ file_path = "/".join(ckpt_path.parts[2:])
242
+
243
+ if file_path.startswith("blob/"):
244
+ file_path = file_path[len("blob/") :]
245
+
246
+ if file_path.startswith("main/"):
247
+ file_path = file_path[len("main/") :]
248
+
249
+ pretrained_model_link_or_path = hf_hub_download(
250
+ repo_id,
251
+ filename=file_path,
252
+ cache_dir=cache_dir,
253
+ resume_download=resume_download,
254
+ proxies=proxies,
255
+ local_files_only=local_files_only,
256
+ use_auth_token=use_auth_token,
257
+ revision=revision,
258
+ force_download=force_download,
259
+ )
260
+
261
+ pipe = download_from_original_stable_diffusion_ckpt(
262
+ pretrained_model_link_or_path,
263
+ pipeline_class=cls,
264
+ model_type=model_type,
265
+ stable_unclip=stable_unclip,
266
+ controlnet=controlnet,
267
+ adapter=adapter,
268
+ from_safetensors=from_safetensors,
269
+ extract_ema=extract_ema,
270
+ image_size=image_size,
271
+ scheduler_type=scheduler_type,
272
+ num_in_channels=num_in_channels,
273
+ upcast_attention=upcast_attention,
274
+ load_safety_checker=load_safety_checker,
275
+ prediction_type=prediction_type,
276
+ text_encoder=text_encoder,
277
+ vae=vae,
278
+ tokenizer=tokenizer,
279
+ original_config_file=original_config_file,
280
+ config_files=config_files,
281
+ local_files_only=local_files_only,
282
+ )
283
+
284
+ if torch_dtype is not None:
285
+ pipe.to(torch_dtype=torch_dtype)
286
+
287
+ return pipe
288
+
289
+
290
+ class FromOriginalVAEMixin:
291
+ """
292
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into an [`AutoencoderKL`].
293
+ """
294
+
295
+ @classmethod
296
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
297
+ r"""
298
+ Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
299
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
300
+
301
+ Parameters:
302
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
303
+ Can be either:
304
+ - A link to the `.ckpt` file (for example
305
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
306
+ - A path to a *file* containing all pipeline weights.
307
+ torch_dtype (`str` or `torch.dtype`, *optional*):
308
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
309
+ dtype is automatically derived from the model's weights.
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
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
314
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
315
+ is not used.
316
+ resume_download (`bool`, *optional*, defaults to `False`):
317
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
318
+ incompletely downloaded files are deleted.
319
+ proxies (`Dict[str, str]`, *optional*):
320
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
321
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
322
+ local_files_only (`bool`, *optional*, defaults to `False`):
323
+ Whether to only load local model weights and configuration files or not. If set to True, the model
324
+ won't be downloaded from the Hub.
325
+ use_auth_token (`str` or *bool*, *optional*):
326
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
327
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
328
+ revision (`str`, *optional*, defaults to `"main"`):
329
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
330
+ allowed by Git.
331
+ image_size (`int`, *optional*, defaults to 512):
332
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
333
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
334
+ use_safetensors (`bool`, *optional*, defaults to `None`):
335
+ If set to `None`, the safetensors weights are downloaded if they're available **and** if the
336
+ safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
337
+ weights. If set to `False`, safetensors weights are not loaded.
338
+ upcast_attention (`bool`, *optional*, defaults to `None`):
339
+ Whether the attention computation should always be upcasted.
340
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
341
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
342
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
343
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
344
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
345
+ = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
346
+ Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
347
+ kwargs (remaining dictionary of keyword arguments, *optional*):
348
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
349
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
350
+ method. See example below for more information.
351
+
352
+ <Tip warning={true}>
353
+
354
+ Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
355
+ a VAE from SDXL or a Stable Diffusion v2 model or higher.
356
+
357
+ </Tip>
358
+
359
+ Examples:
360
+
361
+ ```py
362
+ from diffusers import AutoencoderKL
363
+
364
+ url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
365
+ model = AutoencoderKL.from_single_file(url)
366
+ ```
367
+ """
368
+ if not is_omegaconf_available():
369
+ raise ValueError(BACKENDS_MAPPING["omegaconf"][1])
370
+
371
+ from omegaconf import OmegaConf
372
+
373
+ from ..models import AutoencoderKL
374
+
375
+ # import here to avoid circular dependency
376
+ from ..pipelines.stable_diffusion.convert_from_ckpt import (
377
+ convert_ldm_vae_checkpoint,
378
+ create_vae_diffusers_config,
379
+ )
380
+
381
+ config_file = kwargs.pop("config_file", None)
382
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
383
+ resume_download = kwargs.pop("resume_download", False)
384
+ force_download = kwargs.pop("force_download", False)
385
+ proxies = kwargs.pop("proxies", None)
386
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
387
+ use_auth_token = kwargs.pop("use_auth_token", None)
388
+ revision = kwargs.pop("revision", None)
389
+ image_size = kwargs.pop("image_size", None)
390
+ scaling_factor = kwargs.pop("scaling_factor", None)
391
+ kwargs.pop("upcast_attention", None)
392
+
393
+ torch_dtype = kwargs.pop("torch_dtype", None)
394
+
395
+ use_safetensors = kwargs.pop("use_safetensors", None)
396
+
397
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
398
+ from_safetensors = file_extension == "safetensors"
399
+
400
+ if from_safetensors and use_safetensors is False:
401
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
402
+
403
+ # remove huggingface url
404
+ for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
405
+ if pretrained_model_link_or_path.startswith(prefix):
406
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
407
+
408
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
409
+ ckpt_path = Path(pretrained_model_link_or_path)
410
+ if not ckpt_path.is_file():
411
+ # get repo_id and (potentially nested) file path of ckpt in repo
412
+ repo_id = "/".join(ckpt_path.parts[:2])
413
+ file_path = "/".join(ckpt_path.parts[2:])
414
+
415
+ if file_path.startswith("blob/"):
416
+ file_path = file_path[len("blob/") :]
417
+
418
+ if file_path.startswith("main/"):
419
+ file_path = file_path[len("main/") :]
420
+
421
+ pretrained_model_link_or_path = hf_hub_download(
422
+ repo_id,
423
+ filename=file_path,
424
+ cache_dir=cache_dir,
425
+ resume_download=resume_download,
426
+ proxies=proxies,
427
+ local_files_only=local_files_only,
428
+ use_auth_token=use_auth_token,
429
+ revision=revision,
430
+ force_download=force_download,
431
+ )
432
+
433
+ if from_safetensors:
434
+ from safetensors import safe_open
435
+
436
+ checkpoint = {}
437
+ with safe_open(pretrained_model_link_or_path, framework="pt", device="cpu") as f:
438
+ for key in f.keys():
439
+ checkpoint[key] = f.get_tensor(key)
440
+ else:
441
+ checkpoint = torch.load(pretrained_model_link_or_path, map_location="cpu")
442
+
443
+ if "state_dict" in checkpoint:
444
+ checkpoint = checkpoint["state_dict"]
445
+
446
+ if config_file is None:
447
+ config_url = "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"
448
+ config_file = BytesIO(requests.get(config_url).content)
449
+
450
+ original_config = OmegaConf.load(config_file)
451
+
452
+ # default to sd-v1-5
453
+ image_size = image_size or 512
454
+
455
+ vae_config = create_vae_diffusers_config(original_config, image_size=image_size)
456
+ converted_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
457
+
458
+ if scaling_factor is None:
459
+ if (
460
+ "model" in original_config
461
+ and "params" in original_config.model
462
+ and "scale_factor" in original_config.model.params
463
+ ):
464
+ vae_scaling_factor = original_config.model.params.scale_factor
465
+ else:
466
+ vae_scaling_factor = 0.18215 # default SD scaling factor
467
+
468
+ vae_config["scaling_factor"] = vae_scaling_factor
469
+
470
+ ctx = init_empty_weights if is_accelerate_available() else nullcontext
471
+ with ctx():
472
+ vae = AutoencoderKL(**vae_config)
473
+
474
+ if is_accelerate_available():
475
+ from ..models.modeling_utils import load_model_dict_into_meta
476
+
477
+ load_model_dict_into_meta(vae, converted_vae_checkpoint, device="cpu")
478
+ else:
479
+ vae.load_state_dict(converted_vae_checkpoint)
480
+
481
+ if torch_dtype is not None:
482
+ vae.to(dtype=torch_dtype)
483
+
484
+ return vae
485
+
486
+
487
+ class FromOriginalControlnetMixin:
488
+ """
489
+ Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
490
+ """
491
+
492
+ @classmethod
493
+ def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
494
+ r"""
495
+ Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
496
+ `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
497
+
498
+ Parameters:
499
+ pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
500
+ Can be either:
501
+ - A link to the `.ckpt` file (for example
502
+ `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
503
+ - A path to a *file* containing all pipeline weights.
504
+ torch_dtype (`str` or `torch.dtype`, *optional*):
505
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
506
+ dtype is automatically derived from the model's weights.
507
+ force_download (`bool`, *optional*, defaults to `False`):
508
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
509
+ cached versions if they exist.
510
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
511
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
512
+ is not used.
513
+ resume_download (`bool`, *optional*, defaults to `False`):
514
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
515
+ incompletely downloaded files are deleted.
516
+ proxies (`Dict[str, str]`, *optional*):
517
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
518
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
519
+ local_files_only (`bool`, *optional*, defaults to `False`):
520
+ Whether to only load local model weights and configuration files or not. If set to True, the model
521
+ won't be downloaded from the Hub.
522
+ use_auth_token (`str` or *bool*, *optional*):
523
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
524
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
525
+ revision (`str`, *optional*, defaults to `"main"`):
526
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
527
+ allowed by Git.
528
+ use_safetensors (`bool`, *optional*, defaults to `None`):
529
+ If set to `None`, the safetensors weights are downloaded if they're available **and** if the
530
+ safetensors library is installed. If set to `True`, the model is forcibly loaded from safetensors
531
+ weights. If set to `False`, safetensors weights are not loaded.
532
+ image_size (`int`, *optional*, defaults to 512):
533
+ The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
534
+ Diffusion v2 base model. Use 768 for Stable Diffusion v2.
535
+ upcast_attention (`bool`, *optional*, defaults to `None`):
536
+ Whether the attention computation should always be upcasted.
537
+ kwargs (remaining dictionary of keyword arguments, *optional*):
538
+ Can be used to overwrite load and saveable variables (for example the pipeline components of the
539
+ specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
540
+ method. See example below for more information.
541
+
542
+ Examples:
543
+
544
+ ```py
545
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
546
+
547
+ url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
548
+ model = ControlNetModel.from_single_file(url)
549
+
550
+ url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
551
+ pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
552
+ ```
553
+ """
554
+ # import here to avoid circular dependency
555
+ from ..pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
556
+
557
+ config_file = kwargs.pop("config_file", None)
558
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
559
+ resume_download = kwargs.pop("resume_download", False)
560
+ force_download = kwargs.pop("force_download", False)
561
+ proxies = kwargs.pop("proxies", None)
562
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
563
+ use_auth_token = kwargs.pop("use_auth_token", None)
564
+ num_in_channels = kwargs.pop("num_in_channels", None)
565
+ use_linear_projection = kwargs.pop("use_linear_projection", None)
566
+ revision = kwargs.pop("revision", None)
567
+ extract_ema = kwargs.pop("extract_ema", False)
568
+ image_size = kwargs.pop("image_size", None)
569
+ upcast_attention = kwargs.pop("upcast_attention", None)
570
+
571
+ torch_dtype = kwargs.pop("torch_dtype", None)
572
+
573
+ use_safetensors = kwargs.pop("use_safetensors", None)
574
+
575
+ file_extension = pretrained_model_link_or_path.rsplit(".", 1)[-1]
576
+ from_safetensors = file_extension == "safetensors"
577
+
578
+ if from_safetensors and use_safetensors is False:
579
+ raise ValueError("Make sure to install `safetensors` with `pip install safetensors`.")
580
+
581
+ # remove huggingface url
582
+ for prefix in ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]:
583
+ if pretrained_model_link_or_path.startswith(prefix):
584
+ pretrained_model_link_or_path = pretrained_model_link_or_path[len(prefix) :]
585
+
586
+ # Code based on diffusers.pipelines.pipeline_utils.DiffusionPipeline.from_pretrained
587
+ ckpt_path = Path(pretrained_model_link_or_path)
588
+ if not ckpt_path.is_file():
589
+ # get repo_id and (potentially nested) file path of ckpt in repo
590
+ repo_id = "/".join(ckpt_path.parts[:2])
591
+ file_path = "/".join(ckpt_path.parts[2:])
592
+
593
+ if file_path.startswith("blob/"):
594
+ file_path = file_path[len("blob/") :]
595
+
596
+ if file_path.startswith("main/"):
597
+ file_path = file_path[len("main/") :]
598
+
599
+ pretrained_model_link_or_path = hf_hub_download(
600
+ repo_id,
601
+ filename=file_path,
602
+ cache_dir=cache_dir,
603
+ resume_download=resume_download,
604
+ proxies=proxies,
605
+ local_files_only=local_files_only,
606
+ use_auth_token=use_auth_token,
607
+ revision=revision,
608
+ force_download=force_download,
609
+ )
610
+
611
+ if config_file is None:
612
+ config_url = "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml"
613
+ config_file = BytesIO(requests.get(config_url).content)
614
+
615
+ image_size = image_size or 512
616
+
617
+ controlnet = download_controlnet_from_original_ckpt(
618
+ pretrained_model_link_or_path,
619
+ original_config_file=config_file,
620
+ image_size=image_size,
621
+ extract_ema=extract_ema,
622
+ num_in_channels=num_in_channels,
623
+ upcast_attention=upcast_attention,
624
+ from_safetensors=from_safetensors,
625
+ use_linear_projection=use_linear_projection,
626
+ )
627
+
628
+ if torch_dtype is not None:
629
+ controlnet.to(dtype=torch_dtype)
630
+
631
+ return controlnet
diffusers/loaders/textual_inversion.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 torch import nn
19
+
20
+ from ..utils import (
21
+ DIFFUSERS_CACHE,
22
+ HF_HUB_OFFLINE,
23
+ _get_model_file,
24
+ is_accelerate_available,
25
+ is_transformers_available,
26
+ logging,
27
+ )
28
+
29
+
30
+ if is_transformers_available():
31
+ from transformers import PreTrainedModel, PreTrainedTokenizer
32
+
33
+ if is_accelerate_available():
34
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ TEXT_INVERSION_NAME = "learned_embeds.bin"
39
+ TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
40
+
41
+
42
+ def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
43
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
44
+ force_download = kwargs.pop("force_download", False)
45
+ resume_download = kwargs.pop("resume_download", False)
46
+ proxies = kwargs.pop("proxies", None)
47
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
48
+ use_auth_token = kwargs.pop("use_auth_token", None)
49
+ revision = kwargs.pop("revision", None)
50
+ subfolder = kwargs.pop("subfolder", None)
51
+ weight_name = kwargs.pop("weight_name", None)
52
+ use_safetensors = kwargs.pop("use_safetensors", None)
53
+
54
+ allow_pickle = False
55
+ if use_safetensors is None:
56
+ use_safetensors = True
57
+ allow_pickle = True
58
+
59
+ user_agent = {
60
+ "file_type": "text_inversion",
61
+ "framework": "pytorch",
62
+ }
63
+ state_dicts = []
64
+ for pretrained_model_name_or_path in pretrained_model_name_or_paths:
65
+ if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
66
+ # 3.1. Load textual inversion file
67
+ model_file = None
68
+
69
+ # Let's first try to load .safetensors weights
70
+ if (use_safetensors and weight_name is None) or (
71
+ weight_name is not None and weight_name.endswith(".safetensors")
72
+ ):
73
+ try:
74
+ model_file = _get_model_file(
75
+ pretrained_model_name_or_path,
76
+ weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
77
+ cache_dir=cache_dir,
78
+ force_download=force_download,
79
+ resume_download=resume_download,
80
+ proxies=proxies,
81
+ local_files_only=local_files_only,
82
+ use_auth_token=use_auth_token,
83
+ revision=revision,
84
+ subfolder=subfolder,
85
+ user_agent=user_agent,
86
+ )
87
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
88
+ except Exception as e:
89
+ if not allow_pickle:
90
+ raise e
91
+
92
+ model_file = None
93
+
94
+ if model_file is None:
95
+ model_file = _get_model_file(
96
+ pretrained_model_name_or_path,
97
+ weights_name=weight_name or TEXT_INVERSION_NAME,
98
+ cache_dir=cache_dir,
99
+ force_download=force_download,
100
+ resume_download=resume_download,
101
+ proxies=proxies,
102
+ local_files_only=local_files_only,
103
+ use_auth_token=use_auth_token,
104
+ revision=revision,
105
+ subfolder=subfolder,
106
+ user_agent=user_agent,
107
+ )
108
+ state_dict = torch.load(model_file, map_location="cpu")
109
+ else:
110
+ state_dict = pretrained_model_name_or_path
111
+
112
+ state_dicts.append(state_dict)
113
+
114
+ return state_dicts
115
+
116
+
117
+ class TextualInversionLoaderMixin:
118
+ r"""
119
+ Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
120
+ """
121
+
122
+ def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
123
+ r"""
124
+ Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
125
+ be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
126
+ inversion token or if the textual inversion token is a single vector, the input prompt is returned.
127
+
128
+ Parameters:
129
+ prompt (`str` or list of `str`):
130
+ The prompt or prompts to guide the image generation.
131
+ tokenizer (`PreTrainedTokenizer`):
132
+ The tokenizer responsible for encoding the prompt into input tokens.
133
+
134
+ Returns:
135
+ `str` or list of `str`: The converted prompt
136
+ """
137
+ if not isinstance(prompt, List):
138
+ prompts = [prompt]
139
+ else:
140
+ prompts = prompt
141
+
142
+ prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
143
+
144
+ if not isinstance(prompt, List):
145
+ return prompts[0]
146
+
147
+ return prompts
148
+
149
+ def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
150
+ r"""
151
+ Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
152
+ to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
153
+ is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
154
+ inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
155
+
156
+ Parameters:
157
+ prompt (`str`):
158
+ The prompt to guide the image generation.
159
+ tokenizer (`PreTrainedTokenizer`):
160
+ The tokenizer responsible for encoding the prompt into input tokens.
161
+
162
+ Returns:
163
+ `str`: The converted prompt
164
+ """
165
+ tokens = tokenizer.tokenize(prompt)
166
+ unique_tokens = set(tokens)
167
+ for token in unique_tokens:
168
+ if token in tokenizer.added_tokens_encoder:
169
+ replacement = token
170
+ i = 1
171
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
172
+ replacement += f" {token}_{i}"
173
+ i += 1
174
+
175
+ prompt = prompt.replace(token, replacement)
176
+
177
+ return prompt
178
+
179
+ def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
180
+ if tokenizer is None:
181
+ raise ValueError(
182
+ f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
183
+ f" `{self.load_textual_inversion.__name__}`"
184
+ )
185
+
186
+ if text_encoder is None:
187
+ raise ValueError(
188
+ f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
189
+ f" `{self.load_textual_inversion.__name__}`"
190
+ )
191
+
192
+ if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
193
+ raise ValueError(
194
+ f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
195
+ f"Make sure both lists have the same length."
196
+ )
197
+
198
+ valid_tokens = [t for t in tokens if t is not None]
199
+ if len(set(valid_tokens)) < len(valid_tokens):
200
+ raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
201
+
202
+ @staticmethod
203
+ def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
204
+ all_tokens = []
205
+ all_embeddings = []
206
+ for state_dict, token in zip(state_dicts, tokens):
207
+ if isinstance(state_dict, torch.Tensor):
208
+ if token is None:
209
+ raise ValueError(
210
+ "You are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`."
211
+ )
212
+ loaded_token = token
213
+ embedding = state_dict
214
+ elif len(state_dict) == 1:
215
+ # diffusers
216
+ loaded_token, embedding = next(iter(state_dict.items()))
217
+ elif "string_to_param" in state_dict:
218
+ # A1111
219
+ loaded_token = state_dict["name"]
220
+ embedding = state_dict["string_to_param"]["*"]
221
+ else:
222
+ raise ValueError(
223
+ f"Loaded state dictonary is incorrect: {state_dict}. \n\n"
224
+ "Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
225
+ " input key."
226
+ )
227
+
228
+ if token is not None and loaded_token != token:
229
+ logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
230
+ else:
231
+ token = loaded_token
232
+
233
+ if token in tokenizer.get_vocab():
234
+ raise ValueError(
235
+ f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
236
+ )
237
+
238
+ all_tokens.append(token)
239
+ all_embeddings.append(embedding)
240
+
241
+ return all_tokens, all_embeddings
242
+
243
+ @staticmethod
244
+ def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
245
+ all_tokens = []
246
+ all_embeddings = []
247
+
248
+ for embedding, token in zip(embeddings, tokens):
249
+ if f"{token}_1" in tokenizer.get_vocab():
250
+ multi_vector_tokens = [token]
251
+ i = 1
252
+ while f"{token}_{i}" in tokenizer.added_tokens_encoder:
253
+ multi_vector_tokens.append(f"{token}_{i}")
254
+ i += 1
255
+
256
+ raise ValueError(
257
+ f"Multi-vector Token {multi_vector_tokens} already in tokenizer vocabulary. Please choose a different token name or remove the {multi_vector_tokens} and embedding from the tokenizer and text encoder."
258
+ )
259
+
260
+ is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
261
+ if is_multi_vector:
262
+ all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
263
+ all_embeddings += [e for e in embedding] # noqa: C416
264
+ else:
265
+ all_tokens += [token]
266
+ all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
267
+
268
+ return all_tokens, all_embeddings
269
+
270
+ def load_textual_inversion(
271
+ self,
272
+ pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
273
+ token: Optional[Union[str, List[str]]] = None,
274
+ tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
275
+ text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
276
+ **kwargs,
277
+ ):
278
+ r"""
279
+ Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
280
+ Automatic1111 formats are supported).
281
+
282
+ Parameters:
283
+ pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
284
+ Can be either one of the following or a list of them:
285
+
286
+ - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
287
+ pretrained model hosted on the Hub.
288
+ - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
289
+ inversion weights.
290
+ - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
291
+ - A [torch state
292
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
293
+
294
+ token (`str` or `List[str]`, *optional*):
295
+ Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
296
+ list, then `token` must also be a list of equal length.
297
+ text_encoder ([`~transformers.CLIPTextModel`], *optional*):
298
+ Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
299
+ If not specified, function will take self.tokenizer.
300
+ tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
301
+ A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
302
+ weight_name (`str`, *optional*):
303
+ Name of a custom weight file. This should be used when:
304
+
305
+ - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
306
+ name such as `text_inv.bin`.
307
+ - The saved textual inversion file is in the Automatic1111 format.
308
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
309
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
310
+ is not used.
311
+ force_download (`bool`, *optional*, defaults to `False`):
312
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
313
+ cached versions if they exist.
314
+ resume_download (`bool`, *optional*, defaults to `False`):
315
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
316
+ incompletely downloaded files are deleted.
317
+ proxies (`Dict[str, str]`, *optional*):
318
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
319
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
320
+ local_files_only (`bool`, *optional*, defaults to `False`):
321
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
322
+ won't be downloaded from the Hub.
323
+ use_auth_token (`str` or *bool*, *optional*):
324
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
325
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
326
+ revision (`str`, *optional*, defaults to `"main"`):
327
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
328
+ allowed by Git.
329
+ subfolder (`str`, *optional*, defaults to `""`):
330
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
331
+ mirror (`str`, *optional*):
332
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
333
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
334
+ information.
335
+
336
+ Example:
337
+
338
+ To load a Textual Inversion embedding vector in 🤗 Diffusers format:
339
+
340
+ ```py
341
+ from diffusers import StableDiffusionPipeline
342
+ import torch
343
+
344
+ model_id = "runwayml/stable-diffusion-v1-5"
345
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
346
+
347
+ pipe.load_textual_inversion("sd-concepts-library/cat-toy")
348
+
349
+ prompt = "A <cat-toy> backpack"
350
+
351
+ image = pipe(prompt, num_inference_steps=50).images[0]
352
+ image.save("cat-backpack.png")
353
+ ```
354
+
355
+ To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
356
+ (for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
357
+ locally:
358
+
359
+ ```py
360
+ from diffusers import StableDiffusionPipeline
361
+ import torch
362
+
363
+ model_id = "runwayml/stable-diffusion-v1-5"
364
+ pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
365
+
366
+ pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
367
+
368
+ prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."
369
+
370
+ image = pipe(prompt, num_inference_steps=50).images[0]
371
+ image.save("character.png")
372
+ ```
373
+
374
+ """
375
+ # 1. Set correct tokenizer and text encoder
376
+ tokenizer = tokenizer or getattr(self, "tokenizer", None)
377
+ text_encoder = text_encoder or getattr(self, "text_encoder", None)
378
+
379
+ # 2. Normalize inputs
380
+ pretrained_model_name_or_paths = (
381
+ [pretrained_model_name_or_path]
382
+ if not isinstance(pretrained_model_name_or_path, list)
383
+ else pretrained_model_name_or_path
384
+ )
385
+ tokens = [token] if not isinstance(token, list) else token
386
+ if tokens[0] is None:
387
+ tokens = tokens * len(pretrained_model_name_or_paths)
388
+
389
+ # 3. Check inputs
390
+ self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
391
+
392
+ # 4. Load state dicts of textual embeddings
393
+ state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
394
+
395
+ # 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
396
+ if len(tokens) > 1 and len(state_dicts) == 1:
397
+ if isinstance(state_dicts[0], torch.Tensor):
398
+ state_dicts = list(state_dicts[0])
399
+ if len(tokens) != len(state_dicts):
400
+ raise ValueError(
401
+ f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
402
+ f"Make sure both have the same length."
403
+ )
404
+
405
+ # 4. Retrieve tokens and embeddings
406
+ tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
407
+
408
+ # 5. Extend tokens and embeddings for multi vector
409
+ tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
410
+
411
+ # 6. Make sure all embeddings have the correct size
412
+ expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
413
+ if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
414
+ raise ValueError(
415
+ "Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
416
+ "to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
417
+ )
418
+
419
+ # 7. Now we can be sure that loading the embedding matrix works
420
+ # < Unsafe code:
421
+
422
+ # 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
423
+ is_model_cpu_offload = False
424
+ is_sequential_cpu_offload = False
425
+ for _, component in self.components.items():
426
+ if isinstance(component, nn.Module):
427
+ if hasattr(component, "_hf_hook"):
428
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
429
+ is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
430
+ logger.info(
431
+ "Accelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again."
432
+ )
433
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
434
+
435
+ # 7.2 save expected device and dtype
436
+ device = text_encoder.device
437
+ dtype = text_encoder.dtype
438
+
439
+ # 7.3 Increase token embedding matrix
440
+ text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
441
+ input_embeddings = text_encoder.get_input_embeddings().weight
442
+
443
+ # 7.4 Load token and embedding
444
+ for token, embedding in zip(tokens, embeddings):
445
+ # add tokens and get ids
446
+ tokenizer.add_tokens(token)
447
+ token_id = tokenizer.convert_tokens_to_ids(token)
448
+ input_embeddings.data[token_id] = embedding
449
+ logger.info(f"Loaded textual inversion embedding for {token}.")
450
+
451
+ input_embeddings.to(dtype=dtype, device=device)
452
+
453
+ # 7.5 Offload the model again
454
+ if is_model_cpu_offload:
455
+ self.enable_model_cpu_offload()
456
+ elif is_sequential_cpu_offload:
457
+ self.enable_sequential_cpu_offload()
458
+
459
+ # / Unsafe Code >
diffusers/loaders/unet.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 os
15
+ from collections import defaultdict
16
+ from contextlib import nullcontext
17
+ from typing import Callable, Dict, List, Optional, Union
18
+
19
+ import safetensors
20
+ import torch
21
+ import torch.nn.functional as F
22
+ from torch import nn
23
+
24
+ from ..models.embeddings import ImageProjection
25
+ from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta
26
+ from ..utils import (
27
+ DIFFUSERS_CACHE,
28
+ HF_HUB_OFFLINE,
29
+ USE_PEFT_BACKEND,
30
+ _get_model_file,
31
+ delete_adapter_layers,
32
+ is_accelerate_available,
33
+ logging,
34
+ set_adapter_layers,
35
+ set_weights_and_activate_adapters,
36
+ )
37
+ from .utils import AttnProcsLayers
38
+
39
+
40
+ if is_accelerate_available():
41
+ from accelerate import init_empty_weights
42
+ from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
43
+
44
+ logger = logging.get_logger(__name__)
45
+
46
+
47
+ TEXT_ENCODER_NAME = "text_encoder"
48
+ UNET_NAME = "unet"
49
+
50
+ LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
51
+ LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
52
+
53
+ CUSTOM_DIFFUSION_WEIGHT_NAME = "pytorch_custom_diffusion_weights.bin"
54
+ CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE = "pytorch_custom_diffusion_weights.safetensors"
55
+
56
+
57
+ class UNet2DConditionLoadersMixin:
58
+ """
59
+ Load LoRA layers into a [`UNet2DCondtionModel`].
60
+ """
61
+
62
+ text_encoder_name = TEXT_ENCODER_NAME
63
+ unet_name = UNET_NAME
64
+
65
+ def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
66
+ r"""
67
+ Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
68
+ defined in
69
+ [`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
70
+ and be a `torch.nn.Module` class.
71
+
72
+ Parameters:
73
+ pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
74
+ Can be either:
75
+
76
+ - A string, the model id (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
77
+ the Hub.
78
+ - A path to a directory (for example `./my_model_directory`) containing the model weights saved
79
+ with [`ModelMixin.save_pretrained`].
80
+ - A [torch state
81
+ dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
82
+
83
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
84
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
85
+ is not used.
86
+ force_download (`bool`, *optional*, defaults to `False`):
87
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
88
+ cached versions if they exist.
89
+ resume_download (`bool`, *optional*, defaults to `False`):
90
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
91
+ incompletely downloaded files are deleted.
92
+ proxies (`Dict[str, str]`, *optional*):
93
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
94
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
95
+ local_files_only (`bool`, *optional*, defaults to `False`):
96
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
97
+ won't be downloaded from the Hub.
98
+ use_auth_token (`str` or *bool*, *optional*):
99
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
100
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
101
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
102
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
103
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
104
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
105
+ argument to `True` will raise an error.
106
+ revision (`str`, *optional*, defaults to `"main"`):
107
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
108
+ allowed by Git.
109
+ subfolder (`str`, *optional*, defaults to `""`):
110
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
111
+ mirror (`str`, *optional*):
112
+ Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
113
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
114
+ information.
115
+
116
+ Example:
117
+
118
+ ```py
119
+ from diffusers import AutoPipelineForText2Image
120
+ import torch
121
+
122
+ pipeline = AutoPipelineForText2Image.from_pretrained(
123
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
124
+ ).to("cuda")
125
+ pipeline.unet.load_attn_procs(
126
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
127
+ )
128
+ ```
129
+ """
130
+ from ..models.attention_processor import CustomDiffusionAttnProcessor
131
+ from ..models.lora import LoRACompatibleConv, LoRACompatibleLinear, LoRAConv2dLayer, LoRALinearLayer
132
+
133
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
134
+ force_download = kwargs.pop("force_download", False)
135
+ resume_download = kwargs.pop("resume_download", False)
136
+ proxies = kwargs.pop("proxies", None)
137
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
138
+ use_auth_token = kwargs.pop("use_auth_token", None)
139
+ revision = kwargs.pop("revision", None)
140
+ subfolder = kwargs.pop("subfolder", None)
141
+ weight_name = kwargs.pop("weight_name", None)
142
+ use_safetensors = kwargs.pop("use_safetensors", None)
143
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
144
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
145
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
146
+ network_alphas = kwargs.pop("network_alphas", None)
147
+
148
+ _pipeline = kwargs.pop("_pipeline", None)
149
+
150
+ is_network_alphas_none = network_alphas is None
151
+
152
+ allow_pickle = False
153
+
154
+ if use_safetensors is None:
155
+ use_safetensors = True
156
+ allow_pickle = True
157
+
158
+ user_agent = {
159
+ "file_type": "attn_procs_weights",
160
+ "framework": "pytorch",
161
+ }
162
+
163
+ if low_cpu_mem_usage and not is_accelerate_available():
164
+ low_cpu_mem_usage = False
165
+ logger.warning(
166
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
167
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
168
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
169
+ " install accelerate\n```\n."
170
+ )
171
+
172
+ model_file = None
173
+ if not isinstance(pretrained_model_name_or_path_or_dict, dict):
174
+ # Let's first try to load .safetensors weights
175
+ if (use_safetensors and weight_name is None) or (
176
+ weight_name is not None and weight_name.endswith(".safetensors")
177
+ ):
178
+ try:
179
+ model_file = _get_model_file(
180
+ pretrained_model_name_or_path_or_dict,
181
+ weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
182
+ cache_dir=cache_dir,
183
+ force_download=force_download,
184
+ resume_download=resume_download,
185
+ proxies=proxies,
186
+ local_files_only=local_files_only,
187
+ use_auth_token=use_auth_token,
188
+ revision=revision,
189
+ subfolder=subfolder,
190
+ user_agent=user_agent,
191
+ )
192
+ state_dict = safetensors.torch.load_file(model_file, device="cpu")
193
+ except IOError as e:
194
+ if not allow_pickle:
195
+ raise e
196
+ # try loading non-safetensors weights
197
+ pass
198
+ if model_file is None:
199
+ model_file = _get_model_file(
200
+ pretrained_model_name_or_path_or_dict,
201
+ weights_name=weight_name or LORA_WEIGHT_NAME,
202
+ cache_dir=cache_dir,
203
+ force_download=force_download,
204
+ resume_download=resume_download,
205
+ proxies=proxies,
206
+ local_files_only=local_files_only,
207
+ use_auth_token=use_auth_token,
208
+ revision=revision,
209
+ subfolder=subfolder,
210
+ user_agent=user_agent,
211
+ )
212
+ state_dict = torch.load(model_file, map_location="cpu")
213
+ else:
214
+ state_dict = pretrained_model_name_or_path_or_dict
215
+
216
+ # fill attn processors
217
+ lora_layers_list = []
218
+
219
+ is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys()) and not USE_PEFT_BACKEND
220
+ is_custom_diffusion = any("custom_diffusion" in k for k in state_dict.keys())
221
+
222
+ if is_lora:
223
+ # correct keys
224
+ state_dict, network_alphas = self.convert_state_dict_legacy_attn_format(state_dict, network_alphas)
225
+
226
+ if network_alphas is not None:
227
+ network_alphas_keys = list(network_alphas.keys())
228
+ used_network_alphas_keys = set()
229
+
230
+ lora_grouped_dict = defaultdict(dict)
231
+ mapped_network_alphas = {}
232
+
233
+ all_keys = list(state_dict.keys())
234
+ for key in all_keys:
235
+ value = state_dict.pop(key)
236
+ attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
237
+ lora_grouped_dict[attn_processor_key][sub_key] = value
238
+
239
+ # Create another `mapped_network_alphas` dictionary so that we can properly map them.
240
+ if network_alphas is not None:
241
+ for k in network_alphas_keys:
242
+ if k.replace(".alpha", "") in key:
243
+ mapped_network_alphas.update({attn_processor_key: network_alphas.get(k)})
244
+ used_network_alphas_keys.add(k)
245
+
246
+ if not is_network_alphas_none:
247
+ if len(set(network_alphas_keys) - used_network_alphas_keys) > 0:
248
+ raise ValueError(
249
+ f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
250
+ )
251
+
252
+ if len(state_dict) > 0:
253
+ raise ValueError(
254
+ f"The `state_dict` has to be empty at this point but has the following keys \n\n {', '.join(state_dict.keys())}"
255
+ )
256
+
257
+ for key, value_dict in lora_grouped_dict.items():
258
+ attn_processor = self
259
+ for sub_key in key.split("."):
260
+ attn_processor = getattr(attn_processor, sub_key)
261
+
262
+ # Process non-attention layers, which don't have to_{k,v,q,out_proj}_lora layers
263
+ # or add_{k,v,q,out_proj}_proj_lora layers.
264
+ rank = value_dict["lora.down.weight"].shape[0]
265
+
266
+ if isinstance(attn_processor, LoRACompatibleConv):
267
+ in_features = attn_processor.in_channels
268
+ out_features = attn_processor.out_channels
269
+ kernel_size = attn_processor.kernel_size
270
+
271
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
272
+ with ctx():
273
+ lora = LoRAConv2dLayer(
274
+ in_features=in_features,
275
+ out_features=out_features,
276
+ rank=rank,
277
+ kernel_size=kernel_size,
278
+ stride=attn_processor.stride,
279
+ padding=attn_processor.padding,
280
+ network_alpha=mapped_network_alphas.get(key),
281
+ )
282
+ elif isinstance(attn_processor, LoRACompatibleLinear):
283
+ ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
284
+ with ctx():
285
+ lora = LoRALinearLayer(
286
+ attn_processor.in_features,
287
+ attn_processor.out_features,
288
+ rank,
289
+ mapped_network_alphas.get(key),
290
+ )
291
+ else:
292
+ raise ValueError(f"Module {key} is not a LoRACompatibleConv or LoRACompatibleLinear module.")
293
+
294
+ value_dict = {k.replace("lora.", ""): v for k, v in value_dict.items()}
295
+ lora_layers_list.append((attn_processor, lora))
296
+
297
+ if low_cpu_mem_usage:
298
+ device = next(iter(value_dict.values())).device
299
+ dtype = next(iter(value_dict.values())).dtype
300
+ load_model_dict_into_meta(lora, value_dict, device=device, dtype=dtype)
301
+ else:
302
+ lora.load_state_dict(value_dict)
303
+
304
+ elif is_custom_diffusion:
305
+ attn_processors = {}
306
+ custom_diffusion_grouped_dict = defaultdict(dict)
307
+ for key, value in state_dict.items():
308
+ if len(value) == 0:
309
+ custom_diffusion_grouped_dict[key] = {}
310
+ else:
311
+ if "to_out" in key:
312
+ attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
313
+ else:
314
+ attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
315
+ custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
316
+
317
+ for key, value_dict in custom_diffusion_grouped_dict.items():
318
+ if len(value_dict) == 0:
319
+ attn_processors[key] = CustomDiffusionAttnProcessor(
320
+ train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
321
+ )
322
+ else:
323
+ cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
324
+ hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
325
+ train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
326
+ attn_processors[key] = CustomDiffusionAttnProcessor(
327
+ train_kv=True,
328
+ train_q_out=train_q_out,
329
+ hidden_size=hidden_size,
330
+ cross_attention_dim=cross_attention_dim,
331
+ )
332
+ attn_processors[key].load_state_dict(value_dict)
333
+ elif USE_PEFT_BACKEND:
334
+ # In that case we have nothing to do as loading the adapter weights is already handled above by `set_peft_model_state_dict`
335
+ # on the Unet
336
+ pass
337
+ else:
338
+ raise ValueError(
339
+ f"{model_file} does not seem to be in the correct format expected by LoRA or Custom Diffusion training."
340
+ )
341
+
342
+ # <Unsafe code
343
+ # We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
344
+ # Now we remove any existing hooks to
345
+ is_model_cpu_offload = False
346
+ is_sequential_cpu_offload = False
347
+
348
+ # For PEFT backend the Unet is already offloaded at this stage as it is handled inside `lora_lora_weights_into_unet`
349
+ if not USE_PEFT_BACKEND:
350
+ if _pipeline is not None:
351
+ for _, component in _pipeline.components.items():
352
+ if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
353
+ is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
354
+ is_sequential_cpu_offload = isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
355
+
356
+ logger.info(
357
+ "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."
358
+ )
359
+ remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
360
+
361
+ # only custom diffusion needs to set attn processors
362
+ if is_custom_diffusion:
363
+ self.set_attn_processor(attn_processors)
364
+
365
+ # set lora layers
366
+ for target_module, lora_layer in lora_layers_list:
367
+ target_module.set_lora_layer(lora_layer)
368
+
369
+ self.to(dtype=self.dtype, device=self.device)
370
+
371
+ # Offload back.
372
+ if is_model_cpu_offload:
373
+ _pipeline.enable_model_cpu_offload()
374
+ elif is_sequential_cpu_offload:
375
+ _pipeline.enable_sequential_cpu_offload()
376
+ # Unsafe code />
377
+
378
+ def convert_state_dict_legacy_attn_format(self, state_dict, network_alphas):
379
+ is_new_lora_format = all(
380
+ key.startswith(self.unet_name) or key.startswith(self.text_encoder_name) for key in state_dict.keys()
381
+ )
382
+ if is_new_lora_format:
383
+ # Strip the `"unet"` prefix.
384
+ is_text_encoder_present = any(key.startswith(self.text_encoder_name) for key in state_dict.keys())
385
+ if is_text_encoder_present:
386
+ warn_message = "The state_dict contains LoRA params corresponding to the text encoder which are not being used here. To use both UNet and text encoder related LoRA params, use [`pipe.load_lora_weights()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.load_lora_weights)."
387
+ logger.warn(warn_message)
388
+ unet_keys = [k for k in state_dict.keys() if k.startswith(self.unet_name)]
389
+ state_dict = {k.replace(f"{self.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
390
+
391
+ # change processor format to 'pure' LoRACompatibleLinear format
392
+ if any("processor" in k.split(".") for k in state_dict.keys()):
393
+
394
+ def format_to_lora_compatible(key):
395
+ if "processor" not in key.split("."):
396
+ return key
397
+ return key.replace(".processor", "").replace("to_out_lora", "to_out.0.lora").replace("_lora", ".lora")
398
+
399
+ state_dict = {format_to_lora_compatible(k): v for k, v in state_dict.items()}
400
+
401
+ if network_alphas is not None:
402
+ network_alphas = {format_to_lora_compatible(k): v for k, v in network_alphas.items()}
403
+ return state_dict, network_alphas
404
+
405
+ def save_attn_procs(
406
+ self,
407
+ save_directory: Union[str, os.PathLike],
408
+ is_main_process: bool = True,
409
+ weight_name: str = None,
410
+ save_function: Callable = None,
411
+ safe_serialization: bool = True,
412
+ **kwargs,
413
+ ):
414
+ r"""
415
+ Save attention processor layers to a directory so that it can be reloaded with the
416
+ [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method.
417
+
418
+ Arguments:
419
+ save_directory (`str` or `os.PathLike`):
420
+ Directory to save an attention processor to (will be created if it doesn't exist).
421
+ is_main_process (`bool`, *optional*, defaults to `True`):
422
+ Whether the process calling this is the main process or not. Useful during distributed training and you
423
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
424
+ process to avoid race conditions.
425
+ save_function (`Callable`):
426
+ The function to use to save the state dictionary. Useful during distributed training when you need to
427
+ replace `torch.save` with another method. Can be configured with the environment variable
428
+ `DIFFUSERS_SAVE_MODE`.
429
+ safe_serialization (`bool`, *optional*, defaults to `True`):
430
+ Whether to save the model using `safetensors` or with `pickle`.
431
+
432
+ Example:
433
+
434
+ ```py
435
+ import torch
436
+ from diffusers import DiffusionPipeline
437
+
438
+ pipeline = DiffusionPipeline.from_pretrained(
439
+ "CompVis/stable-diffusion-v1-4",
440
+ torch_dtype=torch.float16,
441
+ ).to("cuda")
442
+ pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
443
+ pipeline.unet.save_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
444
+ ```
445
+ """
446
+ from ..models.attention_processor import (
447
+ CustomDiffusionAttnProcessor,
448
+ CustomDiffusionAttnProcessor2_0,
449
+ CustomDiffusionXFormersAttnProcessor,
450
+ )
451
+
452
+ if os.path.isfile(save_directory):
453
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
454
+ return
455
+
456
+ if save_function is None:
457
+ if safe_serialization:
458
+
459
+ def save_function(weights, filename):
460
+ return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
461
+
462
+ else:
463
+ save_function = torch.save
464
+
465
+ os.makedirs(save_directory, exist_ok=True)
466
+
467
+ is_custom_diffusion = any(
468
+ isinstance(
469
+ x,
470
+ (CustomDiffusionAttnProcessor, CustomDiffusionAttnProcessor2_0, CustomDiffusionXFormersAttnProcessor),
471
+ )
472
+ for (_, x) in self.attn_processors.items()
473
+ )
474
+ if is_custom_diffusion:
475
+ model_to_save = AttnProcsLayers(
476
+ {
477
+ y: x
478
+ for (y, x) in self.attn_processors.items()
479
+ if isinstance(
480
+ x,
481
+ (
482
+ CustomDiffusionAttnProcessor,
483
+ CustomDiffusionAttnProcessor2_0,
484
+ CustomDiffusionXFormersAttnProcessor,
485
+ ),
486
+ )
487
+ }
488
+ )
489
+ state_dict = model_to_save.state_dict()
490
+ for name, attn in self.attn_processors.items():
491
+ if len(attn.state_dict()) == 0:
492
+ state_dict[name] = {}
493
+ else:
494
+ model_to_save = AttnProcsLayers(self.attn_processors)
495
+ state_dict = model_to_save.state_dict()
496
+
497
+ if weight_name is None:
498
+ if safe_serialization:
499
+ weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE if is_custom_diffusion else LORA_WEIGHT_NAME_SAFE
500
+ else:
501
+ weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME if is_custom_diffusion else LORA_WEIGHT_NAME
502
+
503
+ # Save the model
504
+ save_function(state_dict, os.path.join(save_directory, weight_name))
505
+ logger.info(f"Model weights saved in {os.path.join(save_directory, weight_name)}")
506
+
507
+ def fuse_lora(self, lora_scale=1.0, safe_fusing=False):
508
+ self.lora_scale = lora_scale
509
+ self._safe_fusing = safe_fusing
510
+ self.apply(self._fuse_lora_apply)
511
+
512
+ def _fuse_lora_apply(self, module):
513
+ if not USE_PEFT_BACKEND:
514
+ if hasattr(module, "_fuse_lora"):
515
+ module._fuse_lora(self.lora_scale, self._safe_fusing)
516
+ else:
517
+ from peft.tuners.tuners_utils import BaseTunerLayer
518
+
519
+ if isinstance(module, BaseTunerLayer):
520
+ if self.lora_scale != 1.0:
521
+ module.scale_layer(self.lora_scale)
522
+ module.merge(safe_merge=self._safe_fusing)
523
+
524
+ def unfuse_lora(self):
525
+ self.apply(self._unfuse_lora_apply)
526
+
527
+ def _unfuse_lora_apply(self, module):
528
+ if not USE_PEFT_BACKEND:
529
+ if hasattr(module, "_unfuse_lora"):
530
+ module._unfuse_lora()
531
+ else:
532
+ from peft.tuners.tuners_utils import BaseTunerLayer
533
+
534
+ if isinstance(module, BaseTunerLayer):
535
+ module.unmerge()
536
+
537
+ def set_adapters(
538
+ self,
539
+ adapter_names: Union[List[str], str],
540
+ weights: Optional[Union[List[float], float]] = None,
541
+ ):
542
+ """
543
+ Set the currently active adapters for use in the UNet.
544
+
545
+ Args:
546
+ adapter_names (`List[str]` or `str`):
547
+ The names of the adapters to use.
548
+ adapter_weights (`Union[List[float], float]`, *optional*):
549
+ The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
550
+ adapters.
551
+
552
+ Example:
553
+
554
+ ```py
555
+ from diffusers import AutoPipelineForText2Image
556
+ import torch
557
+
558
+ pipeline = AutoPipelineForText2Image.from_pretrained(
559
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
560
+ ).to("cuda")
561
+ pipeline.load_lora_weights(
562
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
563
+ )
564
+ pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
565
+ pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
566
+ ```
567
+ """
568
+ if not USE_PEFT_BACKEND:
569
+ raise ValueError("PEFT backend is required for `set_adapters()`.")
570
+
571
+ adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
572
+
573
+ if weights is None:
574
+ weights = [1.0] * len(adapter_names)
575
+ elif isinstance(weights, float):
576
+ weights = [weights] * len(adapter_names)
577
+
578
+ if len(adapter_names) != len(weights):
579
+ raise ValueError(
580
+ f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
581
+ )
582
+
583
+ set_weights_and_activate_adapters(self, adapter_names, weights)
584
+
585
+ def disable_lora(self):
586
+ """
587
+ Disable the UNet's active LoRA layers.
588
+
589
+ Example:
590
+
591
+ ```py
592
+ from diffusers import AutoPipelineForText2Image
593
+ import torch
594
+
595
+ pipeline = AutoPipelineForText2Image.from_pretrained(
596
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
597
+ ).to("cuda")
598
+ pipeline.load_lora_weights(
599
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
600
+ )
601
+ pipeline.disable_lora()
602
+ ```
603
+ """
604
+ if not USE_PEFT_BACKEND:
605
+ raise ValueError("PEFT backend is required for this method.")
606
+ set_adapter_layers(self, enabled=False)
607
+
608
+ def enable_lora(self):
609
+ """
610
+ Enable the UNet's active LoRA layers.
611
+
612
+ Example:
613
+
614
+ ```py
615
+ from diffusers import AutoPipelineForText2Image
616
+ import torch
617
+
618
+ pipeline = AutoPipelineForText2Image.from_pretrained(
619
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
620
+ ).to("cuda")
621
+ pipeline.load_lora_weights(
622
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
623
+ )
624
+ pipeline.enable_lora()
625
+ ```
626
+ """
627
+ if not USE_PEFT_BACKEND:
628
+ raise ValueError("PEFT backend is required for this method.")
629
+ set_adapter_layers(self, enabled=True)
630
+
631
+ def delete_adapters(self, adapter_names: Union[List[str], str]):
632
+ """
633
+ Delete an adapter's LoRA layers from the UNet.
634
+
635
+ Args:
636
+ adapter_names (`Union[List[str], str]`):
637
+ The names (single string or list of strings) of the adapter to delete.
638
+
639
+ Example:
640
+
641
+ ```py
642
+ from diffusers import AutoPipelineForText2Image
643
+ import torch
644
+
645
+ pipeline = AutoPipelineForText2Image.from_pretrained(
646
+ "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
647
+ ).to("cuda")
648
+ pipeline.load_lora_weights(
649
+ "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
650
+ )
651
+ pipeline.delete_adapters("cinematic")
652
+ ```
653
+ """
654
+ if not USE_PEFT_BACKEND:
655
+ raise ValueError("PEFT backend is required for this method.")
656
+
657
+ if isinstance(adapter_names, str):
658
+ adapter_names = [adapter_names]
659
+
660
+ for adapter_name in adapter_names:
661
+ delete_adapter_layers(self, adapter_name)
662
+
663
+ # Pop also the corresponding adapter from the config
664
+ if hasattr(self, "peft_config"):
665
+ self.peft_config.pop(adapter_name, None)
666
+
667
+ def _load_ip_adapter_weights(self, state_dict):
668
+ from ..models.attention_processor import (
669
+ AttnProcessor,
670
+ AttnProcessor2_0,
671
+ IPAdapterAttnProcessor,
672
+ IPAdapterAttnProcessor2_0,
673
+ )
674
+
675
+ # set ip-adapter cross-attention processors & load state_dict
676
+ attn_procs = {}
677
+ key_id = 1
678
+ for name in self.attn_processors.keys():
679
+ cross_attention_dim = None if name.endswith("attn1.processor") else self.config.cross_attention_dim
680
+ if name.startswith("mid_block"):
681
+ hidden_size = self.config.block_out_channels[-1]
682
+ elif name.startswith("up_blocks"):
683
+ block_id = int(name[len("up_blocks.")])
684
+ hidden_size = list(reversed(self.config.block_out_channels))[block_id]
685
+ elif name.startswith("down_blocks"):
686
+ block_id = int(name[len("down_blocks.")])
687
+ hidden_size = self.config.block_out_channels[block_id]
688
+ if cross_attention_dim is None or "motion_modules" in name:
689
+ attn_processor_class = (
690
+ AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
691
+ )
692
+ attn_procs[name] = attn_processor_class()
693
+ else:
694
+ attn_processor_class = (
695
+ IPAdapterAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else IPAdapterAttnProcessor
696
+ )
697
+ attn_procs[name] = attn_processor_class(
698
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0
699
+ ).to(dtype=self.dtype, device=self.device)
700
+
701
+ value_dict = {}
702
+ for k, w in attn_procs[name].state_dict().items():
703
+ value_dict.update({f"{k}": state_dict["ip_adapter"][f"{key_id}.{k}"]})
704
+
705
+ attn_procs[name].load_state_dict(value_dict)
706
+ key_id += 2
707
+
708
+ self.set_attn_processor(attn_procs)
709
+
710
+ # create image projection layers.
711
+ clip_embeddings_dim = state_dict["image_proj"]["proj.weight"].shape[-1]
712
+ cross_attention_dim = state_dict["image_proj"]["proj.weight"].shape[0] // 4
713
+
714
+ image_projection = ImageProjection(
715
+ cross_attention_dim=cross_attention_dim, image_embed_dim=clip_embeddings_dim, num_image_text_embeds=4
716
+ )
717
+ image_projection.to(dtype=self.dtype, device=self.device)
718
+
719
+ # load image projection layer weights
720
+ image_proj_state_dict = {}
721
+ image_proj_state_dict.update(
722
+ {
723
+ "image_embeds.weight": state_dict["image_proj"]["proj.weight"],
724
+ "image_embeds.bias": state_dict["image_proj"]["proj.bias"],
725
+ "norm.weight": state_dict["image_proj"]["norm.weight"],
726
+ "norm.bias": state_dict["image_proj"]["norm.bias"],
727
+ }
728
+ )
729
+
730
+ image_projection.load_state_dict(image_proj_state_dict)
731
+
732
+ self.encoder_hid_proj = image_projection.to(device=self.device, dtype=self.dtype)
733
+ self.config.encoder_hid_dim_type = "ip_image_proj"
734
+
735
+ delete_adapter_layers
diffusers/loaders/utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 typing import Dict
16
+
17
+ import torch
18
+
19
+
20
+ class AttnProcsLayers(torch.nn.Module):
21
+ def __init__(self, state_dict: Dict[str, torch.Tensor]):
22
+ super().__init__()
23
+ self.layers = torch.nn.ModuleList(state_dict.values())
24
+ self.mapping = dict(enumerate(state_dict.keys()))
25
+ self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
26
+
27
+ # .processor for unet, .self_attn for text encoder
28
+ self.split_keys = [".processor", ".self_attn"]
29
+
30
+ # we add a hook to state_dict() and load_state_dict() so that the
31
+ # naming fits with `unet.attn_processors`
32
+ def map_to(module, state_dict, *args, **kwargs):
33
+ new_state_dict = {}
34
+ for key, value in state_dict.items():
35
+ num = int(key.split(".")[1]) # 0 is always "layers"
36
+ new_key = key.replace(f"layers.{num}", module.mapping[num])
37
+ new_state_dict[new_key] = value
38
+
39
+ return new_state_dict
40
+
41
+ def remap_key(key, state_dict):
42
+ for k in self.split_keys:
43
+ if k in key:
44
+ return key.split(k)[0] + k
45
+
46
+ raise ValueError(
47
+ f"There seems to be a problem with the state_dict: {set(state_dict.keys())}. {key} has to have one of {self.split_keys}."
48
+ )
49
+
50
+ def map_from(module, state_dict, *args, **kwargs):
51
+ all_keys = list(state_dict.keys())
52
+ for key in all_keys:
53
+ replace_key = remap_key(key, state_dict)
54
+ new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
55
+ state_dict[new_key] = state_dict[key]
56
+ del state_dict[key]
57
+
58
+ self._register_state_dict_hook(map_to)
59
+ self._register_load_state_dict_pre_hook(map_from, with_module=True)
diffusers/models/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Models
2
+
3
+ For more detail on the models, please refer to the [docs](https://huggingface.co/docs/diffusers/api/models/overview).
diffusers/models/__init__.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 typing import TYPE_CHECKING
16
+
17
+ from ..utils import (
18
+ DIFFUSERS_SLOW_IMPORT,
19
+ _LazyModule,
20
+ is_flax_available,
21
+ is_torch_available,
22
+ )
23
+
24
+
25
+ _import_structure = {}
26
+
27
+ if is_torch_available():
28
+ _import_structure["adapter"] = ["MultiAdapter", "T2IAdapter"]
29
+ _import_structure["autoencoder_asym_kl"] = ["AsymmetricAutoencoderKL"]
30
+ _import_structure["autoencoder_kl"] = ["AutoencoderKL"]
31
+ _import_structure["autoencoder_kl_temporal_decoder"] = ["AutoencoderKLTemporalDecoder"]
32
+ _import_structure["autoencoder_tiny"] = ["AutoencoderTiny"]
33
+ _import_structure["consistency_decoder_vae"] = ["ConsistencyDecoderVAE"]
34
+ _import_structure["controlnet"] = ["ControlNetModel"]
35
+ _import_structure["dual_transformer_2d"] = ["DualTransformer2DModel"]
36
+ _import_structure["modeling_utils"] = ["ModelMixin"]
37
+ _import_structure["prior_transformer"] = ["PriorTransformer"]
38
+ _import_structure["t5_film_transformer"] = ["T5FilmDecoder"]
39
+ _import_structure["transformer_2d"] = ["Transformer2DModel"]
40
+ _import_structure["transformer_temporal"] = ["TransformerTemporalModel"]
41
+ _import_structure["unet_1d"] = ["UNet1DModel"]
42
+ _import_structure["unet_2d"] = ["UNet2DModel"]
43
+ _import_structure["unet_2d_condition"] = ["UNet2DConditionModel"]
44
+ _import_structure["unet_3d_condition"] = ["UNet3DConditionModel"]
45
+ _import_structure["unet_kandi3"] = ["Kandinsky3UNet"]
46
+ _import_structure["unet_motion_model"] = ["MotionAdapter", "UNetMotionModel"]
47
+ _import_structure["unet_spatio_temporal_condition"] = ["UNetSpatioTemporalConditionModel"]
48
+ _import_structure["vq_model"] = ["VQModel"]
49
+
50
+ if is_flax_available():
51
+ _import_structure["controlnet_flax"] = ["FlaxControlNetModel"]
52
+ _import_structure["unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
53
+ _import_structure["vae_flax"] = ["FlaxAutoencoderKL"]
54
+
55
+
56
+ if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
57
+ if is_torch_available():
58
+ from .adapter import MultiAdapter, T2IAdapter
59
+ from .autoencoder_asym_kl import AsymmetricAutoencoderKL
60
+ from .autoencoder_kl import AutoencoderKL
61
+ from .autoencoder_kl_temporal_decoder import AutoencoderKLTemporalDecoder
62
+ from .autoencoder_tiny import AutoencoderTiny
63
+ from .consistency_decoder_vae import ConsistencyDecoderVAE
64
+ from .controlnet import ControlNetModel
65
+ from .dual_transformer_2d import DualTransformer2DModel
66
+ from .modeling_utils import ModelMixin
67
+ from .prior_transformer import PriorTransformer
68
+ from .t5_film_transformer import T5FilmDecoder
69
+ from .transformer_2d import Transformer2DModel
70
+ from .transformer_temporal import TransformerTemporalModel
71
+ from .unet_1d import UNet1DModel
72
+ from .unet_2d import UNet2DModel
73
+ from .unet_2d_condition import UNet2DConditionModel
74
+ from .unet_3d_condition import UNet3DConditionModel
75
+ from .unet_kandi3 import Kandinsky3UNet
76
+ from .unet_motion_model import MotionAdapter, UNetMotionModel
77
+ from .unet_spatio_temporal_condition import UNetSpatioTemporalConditionModel
78
+ from .vq_model import VQModel
79
+
80
+ if is_flax_available():
81
+ from .controlnet_flax import FlaxControlNetModel
82
+ from .unet_2d_condition_flax import FlaxUNet2DConditionModel
83
+ from .vae_flax import FlaxAutoencoderKL
84
+
85
+ else:
86
+ import sys
87
+
88
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
diffusers/models/activations.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 HuggingFace Inc.
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
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+
20
+ from ..utils import USE_PEFT_BACKEND
21
+ from .lora import LoRACompatibleLinear
22
+
23
+
24
+ ACTIVATION_FUNCTIONS = {
25
+ "swish": nn.SiLU(),
26
+ "silu": nn.SiLU(),
27
+ "mish": nn.Mish(),
28
+ "gelu": nn.GELU(),
29
+ "relu": nn.ReLU(),
30
+ }
31
+
32
+
33
+ def get_activation(act_fn: str) -> nn.Module:
34
+ """Helper function to get activation function from string.
35
+
36
+ Args:
37
+ act_fn (str): Name of activation function.
38
+
39
+ Returns:
40
+ nn.Module: Activation function.
41
+ """
42
+
43
+ act_fn = act_fn.lower()
44
+ if act_fn in ACTIVATION_FUNCTIONS:
45
+ return ACTIVATION_FUNCTIONS[act_fn]
46
+ else:
47
+ raise ValueError(f"Unsupported activation function: {act_fn}")
48
+
49
+
50
+ class GELU(nn.Module):
51
+ r"""
52
+ GELU activation function with tanh approximation support with `approximate="tanh"`.
53
+
54
+ Parameters:
55
+ dim_in (`int`): The number of channels in the input.
56
+ dim_out (`int`): The number of channels in the output.
57
+ approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
58
+ """
59
+
60
+ def __init__(self, dim_in: int, dim_out: int, approximate: str = "none"):
61
+ super().__init__()
62
+ self.proj = nn.Linear(dim_in, dim_out)
63
+ self.approximate = approximate
64
+
65
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
66
+ if gate.device.type != "mps":
67
+ return F.gelu(gate, approximate=self.approximate)
68
+ # mps: gelu is not implemented for float16
69
+ return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
70
+
71
+ def forward(self, hidden_states):
72
+ hidden_states = self.proj(hidden_states)
73
+ hidden_states = self.gelu(hidden_states)
74
+ return hidden_states
75
+
76
+
77
+ class GEGLU(nn.Module):
78
+ r"""
79
+ A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
80
+
81
+ Parameters:
82
+ dim_in (`int`): The number of channels in the input.
83
+ dim_out (`int`): The number of channels in the output.
84
+ """
85
+
86
+ def __init__(self, dim_in: int, dim_out: int):
87
+ super().__init__()
88
+ linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
89
+
90
+ self.proj = linear_cls(dim_in, dim_out * 2)
91
+
92
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
93
+ if gate.device.type != "mps":
94
+ return F.gelu(gate)
95
+ # mps: gelu is not implemented for float16
96
+ return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
97
+
98
+ def forward(self, hidden_states, scale: float = 1.0):
99
+ args = () if USE_PEFT_BACKEND else (scale,)
100
+ hidden_states, gate = self.proj(hidden_states, *args).chunk(2, dim=-1)
101
+ return hidden_states * self.gelu(gate)
102
+
103
+
104
+ class ApproximateGELU(nn.Module):
105
+ r"""
106
+ The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
107
+ [paper](https://arxiv.org/abs/1606.08415).
108
+
109
+ Parameters:
110
+ dim_in (`int`): The number of channels in the input.
111
+ dim_out (`int`): The number of channels in the output.
112
+ """
113
+
114
+ def __init__(self, dim_in: int, dim_out: int):
115
+ super().__init__()
116
+ self.proj = nn.Linear(dim_in, dim_out)
117
+
118
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
119
+ x = self.proj(x)
120
+ return x * torch.sigmoid(1.702 * x)
diffusers/models/adapter.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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 os
15
+ from typing import Callable, List, Optional, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from ..configuration_utils import ConfigMixin, register_to_config
21
+ from ..utils import logging
22
+ from .modeling_utils import ModelMixin
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ class MultiAdapter(ModelMixin):
29
+ r"""
30
+ MultiAdapter is a wrapper model that contains multiple adapter models and merges their outputs according to
31
+ user-assigned weighting.
32
+
33
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
34
+ implements for all the model (such as downloading or saving, etc.)
35
+
36
+ Parameters:
37
+ adapters (`List[T2IAdapter]`, *optional*, defaults to None):
38
+ A list of `T2IAdapter` model instances.
39
+ """
40
+
41
+ def __init__(self, adapters: List["T2IAdapter"]):
42
+ super(MultiAdapter, self).__init__()
43
+
44
+ self.num_adapter = len(adapters)
45
+ self.adapters = nn.ModuleList(adapters)
46
+
47
+ if len(adapters) == 0:
48
+ raise ValueError("Expecting at least one adapter")
49
+
50
+ if len(adapters) == 1:
51
+ raise ValueError("For a single adapter, please use the `T2IAdapter` class instead of `MultiAdapter`")
52
+
53
+ # The outputs from each adapter are added together with a weight.
54
+ # This means that the change in dimensions from downsampling must
55
+ # be the same for all adapters. Inductively, it also means the
56
+ # downscale_factor and total_downscale_factor must be the same for all
57
+ # adapters.
58
+ first_adapter_total_downscale_factor = adapters[0].total_downscale_factor
59
+ first_adapter_downscale_factor = adapters[0].downscale_factor
60
+ for idx in range(1, len(adapters)):
61
+ if (
62
+ adapters[idx].total_downscale_factor != first_adapter_total_downscale_factor
63
+ or adapters[idx].downscale_factor != first_adapter_downscale_factor
64
+ ):
65
+ raise ValueError(
66
+ f"Expecting all adapters to have the same downscaling behavior, but got:\n"
67
+ f"adapters[0].total_downscale_factor={first_adapter_total_downscale_factor}\n"
68
+ f"adapters[0].downscale_factor={first_adapter_downscale_factor}\n"
69
+ f"adapter[`{idx}`].total_downscale_factor={adapters[idx].total_downscale_factor}\n"
70
+ f"adapter[`{idx}`].downscale_factor={adapters[idx].downscale_factor}"
71
+ )
72
+
73
+ self.total_downscale_factor = first_adapter_total_downscale_factor
74
+ self.downscale_factor = first_adapter_downscale_factor
75
+
76
+ def forward(self, xs: torch.Tensor, adapter_weights: Optional[List[float]] = None) -> List[torch.Tensor]:
77
+ r"""
78
+ Args:
79
+ xs (`torch.Tensor`):
80
+ (batch, channel, height, width) input images for multiple adapter models concated along dimension 1,
81
+ `channel` should equal to `num_adapter` * "number of channel of image".
82
+ adapter_weights (`List[float]`, *optional*, defaults to None):
83
+ List of floats representing the weight which will be multiply to each adapter's output before adding
84
+ them together.
85
+ """
86
+ if adapter_weights is None:
87
+ adapter_weights = torch.tensor([1 / self.num_adapter] * self.num_adapter)
88
+ else:
89
+ adapter_weights = torch.tensor(adapter_weights)
90
+
91
+ accume_state = None
92
+ for x, w, adapter in zip(xs, adapter_weights, self.adapters):
93
+ features = adapter(x)
94
+ if accume_state is None:
95
+ accume_state = features
96
+ for i in range(len(accume_state)):
97
+ accume_state[i] = w * accume_state[i]
98
+ else:
99
+ for i in range(len(features)):
100
+ accume_state[i] += w * features[i]
101
+ return accume_state
102
+
103
+ def save_pretrained(
104
+ self,
105
+ save_directory: Union[str, os.PathLike],
106
+ is_main_process: bool = True,
107
+ save_function: Callable = None,
108
+ safe_serialization: bool = True,
109
+ variant: Optional[str] = None,
110
+ ):
111
+ """
112
+ Save a model and its configuration file to a directory, so that it can be re-loaded using the
113
+ `[`~models.adapter.MultiAdapter.from_pretrained`]` class method.
114
+
115
+ Arguments:
116
+ save_directory (`str` or `os.PathLike`):
117
+ Directory to which to save. Will be created if it doesn't exist.
118
+ is_main_process (`bool`, *optional*, defaults to `True`):
119
+ Whether the process calling this is the main process or not. Useful when in distributed training like
120
+ TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
121
+ the main process to avoid race conditions.
122
+ save_function (`Callable`):
123
+ The function to use to save the state dictionary. Useful on distributed training like TPUs when one
124
+ need to replace `torch.save` by another method. Can be configured with the environment variable
125
+ `DIFFUSERS_SAVE_MODE`.
126
+ safe_serialization (`bool`, *optional*, defaults to `True`):
127
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
128
+ variant (`str`, *optional*):
129
+ If specified, weights are saved in the format pytorch_model.<variant>.bin.
130
+ """
131
+ idx = 0
132
+ model_path_to_save = save_directory
133
+ for adapter in self.adapters:
134
+ adapter.save_pretrained(
135
+ model_path_to_save,
136
+ is_main_process=is_main_process,
137
+ save_function=save_function,
138
+ safe_serialization=safe_serialization,
139
+ variant=variant,
140
+ )
141
+
142
+ idx += 1
143
+ model_path_to_save = model_path_to_save + f"_{idx}"
144
+
145
+ @classmethod
146
+ def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
147
+ r"""
148
+ Instantiate a pretrained MultiAdapter model from multiple pre-trained adapter models.
149
+
150
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
151
+ the model, you should first set it back in training mode with `model.train()`.
152
+
153
+ The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
154
+ pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
155
+ task.
156
+
157
+ The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
158
+ weights are discarded.
159
+
160
+ Parameters:
161
+ pretrained_model_path (`os.PathLike`):
162
+ A path to a *directory* containing model weights saved using
163
+ [`~diffusers.models.adapter.MultiAdapter.save_pretrained`], e.g., `./my_model_directory/adapter`.
164
+ torch_dtype (`str` or `torch.dtype`, *optional*):
165
+ Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
166
+ will be automatically derived from the model's weights.
167
+ output_loading_info(`bool`, *optional*, defaults to `False`):
168
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
169
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
170
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
171
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
172
+ same device.
173
+
174
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
175
+ more information about each option see [designing a device
176
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
177
+ max_memory (`Dict`, *optional*):
178
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
179
+ GPU and the available CPU RAM if unset.
180
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
181
+ Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
182
+ also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
183
+ model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
184
+ setting this argument to `True` will raise an error.
185
+ variant (`str`, *optional*):
186
+ If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is
187
+ ignored when using `from_flax`.
188
+ use_safetensors (`bool`, *optional*, defaults to `None`):
189
+ If set to `None`, the `safetensors` weights will be downloaded if they're available **and** if the
190
+ `safetensors` library is installed. If set to `True`, the model will be forcibly loaded from
191
+ `safetensors` weights. If set to `False`, loading will *not* use `safetensors`.
192
+ """
193
+ idx = 0
194
+ adapters = []
195
+
196
+ # load adapter and append to list until no adapter directory exists anymore
197
+ # first adapter has to be saved under `./mydirectory/adapter` to be compliant with `DiffusionPipeline.from_pretrained`
198
+ # second, third, ... adapters have to be saved under `./mydirectory/adapter_1`, `./mydirectory/adapter_2`, ...
199
+ model_path_to_load = pretrained_model_path
200
+ while os.path.isdir(model_path_to_load):
201
+ adapter = T2IAdapter.from_pretrained(model_path_to_load, **kwargs)
202
+ adapters.append(adapter)
203
+
204
+ idx += 1
205
+ model_path_to_load = pretrained_model_path + f"_{idx}"
206
+
207
+ logger.info(f"{len(adapters)} adapters loaded from {pretrained_model_path}.")
208
+
209
+ if len(adapters) == 0:
210
+ raise ValueError(
211
+ f"No T2IAdapters found under {os.path.dirname(pretrained_model_path)}. Expected at least {pretrained_model_path + '_0'}."
212
+ )
213
+
214
+ return cls(adapters)
215
+
216
+
217
+ class T2IAdapter(ModelMixin, ConfigMixin):
218
+ r"""
219
+ A simple ResNet-like model that accepts images containing control signals such as keyposes and depth. The model
220
+ generates multiple feature maps that are used as additional conditioning in [`UNet2DConditionModel`]. The model's
221
+ architecture follows the original implementation of
222
+ [Adapter](https://github.com/TencentARC/T2I-Adapter/blob/686de4681515662c0ac2ffa07bf5dda83af1038a/ldm/modules/encoders/adapter.py#L97)
223
+ and
224
+ [AdapterLight](https://github.com/TencentARC/T2I-Adapter/blob/686de4681515662c0ac2ffa07bf5dda83af1038a/ldm/modules/encoders/adapter.py#L235).
225
+
226
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
227
+ implements for all the model (such as downloading or saving, etc.)
228
+
229
+ Parameters:
230
+ in_channels (`int`, *optional*, defaults to 3):
231
+ Number of channels of Aapter's input(*control image*). Set this parameter to 1 if you're using gray scale
232
+ image as *control image*.
233
+ channels (`List[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
234
+ The number of channel of each downsample block's output hidden state. The `len(block_out_channels)` will
235
+ also determine the number of downsample blocks in the Adapter.
236
+ num_res_blocks (`int`, *optional*, defaults to 2):
237
+ Number of ResNet blocks in each downsample block.
238
+ downscale_factor (`int`, *optional*, defaults to 8):
239
+ A factor that determines the total downscale factor of the Adapter.
240
+ adapter_type (`str`, *optional*, defaults to `full_adapter`):
241
+ The type of Adapter to use. Choose either `full_adapter` or `full_adapter_xl` or `light_adapter`.
242
+ """
243
+
244
+ @register_to_config
245
+ def __init__(
246
+ self,
247
+ in_channels: int = 3,
248
+ channels: List[int] = [320, 640, 1280, 1280],
249
+ num_res_blocks: int = 2,
250
+ downscale_factor: int = 8,
251
+ adapter_type: str = "full_adapter",
252
+ ):
253
+ super().__init__()
254
+
255
+ if adapter_type == "full_adapter":
256
+ self.adapter = FullAdapter(in_channels, channels, num_res_blocks, downscale_factor)
257
+ elif adapter_type == "full_adapter_xl":
258
+ self.adapter = FullAdapterXL(in_channels, channels, num_res_blocks, downscale_factor)
259
+ elif adapter_type == "light_adapter":
260
+ self.adapter = LightAdapter(in_channels, channels, num_res_blocks, downscale_factor)
261
+ else:
262
+ raise ValueError(
263
+ f"Unsupported adapter_type: '{adapter_type}'. Choose either 'full_adapter' or "
264
+ "'full_adapter_xl' or 'light_adapter'."
265
+ )
266
+
267
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
268
+ r"""
269
+ This function processes the input tensor `x` through the adapter model and returns a list of feature tensors,
270
+ each representing information extracted at a different scale from the input. The length of the list is
271
+ determined by the number of downsample blocks in the Adapter, as specified by the `channels` and
272
+ `num_res_blocks` parameters during initialization.
273
+ """
274
+ return self.adapter(x)
275
+
276
+ @property
277
+ def total_downscale_factor(self):
278
+ return self.adapter.total_downscale_factor
279
+
280
+ @property
281
+ def downscale_factor(self):
282
+ """The downscale factor applied in the T2I-Adapter's initial pixel unshuffle operation. If an input image's dimensions are
283
+ not evenly divisible by the downscale_factor then an exception will be raised.
284
+ """
285
+ return self.adapter.unshuffle.downscale_factor
286
+
287
+
288
+ # full adapter
289
+
290
+
291
+ class FullAdapter(nn.Module):
292
+ r"""
293
+ See [`T2IAdapter`] for more information.
294
+ """
295
+
296
+ def __init__(
297
+ self,
298
+ in_channels: int = 3,
299
+ channels: List[int] = [320, 640, 1280, 1280],
300
+ num_res_blocks: int = 2,
301
+ downscale_factor: int = 8,
302
+ ):
303
+ super().__init__()
304
+
305
+ in_channels = in_channels * downscale_factor**2
306
+
307
+ self.unshuffle = nn.PixelUnshuffle(downscale_factor)
308
+ self.conv_in = nn.Conv2d(in_channels, channels[0], kernel_size=3, padding=1)
309
+
310
+ self.body = nn.ModuleList(
311
+ [
312
+ AdapterBlock(channels[0], channels[0], num_res_blocks),
313
+ *[
314
+ AdapterBlock(channels[i - 1], channels[i], num_res_blocks, down=True)
315
+ for i in range(1, len(channels))
316
+ ],
317
+ ]
318
+ )
319
+
320
+ self.total_downscale_factor = downscale_factor * 2 ** (len(channels) - 1)
321
+
322
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
323
+ r"""
324
+ This method processes the input tensor `x` through the FullAdapter model and performs operations including
325
+ pixel unshuffling, convolution, and a stack of AdapterBlocks. It returns a list of feature tensors, each
326
+ capturing information at a different stage of processing within the FullAdapter model. The number of feature
327
+ tensors in the list is determined by the number of downsample blocks specified during initialization.
328
+ """
329
+ x = self.unshuffle(x)
330
+ x = self.conv_in(x)
331
+
332
+ features = []
333
+
334
+ for block in self.body:
335
+ x = block(x)
336
+ features.append(x)
337
+
338
+ return features
339
+
340
+
341
+ class FullAdapterXL(nn.Module):
342
+ r"""
343
+ See [`T2IAdapter`] for more information.
344
+ """
345
+
346
+ def __init__(
347
+ self,
348
+ in_channels: int = 3,
349
+ channels: List[int] = [320, 640, 1280, 1280],
350
+ num_res_blocks: int = 2,
351
+ downscale_factor: int = 16,
352
+ ):
353
+ super().__init__()
354
+
355
+ in_channels = in_channels * downscale_factor**2
356
+
357
+ self.unshuffle = nn.PixelUnshuffle(downscale_factor)
358
+ self.conv_in = nn.Conv2d(in_channels, channels[0], kernel_size=3, padding=1)
359
+
360
+ self.body = []
361
+ # blocks to extract XL features with dimensions of [320, 64, 64], [640, 64, 64], [1280, 32, 32], [1280, 32, 32]
362
+ for i in range(len(channels)):
363
+ if i == 1:
364
+ self.body.append(AdapterBlock(channels[i - 1], channels[i], num_res_blocks))
365
+ elif i == 2:
366
+ self.body.append(AdapterBlock(channels[i - 1], channels[i], num_res_blocks, down=True))
367
+ else:
368
+ self.body.append(AdapterBlock(channels[i], channels[i], num_res_blocks))
369
+
370
+ self.body = nn.ModuleList(self.body)
371
+ # XL has only one downsampling AdapterBlock.
372
+ self.total_downscale_factor = downscale_factor * 2
373
+
374
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
375
+ r"""
376
+ This method takes the tensor x as input and processes it through FullAdapterXL model. It consists of operations
377
+ including unshuffling pixels, applying convolution layer and appending each block into list of feature tensors.
378
+ """
379
+ x = self.unshuffle(x)
380
+ x = self.conv_in(x)
381
+
382
+ features = []
383
+
384
+ for block in self.body:
385
+ x = block(x)
386
+ features.append(x)
387
+
388
+ return features
389
+
390
+
391
+ class AdapterBlock(nn.Module):
392
+ r"""
393
+ An AdapterBlock is a helper model that contains multiple ResNet-like blocks. It is used in the `FullAdapter` and
394
+ `FullAdapterXL` models.
395
+
396
+ Parameters:
397
+ in_channels (`int`):
398
+ Number of channels of AdapterBlock's input.
399
+ out_channels (`int`):
400
+ Number of channels of AdapterBlock's output.
401
+ num_res_blocks (`int`):
402
+ Number of ResNet blocks in the AdapterBlock.
403
+ down (`bool`, *optional*, defaults to `False`):
404
+ Whether to perform downsampling on AdapterBlock's input.
405
+ """
406
+
407
+ def __init__(self, in_channels: int, out_channels: int, num_res_blocks: int, down: bool = False):
408
+ super().__init__()
409
+
410
+ self.downsample = None
411
+ if down:
412
+ self.downsample = nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True)
413
+
414
+ self.in_conv = None
415
+ if in_channels != out_channels:
416
+ self.in_conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
417
+
418
+ self.resnets = nn.Sequential(
419
+ *[AdapterResnetBlock(out_channels) for _ in range(num_res_blocks)],
420
+ )
421
+
422
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
423
+ r"""
424
+ This method takes tensor x as input and performs operations downsampling and convolutional layers if the
425
+ self.downsample and self.in_conv properties of AdapterBlock model are specified. Then it applies a series of
426
+ residual blocks to the input tensor.
427
+ """
428
+ if self.downsample is not None:
429
+ x = self.downsample(x)
430
+
431
+ if self.in_conv is not None:
432
+ x = self.in_conv(x)
433
+
434
+ x = self.resnets(x)
435
+
436
+ return x
437
+
438
+
439
+ class AdapterResnetBlock(nn.Module):
440
+ r"""
441
+ An `AdapterResnetBlock` is a helper model that implements a ResNet-like block.
442
+
443
+ Parameters:
444
+ channels (`int`):
445
+ Number of channels of AdapterResnetBlock's input and output.
446
+ """
447
+
448
+ def __init__(self, channels: int):
449
+ super().__init__()
450
+ self.block1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
451
+ self.act = nn.ReLU()
452
+ self.block2 = nn.Conv2d(channels, channels, kernel_size=1)
453
+
454
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
455
+ r"""
456
+ This method takes input tensor x and applies a convolutional layer, ReLU activation, and another convolutional
457
+ layer on the input tensor. It returns addition with the input tensor.
458
+ """
459
+
460
+ h = self.act(self.block1(x))
461
+ h = self.block2(h)
462
+
463
+ return h + x
464
+
465
+
466
+ # light adapter
467
+
468
+
469
+ class LightAdapter(nn.Module):
470
+ r"""
471
+ See [`T2IAdapter`] for more information.
472
+ """
473
+
474
+ def __init__(
475
+ self,
476
+ in_channels: int = 3,
477
+ channels: List[int] = [320, 640, 1280],
478
+ num_res_blocks: int = 4,
479
+ downscale_factor: int = 8,
480
+ ):
481
+ super().__init__()
482
+
483
+ in_channels = in_channels * downscale_factor**2
484
+
485
+ self.unshuffle = nn.PixelUnshuffle(downscale_factor)
486
+
487
+ self.body = nn.ModuleList(
488
+ [
489
+ LightAdapterBlock(in_channels, channels[0], num_res_blocks),
490
+ *[
491
+ LightAdapterBlock(channels[i], channels[i + 1], num_res_blocks, down=True)
492
+ for i in range(len(channels) - 1)
493
+ ],
494
+ LightAdapterBlock(channels[-1], channels[-1], num_res_blocks, down=True),
495
+ ]
496
+ )
497
+
498
+ self.total_downscale_factor = downscale_factor * (2 ** len(channels))
499
+
500
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
501
+ r"""
502
+ This method takes the input tensor x and performs downscaling and appends it in list of feature tensors. Each
503
+ feature tensor corresponds to a different level of processing within the LightAdapter.
504
+ """
505
+ x = self.unshuffle(x)
506
+
507
+ features = []
508
+
509
+ for block in self.body:
510
+ x = block(x)
511
+ features.append(x)
512
+
513
+ return features
514
+
515
+
516
+ class LightAdapterBlock(nn.Module):
517
+ r"""
518
+ A `LightAdapterBlock` is a helper model that contains multiple `LightAdapterResnetBlocks`. It is used in the
519
+ `LightAdapter` model.
520
+
521
+ Parameters:
522
+ in_channels (`int`):
523
+ Number of channels of LightAdapterBlock's input.
524
+ out_channels (`int`):
525
+ Number of channels of LightAdapterBlock's output.
526
+ num_res_blocks (`int`):
527
+ Number of LightAdapterResnetBlocks in the LightAdapterBlock.
528
+ down (`bool`, *optional*, defaults to `False`):
529
+ Whether to perform downsampling on LightAdapterBlock's input.
530
+ """
531
+
532
+ def __init__(self, in_channels: int, out_channels: int, num_res_blocks: int, down: bool = False):
533
+ super().__init__()
534
+ mid_channels = out_channels // 4
535
+
536
+ self.downsample = None
537
+ if down:
538
+ self.downsample = nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True)
539
+
540
+ self.in_conv = nn.Conv2d(in_channels, mid_channels, kernel_size=1)
541
+ self.resnets = nn.Sequential(*[LightAdapterResnetBlock(mid_channels) for _ in range(num_res_blocks)])
542
+ self.out_conv = nn.Conv2d(mid_channels, out_channels, kernel_size=1)
543
+
544
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
545
+ r"""
546
+ This method takes tensor x as input and performs downsampling if required. Then it applies in convolution
547
+ layer, a sequence of residual blocks, and out convolutional layer.
548
+ """
549
+ if self.downsample is not None:
550
+ x = self.downsample(x)
551
+
552
+ x = self.in_conv(x)
553
+ x = self.resnets(x)
554
+ x = self.out_conv(x)
555
+
556
+ return x
557
+
558
+
559
+ class LightAdapterResnetBlock(nn.Module):
560
+ """
561
+ A `LightAdapterResnetBlock` is a helper model that implements a ResNet-like block with a slightly different
562
+ architecture than `AdapterResnetBlock`.
563
+
564
+ Parameters:
565
+ channels (`int`):
566
+ Number of channels of LightAdapterResnetBlock's input and output.
567
+ """
568
+
569
+ def __init__(self, channels: int):
570
+ super().__init__()
571
+ self.block1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
572
+ self.act = nn.ReLU()
573
+ self.block2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
574
+
575
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
576
+ r"""
577
+ This function takes input tensor x and processes it through one convolutional layer, ReLU activation, and
578
+ another convolutional layer and adds it to input tensor.
579
+ """
580
+
581
+ h = self.act(self.block1(x))
582
+ h = self.block2(h)
583
+
584
+ return h + x
diffusers/models/attention.py ADDED
@@ -0,0 +1,547 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 Any, Dict, Optional
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ..utils import USE_PEFT_BACKEND
20
+ from ..utils.torch_utils import maybe_allow_in_graph
21
+ from .activations import GEGLU, GELU, ApproximateGELU
22
+ from .attention_processor import Attention
23
+ from .embeddings import SinusoidalPositionalEmbedding
24
+ from .lora import LoRACompatibleLinear
25
+ from .normalization import AdaLayerNorm, AdaLayerNormZero
26
+
27
+
28
+ def _chunked_feed_forward(
29
+ ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int, lora_scale: Optional[float] = None
30
+ ):
31
+ # "feed_forward_chunk_size" can be used to save memory
32
+ if hidden_states.shape[chunk_dim] % chunk_size != 0:
33
+ raise ValueError(
34
+ f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
35
+ )
36
+
37
+ num_chunks = hidden_states.shape[chunk_dim] // chunk_size
38
+ if lora_scale is None:
39
+ ff_output = torch.cat(
40
+ [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
41
+ dim=chunk_dim,
42
+ )
43
+ else:
44
+ # TOOD(Patrick): LoRA scale can be removed once PEFT refactor is complete
45
+ ff_output = torch.cat(
46
+ [ff(hid_slice, scale=lora_scale) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
47
+ dim=chunk_dim,
48
+ )
49
+
50
+ return ff_output
51
+
52
+
53
+ @maybe_allow_in_graph
54
+ class GatedSelfAttentionDense(nn.Module):
55
+ r"""
56
+ A gated self-attention dense layer that combines visual features and object features.
57
+
58
+ Parameters:
59
+ query_dim (`int`): The number of channels in the query.
60
+ context_dim (`int`): The number of channels in the context.
61
+ n_heads (`int`): The number of heads to use for attention.
62
+ d_head (`int`): The number of channels in each head.
63
+ """
64
+
65
+ def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
66
+ super().__init__()
67
+
68
+ # we need a linear projection since we need cat visual feature and obj feature
69
+ self.linear = nn.Linear(context_dim, query_dim)
70
+
71
+ self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
72
+ self.ff = FeedForward(query_dim, activation_fn="geglu")
73
+
74
+ self.norm1 = nn.LayerNorm(query_dim)
75
+ self.norm2 = nn.LayerNorm(query_dim)
76
+
77
+ self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
78
+ self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
79
+
80
+ self.enabled = True
81
+
82
+ def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
83
+ if not self.enabled:
84
+ return x
85
+
86
+ n_visual = x.shape[1]
87
+ objs = self.linear(objs)
88
+
89
+ x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
90
+ x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
91
+
92
+ return x
93
+
94
+
95
+ @maybe_allow_in_graph
96
+ class BasicTransformerBlock(nn.Module):
97
+ r"""
98
+ A basic Transformer block.
99
+
100
+ Parameters:
101
+ dim (`int`): The number of channels in the input and output.
102
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
103
+ attention_head_dim (`int`): The number of channels in each head.
104
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
105
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
106
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
107
+ num_embeds_ada_norm (:
108
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
109
+ attention_bias (:
110
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
111
+ only_cross_attention (`bool`, *optional*):
112
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
113
+ double_self_attention (`bool`, *optional*):
114
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
115
+ upcast_attention (`bool`, *optional*):
116
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
117
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
118
+ Whether to use learnable elementwise affine parameters for normalization.
119
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
120
+ The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
121
+ final_dropout (`bool` *optional*, defaults to False):
122
+ Whether to apply a final dropout after the last feed-forward layer.
123
+ attention_type (`str`, *optional*, defaults to `"default"`):
124
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
125
+ positional_embeddings (`str`, *optional*, defaults to `None`):
126
+ The type of positional embeddings to apply to.
127
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
128
+ The maximum number of positional embeddings to apply.
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ dim: int,
134
+ num_attention_heads: int,
135
+ attention_head_dim: int,
136
+ dropout=0.0,
137
+ cross_attention_dim: Optional[int] = None,
138
+ activation_fn: str = "geglu",
139
+ num_embeds_ada_norm: Optional[int] = None,
140
+ attention_bias: bool = False,
141
+ only_cross_attention: bool = False,
142
+ double_self_attention: bool = False,
143
+ upcast_attention: bool = False,
144
+ norm_elementwise_affine: bool = True,
145
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
146
+ norm_eps: float = 1e-5,
147
+ final_dropout: bool = False,
148
+ attention_type: str = "default",
149
+ positional_embeddings: Optional[str] = None,
150
+ num_positional_embeddings: Optional[int] = None,
151
+ ):
152
+ super().__init__()
153
+ self.only_cross_attention = only_cross_attention
154
+
155
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
156
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
157
+ self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
158
+ self.use_layer_norm = norm_type == "layer_norm"
159
+
160
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
161
+ raise ValueError(
162
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
163
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
164
+ )
165
+
166
+ if positional_embeddings and (num_positional_embeddings is None):
167
+ raise ValueError(
168
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
169
+ )
170
+
171
+ if positional_embeddings == "sinusoidal":
172
+ self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
173
+ else:
174
+ self.pos_embed = None
175
+
176
+ # Define 3 blocks. Each block has its own normalization layer.
177
+ # 1. Self-Attn
178
+ if self.use_ada_layer_norm:
179
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
180
+ elif self.use_ada_layer_norm_zero:
181
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
182
+ else:
183
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
184
+
185
+ self.attn1 = Attention(
186
+ query_dim=dim,
187
+ heads=num_attention_heads,
188
+ dim_head=attention_head_dim,
189
+ dropout=dropout,
190
+ bias=attention_bias,
191
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
192
+ upcast_attention=upcast_attention,
193
+ )
194
+
195
+ # 2. Cross-Attn
196
+ if cross_attention_dim is not None or double_self_attention:
197
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
198
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
199
+ # the second cross attention block.
200
+ self.norm2 = (
201
+ AdaLayerNorm(dim, num_embeds_ada_norm)
202
+ if self.use_ada_layer_norm
203
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
204
+ )
205
+ self.attn2 = Attention(
206
+ query_dim=dim,
207
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
208
+ heads=num_attention_heads,
209
+ dim_head=attention_head_dim,
210
+ dropout=dropout,
211
+ bias=attention_bias,
212
+ upcast_attention=upcast_attention,
213
+ ) # is self-attn if encoder_hidden_states is none
214
+ else:
215
+ self.norm2 = None
216
+ self.attn2 = None
217
+
218
+ # 3. Feed-forward
219
+ if not self.use_ada_layer_norm_single:
220
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
221
+
222
+ self.ff = FeedForward(
223
+ dim,
224
+ dropout=dropout,
225
+ activation_fn=activation_fn,
226
+ final_dropout=final_dropout,
227
+ )
228
+
229
+ # 4. Fuser
230
+ if attention_type == "gated" or attention_type == "gated-text-image":
231
+ self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
232
+
233
+ # 5. Scale-shift for PixArt-Alpha.
234
+ if self.use_ada_layer_norm_single:
235
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
236
+
237
+ # let chunk size default to None
238
+ self._chunk_size = None
239
+ self._chunk_dim = 0
240
+
241
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
242
+ # Sets chunk feed-forward
243
+ self._chunk_size = chunk_size
244
+ self._chunk_dim = dim
245
+
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.FloatTensor,
249
+ attention_mask: Optional[torch.FloatTensor] = None,
250
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
251
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
252
+ timestep: Optional[torch.LongTensor] = None,
253
+ cross_attention_kwargs: Dict[str, Any] = None,
254
+ class_labels: Optional[torch.LongTensor] = None,
255
+ ) -> torch.FloatTensor:
256
+ # Notice that normalization is always applied before the real computation in the following blocks.
257
+ # 0. Self-Attention
258
+ batch_size = hidden_states.shape[0]
259
+
260
+ if self.use_ada_layer_norm:
261
+ norm_hidden_states = self.norm1(hidden_states, timestep)
262
+ elif self.use_ada_layer_norm_zero:
263
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
264
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
265
+ )
266
+ elif self.use_layer_norm:
267
+ norm_hidden_states = self.norm1(hidden_states)
268
+ elif self.use_ada_layer_norm_single:
269
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
270
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
271
+ ).chunk(6, dim=1)
272
+ norm_hidden_states = self.norm1(hidden_states)
273
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
274
+ norm_hidden_states = norm_hidden_states.squeeze(1)
275
+ else:
276
+ raise ValueError("Incorrect norm used")
277
+
278
+ if self.pos_embed is not None:
279
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
280
+
281
+ # 1. Retrieve lora scale.
282
+ lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
283
+
284
+ # 2. Prepare GLIGEN inputs
285
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
286
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
287
+
288
+ attn_output = self.attn1(
289
+ norm_hidden_states,
290
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
291
+ attention_mask=attention_mask,
292
+ **cross_attention_kwargs,
293
+ )
294
+ if self.use_ada_layer_norm_zero:
295
+ attn_output = gate_msa.unsqueeze(1) * attn_output
296
+ elif self.use_ada_layer_norm_single:
297
+ attn_output = gate_msa * attn_output
298
+
299
+ hidden_states = attn_output + hidden_states
300
+ if hidden_states.ndim == 4:
301
+ hidden_states = hidden_states.squeeze(1)
302
+
303
+ # 2.5 GLIGEN Control
304
+ if gligen_kwargs is not None:
305
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
306
+
307
+ # 3. Cross-Attention
308
+ if self.attn2 is not None:
309
+ if self.use_ada_layer_norm:
310
+ norm_hidden_states = self.norm2(hidden_states, timestep)
311
+ elif self.use_ada_layer_norm_zero or self.use_layer_norm:
312
+ norm_hidden_states = self.norm2(hidden_states)
313
+ elif self.use_ada_layer_norm_single:
314
+ # For PixArt norm2 isn't applied here:
315
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
316
+ norm_hidden_states = hidden_states
317
+ else:
318
+ raise ValueError("Incorrect norm")
319
+
320
+ if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
321
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
322
+
323
+ attn_output = self.attn2(
324
+ norm_hidden_states,
325
+ encoder_hidden_states=encoder_hidden_states,
326
+ attention_mask=encoder_attention_mask,
327
+ **cross_attention_kwargs,
328
+ )
329
+ hidden_states = attn_output + hidden_states
330
+
331
+ # 4. Feed-forward
332
+ if not self.use_ada_layer_norm_single:
333
+ norm_hidden_states = self.norm3(hidden_states)
334
+
335
+ if self.use_ada_layer_norm_zero:
336
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
337
+
338
+ if self.use_ada_layer_norm_single:
339
+ norm_hidden_states = self.norm2(hidden_states)
340
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
341
+
342
+ if self._chunk_size is not None:
343
+ # "feed_forward_chunk_size" can be used to save memory
344
+ ff_output = _chunked_feed_forward(
345
+ self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size, lora_scale=lora_scale
346
+ )
347
+ else:
348
+ ff_output = self.ff(norm_hidden_states, scale=lora_scale)
349
+
350
+ if self.use_ada_layer_norm_zero:
351
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
352
+ elif self.use_ada_layer_norm_single:
353
+ ff_output = gate_mlp * ff_output
354
+
355
+ hidden_states = ff_output + hidden_states
356
+ if hidden_states.ndim == 4:
357
+ hidden_states = hidden_states.squeeze(1)
358
+
359
+ return hidden_states
360
+
361
+
362
+ @maybe_allow_in_graph
363
+ class TemporalBasicTransformerBlock(nn.Module):
364
+ r"""
365
+ A basic Transformer block for video like data.
366
+
367
+ Parameters:
368
+ dim (`int`): The number of channels in the input and output.
369
+ time_mix_inner_dim (`int`): The number of channels for temporal attention.
370
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
371
+ attention_head_dim (`int`): The number of channels in each head.
372
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
373
+ """
374
+
375
+ def __init__(
376
+ self,
377
+ dim: int,
378
+ time_mix_inner_dim: int,
379
+ num_attention_heads: int,
380
+ attention_head_dim: int,
381
+ cross_attention_dim: Optional[int] = None,
382
+ ):
383
+ super().__init__()
384
+ self.is_res = dim == time_mix_inner_dim
385
+
386
+ self.norm_in = nn.LayerNorm(dim)
387
+
388
+ # Define 3 blocks. Each block has its own normalization layer.
389
+ # 1. Self-Attn
390
+ self.norm_in = nn.LayerNorm(dim)
391
+ self.ff_in = FeedForward(
392
+ dim,
393
+ dim_out=time_mix_inner_dim,
394
+ activation_fn="geglu",
395
+ )
396
+
397
+ self.norm1 = nn.LayerNorm(time_mix_inner_dim)
398
+ self.attn1 = Attention(
399
+ query_dim=time_mix_inner_dim,
400
+ heads=num_attention_heads,
401
+ dim_head=attention_head_dim,
402
+ cross_attention_dim=None,
403
+ )
404
+
405
+ # 2. Cross-Attn
406
+ if cross_attention_dim is not None:
407
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
408
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
409
+ # the second cross attention block.
410
+ self.norm2 = nn.LayerNorm(time_mix_inner_dim)
411
+ self.attn2 = Attention(
412
+ query_dim=time_mix_inner_dim,
413
+ cross_attention_dim=cross_attention_dim,
414
+ heads=num_attention_heads,
415
+ dim_head=attention_head_dim,
416
+ ) # is self-attn if encoder_hidden_states is none
417
+ else:
418
+ self.norm2 = None
419
+ self.attn2 = None
420
+
421
+ # 3. Feed-forward
422
+ self.norm3 = nn.LayerNorm(time_mix_inner_dim)
423
+ self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
424
+
425
+ # let chunk size default to None
426
+ self._chunk_size = None
427
+ self._chunk_dim = None
428
+
429
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
430
+ # Sets chunk feed-forward
431
+ self._chunk_size = chunk_size
432
+ # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
433
+ self._chunk_dim = 1
434
+
435
+ def forward(
436
+ self,
437
+ hidden_states: torch.FloatTensor,
438
+ num_frames: int,
439
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
440
+ ) -> torch.FloatTensor:
441
+ # Notice that normalization is always applied before the real computation in the following blocks.
442
+ # 0. Self-Attention
443
+ batch_size = hidden_states.shape[0]
444
+
445
+ batch_frames, seq_length, channels = hidden_states.shape
446
+ batch_size = batch_frames // num_frames
447
+
448
+ hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
449
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
450
+ hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
451
+
452
+ residual = hidden_states
453
+ hidden_states = self.norm_in(hidden_states)
454
+
455
+ if self._chunk_size is not None:
456
+ hidden_states = _chunked_feed_forward(self.ff, hidden_states, self._chunk_dim, self._chunk_size)
457
+ else:
458
+ hidden_states = self.ff_in(hidden_states)
459
+
460
+ if self.is_res:
461
+ hidden_states = hidden_states + residual
462
+
463
+ norm_hidden_states = self.norm1(hidden_states)
464
+ attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
465
+ hidden_states = attn_output + hidden_states
466
+
467
+ # 3. Cross-Attention
468
+ if self.attn2 is not None:
469
+ norm_hidden_states = self.norm2(hidden_states)
470
+ attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
471
+ hidden_states = attn_output + hidden_states
472
+
473
+ # 4. Feed-forward
474
+ norm_hidden_states = self.norm3(hidden_states)
475
+
476
+ if self._chunk_size is not None:
477
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
478
+ else:
479
+ ff_output = self.ff(norm_hidden_states)
480
+
481
+ if self.is_res:
482
+ hidden_states = ff_output + hidden_states
483
+ else:
484
+ hidden_states = ff_output
485
+
486
+ hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
487
+ hidden_states = hidden_states.permute(0, 2, 1, 3)
488
+ hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
489
+
490
+ return hidden_states
491
+
492
+
493
+ class FeedForward(nn.Module):
494
+ r"""
495
+ A feed-forward layer.
496
+
497
+ Parameters:
498
+ dim (`int`): The number of channels in the input.
499
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
500
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
501
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
502
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
503
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
504
+ """
505
+
506
+ def __init__(
507
+ self,
508
+ dim: int,
509
+ dim_out: Optional[int] = None,
510
+ mult: int = 4,
511
+ dropout: float = 0.0,
512
+ activation_fn: str = "geglu",
513
+ final_dropout: bool = False,
514
+ ):
515
+ super().__init__()
516
+ inner_dim = int(dim * mult)
517
+ dim_out = dim_out if dim_out is not None else dim
518
+ linear_cls = LoRACompatibleLinear if not USE_PEFT_BACKEND else nn.Linear
519
+
520
+ if activation_fn == "gelu":
521
+ act_fn = GELU(dim, inner_dim)
522
+ if activation_fn == "gelu-approximate":
523
+ act_fn = GELU(dim, inner_dim, approximate="tanh")
524
+ elif activation_fn == "geglu":
525
+ act_fn = GEGLU(dim, inner_dim)
526
+ elif activation_fn == "geglu-approximate":
527
+ act_fn = ApproximateGELU(dim, inner_dim)
528
+
529
+ self.net = nn.ModuleList([])
530
+ # project in
531
+ self.net.append(act_fn)
532
+ # project dropout
533
+ self.net.append(nn.Dropout(dropout))
534
+ # project out
535
+ self.net.append(linear_cls(inner_dim, dim_out))
536
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
537
+ if final_dropout:
538
+ self.net.append(nn.Dropout(dropout))
539
+
540
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
541
+ compatible_cls = (GEGLU,) if USE_PEFT_BACKEND else (GEGLU, LoRACompatibleLinear)
542
+ for module in self.net:
543
+ if isinstance(module, compatible_cls):
544
+ hidden_states = module(hidden_states, scale)
545
+ else:
546
+ hidden_states = module(hidden_states)
547
+ return hidden_states
diffusers/models/attention_flax.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 functools
16
+ import math
17
+
18
+ import flax.linen as nn
19
+ import jax
20
+ import jax.numpy as jnp
21
+
22
+
23
+ def _query_chunk_attention(query, key, value, precision, key_chunk_size: int = 4096):
24
+ """Multi-head dot product attention with a limited number of queries."""
25
+ num_kv, num_heads, k_features = key.shape[-3:]
26
+ v_features = value.shape[-1]
27
+ key_chunk_size = min(key_chunk_size, num_kv)
28
+ query = query / jnp.sqrt(k_features)
29
+
30
+ @functools.partial(jax.checkpoint, prevent_cse=False)
31
+ def summarize_chunk(query, key, value):
32
+ attn_weights = jnp.einsum("...qhd,...khd->...qhk", query, key, precision=precision)
33
+
34
+ max_score = jnp.max(attn_weights, axis=-1, keepdims=True)
35
+ max_score = jax.lax.stop_gradient(max_score)
36
+ exp_weights = jnp.exp(attn_weights - max_score)
37
+
38
+ exp_values = jnp.einsum("...vhf,...qhv->...qhf", value, exp_weights, precision=precision)
39
+ max_score = jnp.einsum("...qhk->...qh", max_score)
40
+
41
+ return (exp_values, exp_weights.sum(axis=-1), max_score)
42
+
43
+ def chunk_scanner(chunk_idx):
44
+ # julienne key array
45
+ key_chunk = jax.lax.dynamic_slice(
46
+ operand=key,
47
+ start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0], # [...,k,h,d]
48
+ slice_sizes=list(key.shape[:-3]) + [key_chunk_size, num_heads, k_features], # [...,k,h,d]
49
+ )
50
+
51
+ # julienne value array
52
+ value_chunk = jax.lax.dynamic_slice(
53
+ operand=value,
54
+ start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0], # [...,v,h,d]
55
+ slice_sizes=list(value.shape[:-3]) + [key_chunk_size, num_heads, v_features], # [...,v,h,d]
56
+ )
57
+
58
+ return summarize_chunk(query, key_chunk, value_chunk)
59
+
60
+ chunk_values, chunk_weights, chunk_max = jax.lax.map(f=chunk_scanner, xs=jnp.arange(0, num_kv, key_chunk_size))
61
+
62
+ global_max = jnp.max(chunk_max, axis=0, keepdims=True)
63
+ max_diffs = jnp.exp(chunk_max - global_max)
64
+
65
+ chunk_values *= jnp.expand_dims(max_diffs, axis=-1)
66
+ chunk_weights *= max_diffs
67
+
68
+ all_values = chunk_values.sum(axis=0)
69
+ all_weights = jnp.expand_dims(chunk_weights, -1).sum(axis=0)
70
+
71
+ return all_values / all_weights
72
+
73
+
74
+ def jax_memory_efficient_attention(
75
+ query, key, value, precision=jax.lax.Precision.HIGHEST, query_chunk_size: int = 1024, key_chunk_size: int = 4096
76
+ ):
77
+ r"""
78
+ Flax Memory-efficient multi-head dot product attention. https://arxiv.org/abs/2112.05682v2
79
+ https://github.com/AminRezaei0x443/memory-efficient-attention
80
+
81
+ Args:
82
+ query (`jnp.ndarray`): (batch..., query_length, head, query_key_depth_per_head)
83
+ key (`jnp.ndarray`): (batch..., key_value_length, head, query_key_depth_per_head)
84
+ value (`jnp.ndarray`): (batch..., key_value_length, head, value_depth_per_head)
85
+ precision (`jax.lax.Precision`, *optional*, defaults to `jax.lax.Precision.HIGHEST`):
86
+ numerical precision for computation
87
+ query_chunk_size (`int`, *optional*, defaults to 1024):
88
+ chunk size to divide query array value must divide query_length equally without remainder
89
+ key_chunk_size (`int`, *optional*, defaults to 4096):
90
+ chunk size to divide key and value array value must divide key_value_length equally without remainder
91
+
92
+ Returns:
93
+ (`jnp.ndarray`) with shape of (batch..., query_length, head, value_depth_per_head)
94
+ """
95
+ num_q, num_heads, q_features = query.shape[-3:]
96
+
97
+ def chunk_scanner(chunk_idx, _):
98
+ # julienne query array
99
+ query_chunk = jax.lax.dynamic_slice(
100
+ operand=query,
101
+ start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0], # [...,q,h,d]
102
+ slice_sizes=list(query.shape[:-3]) + [min(query_chunk_size, num_q), num_heads, q_features], # [...,q,h,d]
103
+ )
104
+
105
+ return (
106
+ chunk_idx + query_chunk_size, # unused ignore it
107
+ _query_chunk_attention(
108
+ query=query_chunk, key=key, value=value, precision=precision, key_chunk_size=key_chunk_size
109
+ ),
110
+ )
111
+
112
+ _, res = jax.lax.scan(
113
+ f=chunk_scanner,
114
+ init=0,
115
+ xs=None,
116
+ length=math.ceil(num_q / query_chunk_size), # start counter # stop counter
117
+ )
118
+
119
+ return jnp.concatenate(res, axis=-3) # fuse the chunked result back
120
+
121
+
122
+ class FlaxAttention(nn.Module):
123
+ r"""
124
+ A Flax multi-head attention module as described in: https://arxiv.org/abs/1706.03762
125
+
126
+ Parameters:
127
+ query_dim (:obj:`int`):
128
+ Input hidden states dimension
129
+ heads (:obj:`int`, *optional*, defaults to 8):
130
+ Number of heads
131
+ dim_head (:obj:`int`, *optional*, defaults to 64):
132
+ Hidden states dimension inside each head
133
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
134
+ Dropout rate
135
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
136
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
137
+ split_head_dim (`bool`, *optional*, defaults to `False`):
138
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
139
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
140
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
141
+ Parameters `dtype`
142
+
143
+ """
144
+
145
+ query_dim: int
146
+ heads: int = 8
147
+ dim_head: int = 64
148
+ dropout: float = 0.0
149
+ use_memory_efficient_attention: bool = False
150
+ split_head_dim: bool = False
151
+ dtype: jnp.dtype = jnp.float32
152
+
153
+ def setup(self):
154
+ inner_dim = self.dim_head * self.heads
155
+ self.scale = self.dim_head**-0.5
156
+
157
+ # Weights were exported with old names {to_q, to_k, to_v, to_out}
158
+ self.query = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_q")
159
+ self.key = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_k")
160
+ self.value = nn.Dense(inner_dim, use_bias=False, dtype=self.dtype, name="to_v")
161
+
162
+ self.proj_attn = nn.Dense(self.query_dim, dtype=self.dtype, name="to_out_0")
163
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
164
+
165
+ def reshape_heads_to_batch_dim(self, tensor):
166
+ batch_size, seq_len, dim = tensor.shape
167
+ head_size = self.heads
168
+ tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
169
+ tensor = jnp.transpose(tensor, (0, 2, 1, 3))
170
+ tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
171
+ return tensor
172
+
173
+ def reshape_batch_dim_to_heads(self, tensor):
174
+ batch_size, seq_len, dim = tensor.shape
175
+ head_size = self.heads
176
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
177
+ tensor = jnp.transpose(tensor, (0, 2, 1, 3))
178
+ tensor = tensor.reshape(batch_size // head_size, seq_len, dim * head_size)
179
+ return tensor
180
+
181
+ def __call__(self, hidden_states, context=None, deterministic=True):
182
+ context = hidden_states if context is None else context
183
+
184
+ query_proj = self.query(hidden_states)
185
+ key_proj = self.key(context)
186
+ value_proj = self.value(context)
187
+
188
+ if self.split_head_dim:
189
+ b = hidden_states.shape[0]
190
+ query_states = jnp.reshape(query_proj, (b, -1, self.heads, self.dim_head))
191
+ key_states = jnp.reshape(key_proj, (b, -1, self.heads, self.dim_head))
192
+ value_states = jnp.reshape(value_proj, (b, -1, self.heads, self.dim_head))
193
+ else:
194
+ query_states = self.reshape_heads_to_batch_dim(query_proj)
195
+ key_states = self.reshape_heads_to_batch_dim(key_proj)
196
+ value_states = self.reshape_heads_to_batch_dim(value_proj)
197
+
198
+ if self.use_memory_efficient_attention:
199
+ query_states = query_states.transpose(1, 0, 2)
200
+ key_states = key_states.transpose(1, 0, 2)
201
+ value_states = value_states.transpose(1, 0, 2)
202
+
203
+ # this if statement create a chunk size for each layer of the unet
204
+ # the chunk size is equal to the query_length dimension of the deepest layer of the unet
205
+
206
+ flatten_latent_dim = query_states.shape[-3]
207
+ if flatten_latent_dim % 64 == 0:
208
+ query_chunk_size = int(flatten_latent_dim / 64)
209
+ elif flatten_latent_dim % 16 == 0:
210
+ query_chunk_size = int(flatten_latent_dim / 16)
211
+ elif flatten_latent_dim % 4 == 0:
212
+ query_chunk_size = int(flatten_latent_dim / 4)
213
+ else:
214
+ query_chunk_size = int(flatten_latent_dim)
215
+
216
+ hidden_states = jax_memory_efficient_attention(
217
+ query_states, key_states, value_states, query_chunk_size=query_chunk_size, key_chunk_size=4096 * 4
218
+ )
219
+
220
+ hidden_states = hidden_states.transpose(1, 0, 2)
221
+ else:
222
+ # compute attentions
223
+ if self.split_head_dim:
224
+ attention_scores = jnp.einsum("b t n h, b f n h -> b n f t", key_states, query_states)
225
+ else:
226
+ attention_scores = jnp.einsum("b i d, b j d->b i j", query_states, key_states)
227
+
228
+ attention_scores = attention_scores * self.scale
229
+ attention_probs = nn.softmax(attention_scores, axis=-1 if self.split_head_dim else 2)
230
+
231
+ # attend to values
232
+ if self.split_head_dim:
233
+ hidden_states = jnp.einsum("b n f t, b t n h -> b f n h", attention_probs, value_states)
234
+ b = hidden_states.shape[0]
235
+ hidden_states = jnp.reshape(hidden_states, (b, -1, self.heads * self.dim_head))
236
+ else:
237
+ hidden_states = jnp.einsum("b i j, b j d -> b i d", attention_probs, value_states)
238
+ hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
239
+
240
+ hidden_states = self.proj_attn(hidden_states)
241
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
242
+
243
+
244
+ class FlaxBasicTransformerBlock(nn.Module):
245
+ r"""
246
+ A Flax transformer block layer with `GLU` (Gated Linear Unit) activation function as described in:
247
+ https://arxiv.org/abs/1706.03762
248
+
249
+
250
+ Parameters:
251
+ dim (:obj:`int`):
252
+ Inner hidden states dimension
253
+ n_heads (:obj:`int`):
254
+ Number of heads
255
+ d_head (:obj:`int`):
256
+ Hidden states dimension inside each head
257
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
258
+ Dropout rate
259
+ only_cross_attention (`bool`, defaults to `False`):
260
+ Whether to only apply cross attention.
261
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
262
+ Parameters `dtype`
263
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
264
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
265
+ split_head_dim (`bool`, *optional*, defaults to `False`):
266
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
267
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
268
+ """
269
+
270
+ dim: int
271
+ n_heads: int
272
+ d_head: int
273
+ dropout: float = 0.0
274
+ only_cross_attention: bool = False
275
+ dtype: jnp.dtype = jnp.float32
276
+ use_memory_efficient_attention: bool = False
277
+ split_head_dim: bool = False
278
+
279
+ def setup(self):
280
+ # self attention (or cross_attention if only_cross_attention is True)
281
+ self.attn1 = FlaxAttention(
282
+ self.dim,
283
+ self.n_heads,
284
+ self.d_head,
285
+ self.dropout,
286
+ self.use_memory_efficient_attention,
287
+ self.split_head_dim,
288
+ dtype=self.dtype,
289
+ )
290
+ # cross attention
291
+ self.attn2 = FlaxAttention(
292
+ self.dim,
293
+ self.n_heads,
294
+ self.d_head,
295
+ self.dropout,
296
+ self.use_memory_efficient_attention,
297
+ self.split_head_dim,
298
+ dtype=self.dtype,
299
+ )
300
+ self.ff = FlaxFeedForward(dim=self.dim, dropout=self.dropout, dtype=self.dtype)
301
+ self.norm1 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
302
+ self.norm2 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
303
+ self.norm3 = nn.LayerNorm(epsilon=1e-5, dtype=self.dtype)
304
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
305
+
306
+ def __call__(self, hidden_states, context, deterministic=True):
307
+ # self attention
308
+ residual = hidden_states
309
+ if self.only_cross_attention:
310
+ hidden_states = self.attn1(self.norm1(hidden_states), context, deterministic=deterministic)
311
+ else:
312
+ hidden_states = self.attn1(self.norm1(hidden_states), deterministic=deterministic)
313
+ hidden_states = hidden_states + residual
314
+
315
+ # cross attention
316
+ residual = hidden_states
317
+ hidden_states = self.attn2(self.norm2(hidden_states), context, deterministic=deterministic)
318
+ hidden_states = hidden_states + residual
319
+
320
+ # feed forward
321
+ residual = hidden_states
322
+ hidden_states = self.ff(self.norm3(hidden_states), deterministic=deterministic)
323
+ hidden_states = hidden_states + residual
324
+
325
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
326
+
327
+
328
+ class FlaxTransformer2DModel(nn.Module):
329
+ r"""
330
+ A Spatial Transformer layer with Gated Linear Unit (GLU) activation function as described in:
331
+ https://arxiv.org/pdf/1506.02025.pdf
332
+
333
+
334
+ Parameters:
335
+ in_channels (:obj:`int`):
336
+ Input number of channels
337
+ n_heads (:obj:`int`):
338
+ Number of heads
339
+ d_head (:obj:`int`):
340
+ Hidden states dimension inside each head
341
+ depth (:obj:`int`, *optional*, defaults to 1):
342
+ Number of transformers block
343
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
344
+ Dropout rate
345
+ use_linear_projection (`bool`, defaults to `False`): tbd
346
+ only_cross_attention (`bool`, defaults to `False`): tbd
347
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
348
+ Parameters `dtype`
349
+ use_memory_efficient_attention (`bool`, *optional*, defaults to `False`):
350
+ enable memory efficient attention https://arxiv.org/abs/2112.05682
351
+ split_head_dim (`bool`, *optional*, defaults to `False`):
352
+ Whether to split the head dimension into a new axis for the self-attention computation. In most cases,
353
+ enabling this flag should speed up the computation for Stable Diffusion 2.x and Stable Diffusion XL.
354
+ """
355
+
356
+ in_channels: int
357
+ n_heads: int
358
+ d_head: int
359
+ depth: int = 1
360
+ dropout: float = 0.0
361
+ use_linear_projection: bool = False
362
+ only_cross_attention: bool = False
363
+ dtype: jnp.dtype = jnp.float32
364
+ use_memory_efficient_attention: bool = False
365
+ split_head_dim: bool = False
366
+
367
+ def setup(self):
368
+ self.norm = nn.GroupNorm(num_groups=32, epsilon=1e-5)
369
+
370
+ inner_dim = self.n_heads * self.d_head
371
+ if self.use_linear_projection:
372
+ self.proj_in = nn.Dense(inner_dim, dtype=self.dtype)
373
+ else:
374
+ self.proj_in = nn.Conv(
375
+ inner_dim,
376
+ kernel_size=(1, 1),
377
+ strides=(1, 1),
378
+ padding="VALID",
379
+ dtype=self.dtype,
380
+ )
381
+
382
+ self.transformer_blocks = [
383
+ FlaxBasicTransformerBlock(
384
+ inner_dim,
385
+ self.n_heads,
386
+ self.d_head,
387
+ dropout=self.dropout,
388
+ only_cross_attention=self.only_cross_attention,
389
+ dtype=self.dtype,
390
+ use_memory_efficient_attention=self.use_memory_efficient_attention,
391
+ split_head_dim=self.split_head_dim,
392
+ )
393
+ for _ in range(self.depth)
394
+ ]
395
+
396
+ if self.use_linear_projection:
397
+ self.proj_out = nn.Dense(inner_dim, dtype=self.dtype)
398
+ else:
399
+ self.proj_out = nn.Conv(
400
+ inner_dim,
401
+ kernel_size=(1, 1),
402
+ strides=(1, 1),
403
+ padding="VALID",
404
+ dtype=self.dtype,
405
+ )
406
+
407
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
408
+
409
+ def __call__(self, hidden_states, context, deterministic=True):
410
+ batch, height, width, channels = hidden_states.shape
411
+ residual = hidden_states
412
+ hidden_states = self.norm(hidden_states)
413
+ if self.use_linear_projection:
414
+ hidden_states = hidden_states.reshape(batch, height * width, channels)
415
+ hidden_states = self.proj_in(hidden_states)
416
+ else:
417
+ hidden_states = self.proj_in(hidden_states)
418
+ hidden_states = hidden_states.reshape(batch, height * width, channels)
419
+
420
+ for transformer_block in self.transformer_blocks:
421
+ hidden_states = transformer_block(hidden_states, context, deterministic=deterministic)
422
+
423
+ if self.use_linear_projection:
424
+ hidden_states = self.proj_out(hidden_states)
425
+ hidden_states = hidden_states.reshape(batch, height, width, channels)
426
+ else:
427
+ hidden_states = hidden_states.reshape(batch, height, width, channels)
428
+ hidden_states = self.proj_out(hidden_states)
429
+
430
+ hidden_states = hidden_states + residual
431
+ return self.dropout_layer(hidden_states, deterministic=deterministic)
432
+
433
+
434
+ class FlaxFeedForward(nn.Module):
435
+ r"""
436
+ Flax module that encapsulates two Linear layers separated by a non-linearity. It is the counterpart of PyTorch's
437
+ [`FeedForward`] class, with the following simplifications:
438
+ - The activation function is currently hardcoded to a gated linear unit from:
439
+ https://arxiv.org/abs/2002.05202
440
+ - `dim_out` is equal to `dim`.
441
+ - The number of hidden dimensions is hardcoded to `dim * 4` in [`FlaxGELU`].
442
+
443
+ Parameters:
444
+ dim (:obj:`int`):
445
+ Inner hidden states dimension
446
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
447
+ Dropout rate
448
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
449
+ Parameters `dtype`
450
+ """
451
+
452
+ dim: int
453
+ dropout: float = 0.0
454
+ dtype: jnp.dtype = jnp.float32
455
+
456
+ def setup(self):
457
+ # The second linear layer needs to be called
458
+ # net_2 for now to match the index of the Sequential layer
459
+ self.net_0 = FlaxGEGLU(self.dim, self.dropout, self.dtype)
460
+ self.net_2 = nn.Dense(self.dim, dtype=self.dtype)
461
+
462
+ def __call__(self, hidden_states, deterministic=True):
463
+ hidden_states = self.net_0(hidden_states, deterministic=deterministic)
464
+ hidden_states = self.net_2(hidden_states)
465
+ return hidden_states
466
+
467
+
468
+ class FlaxGEGLU(nn.Module):
469
+ r"""
470
+ Flax implementation of a Linear layer followed by the variant of the gated linear unit activation function from
471
+ https://arxiv.org/abs/2002.05202.
472
+
473
+ Parameters:
474
+ dim (:obj:`int`):
475
+ Input hidden states dimension
476
+ dropout (:obj:`float`, *optional*, defaults to 0.0):
477
+ Dropout rate
478
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
479
+ Parameters `dtype`
480
+ """
481
+
482
+ dim: int
483
+ dropout: float = 0.0
484
+ dtype: jnp.dtype = jnp.float32
485
+
486
+ def setup(self):
487
+ inner_dim = self.dim * 4
488
+ self.proj = nn.Dense(inner_dim * 2, dtype=self.dtype)
489
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
490
+
491
+ def __call__(self, hidden_states, deterministic=True):
492
+ hidden_states = self.proj(hidden_states)
493
+ hidden_linear, hidden_gelu = jnp.split(hidden_states, 2, axis=2)
494
+ return self.dropout_layer(hidden_linear * nn.gelu(hidden_gelu), deterministic=deterministic)
diffusers/models/attention_processor.py ADDED
@@ -0,0 +1,2305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 importlib import import_module
15
+ from typing import Callable, Optional, Union
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import einsum, nn
20
+
21
+ from ..utils import USE_PEFT_BACKEND, deprecate, logging
22
+ from ..utils.import_utils import is_xformers_available
23
+ from ..utils.torch_utils import maybe_allow_in_graph
24
+ from .lora import LoRACompatibleLinear, LoRALinearLayer
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ if is_xformers_available():
31
+ import xformers
32
+ import xformers.ops
33
+ else:
34
+ xformers = None
35
+
36
+
37
+ @maybe_allow_in_graph
38
+ class Attention(nn.Module):
39
+ r"""
40
+ A cross attention layer.
41
+
42
+ Parameters:
43
+ query_dim (`int`):
44
+ The number of channels in the query.
45
+ cross_attention_dim (`int`, *optional*):
46
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
47
+ heads (`int`, *optional*, defaults to 8):
48
+ The number of heads to use for multi-head attention.
49
+ dim_head (`int`, *optional*, defaults to 64):
50
+ The number of channels in each head.
51
+ dropout (`float`, *optional*, defaults to 0.0):
52
+ The dropout probability to use.
53
+ bias (`bool`, *optional*, defaults to False):
54
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
55
+ upcast_attention (`bool`, *optional*, defaults to False):
56
+ Set to `True` to upcast the attention computation to `float32`.
57
+ upcast_softmax (`bool`, *optional*, defaults to False):
58
+ Set to `True` to upcast the softmax computation to `float32`.
59
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
60
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
61
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
62
+ The number of groups to use for the group norm in the cross attention.
63
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
64
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
65
+ norm_num_groups (`int`, *optional*, defaults to `None`):
66
+ The number of groups to use for the group norm in the attention.
67
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
68
+ The number of channels to use for the spatial normalization.
69
+ out_bias (`bool`, *optional*, defaults to `True`):
70
+ Set to `True` to use a bias in the output linear layer.
71
+ scale_qk (`bool`, *optional*, defaults to `True`):
72
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
73
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
74
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
75
+ `added_kv_proj_dim` is not `None`.
76
+ eps (`float`, *optional*, defaults to 1e-5):
77
+ An additional value added to the denominator in group normalization that is used for numerical stability.
78
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
79
+ A factor to rescale the output by dividing it with this value.
80
+ residual_connection (`bool`, *optional*, defaults to `False`):
81
+ Set to `True` to add the residual connection to the output.
82
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
83
+ Set to `True` if the attention block is loaded from a deprecated state dict.
84
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
85
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
86
+ `AttnProcessor` otherwise.
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ query_dim: int,
92
+ cross_attention_dim: Optional[int] = None,
93
+ heads: int = 8,
94
+ dim_head: int = 64,
95
+ dropout: float = 0.0,
96
+ bias: bool = False,
97
+ upcast_attention: bool = False,
98
+ upcast_softmax: bool = False,
99
+ cross_attention_norm: Optional[str] = None,
100
+ cross_attention_norm_num_groups: int = 32,
101
+ added_kv_proj_dim: Optional[int] = None,
102
+ norm_num_groups: Optional[int] = None,
103
+ spatial_norm_dim: Optional[int] = None,
104
+ out_bias: bool = True,
105
+ scale_qk: bool = True,
106
+ only_cross_attention: bool = False,
107
+ eps: float = 1e-5,
108
+ rescale_output_factor: float = 1.0,
109
+ residual_connection: bool = False,
110
+ _from_deprecated_attn_block: bool = False,
111
+ processor: Optional["AttnProcessor"] = None,
112
+ ):
113
+ super().__init__()
114
+ self.inner_dim = dim_head * heads
115
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
116
+ self.upcast_attention = upcast_attention
117
+ self.upcast_softmax = upcast_softmax
118
+ self.rescale_output_factor = rescale_output_factor
119
+ self.residual_connection = residual_connection
120
+ self.dropout = dropout
121
+
122
+ # we make use of this private variable to know whether this class is loaded
123
+ # with an deprecated state dict so that we can convert it on the fly
124
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
125
+
126
+ self.scale_qk = scale_qk
127
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
128
+
129
+ self.heads = heads
130
+ # for slice_size > 0 the attention score computation
131
+ # is split across the batch axis to save memory
132
+ # You can set slice_size with `set_attention_slice`
133
+ self.sliceable_head_dim = heads
134
+
135
+ self.added_kv_proj_dim = added_kv_proj_dim
136
+ self.only_cross_attention = only_cross_attention
137
+
138
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
139
+ raise ValueError(
140
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
141
+ )
142
+
143
+ if norm_num_groups is not None:
144
+ self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True)
145
+ else:
146
+ self.group_norm = None
147
+
148
+ if spatial_norm_dim is not None:
149
+ self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim)
150
+ else:
151
+ self.spatial_norm = None
152
+
153
+ if cross_attention_norm is None:
154
+ self.norm_cross = None
155
+ elif cross_attention_norm == "layer_norm":
156
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
157
+ elif cross_attention_norm == "group_norm":
158
+ if self.added_kv_proj_dim is not None:
159
+ # The given `encoder_hidden_states` are initially of shape
160
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
161
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
162
+ # before the projection, so we need to use `added_kv_proj_dim` as
163
+ # the number of channels for the group norm.
164
+ norm_cross_num_channels = added_kv_proj_dim
165
+ else:
166
+ norm_cross_num_channels = self.cross_attention_dim
167
+
168
+ self.norm_cross = nn.GroupNorm(
169
+ num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True
170
+ )
171
+ else:
172
+ raise ValueError(
173
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
174
+ )
175
+
176
+ if USE_PEFT_BACKEND:
177
+ linear_cls = nn.Linear
178
+ else:
179
+ linear_cls = LoRACompatibleLinear
180
+
181
+ self.to_q = linear_cls(query_dim, self.inner_dim, bias=bias)
182
+
183
+ if not self.only_cross_attention:
184
+ # only relevant for the `AddedKVProcessor` classes
185
+ self.to_k = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
186
+ self.to_v = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
187
+ else:
188
+ self.to_k = None
189
+ self.to_v = None
190
+
191
+ if self.added_kv_proj_dim is not None:
192
+ self.add_k_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
193
+ self.add_v_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
194
+
195
+ self.to_out = nn.ModuleList([])
196
+ self.to_out.append(linear_cls(self.inner_dim, query_dim, bias=out_bias))
197
+ self.to_out.append(nn.Dropout(dropout))
198
+
199
+ # set attention processor
200
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
201
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
202
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
203
+ if processor is None:
204
+ processor = (
205
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
206
+ )
207
+ self.set_processor(processor)
208
+
209
+ def set_use_memory_efficient_attention_xformers(
210
+ self, use_memory_efficient_attention_xformers: bool, attention_op: Optional[Callable] = None
211
+ ) -> None:
212
+ r"""
213
+ Set whether to use memory efficient attention from `xformers` or not.
214
+
215
+ Args:
216
+ use_memory_efficient_attention_xformers (`bool`):
217
+ Whether to use memory efficient attention from `xformers` or not.
218
+ attention_op (`Callable`, *optional*):
219
+ The attention operation to use. Defaults to `None` which uses the default attention operation from
220
+ `xformers`.
221
+ """
222
+ is_lora = hasattr(self, "processor") and isinstance(
223
+ self.processor,
224
+ LORA_ATTENTION_PROCESSORS,
225
+ )
226
+ is_custom_diffusion = hasattr(self, "processor") and isinstance(
227
+ self.processor,
228
+ (CustomDiffusionAttnProcessor, CustomDiffusionXFormersAttnProcessor, CustomDiffusionAttnProcessor2_0),
229
+ )
230
+ is_added_kv_processor = hasattr(self, "processor") and isinstance(
231
+ self.processor,
232
+ (
233
+ AttnAddedKVProcessor,
234
+ AttnAddedKVProcessor2_0,
235
+ SlicedAttnAddedKVProcessor,
236
+ XFormersAttnAddedKVProcessor,
237
+ LoRAAttnAddedKVProcessor,
238
+ ),
239
+ )
240
+
241
+ if use_memory_efficient_attention_xformers:
242
+ if is_added_kv_processor and (is_lora or is_custom_diffusion):
243
+ raise NotImplementedError(
244
+ f"Memory efficient attention is currently not supported for LoRA or custom diffusion for attention processor type {self.processor}"
245
+ )
246
+ if not is_xformers_available():
247
+ raise ModuleNotFoundError(
248
+ (
249
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
250
+ " xformers"
251
+ ),
252
+ name="xformers",
253
+ )
254
+ elif not torch.cuda.is_available():
255
+ raise ValueError(
256
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
257
+ " only available for GPU "
258
+ )
259
+ else:
260
+ try:
261
+ # Make sure we can run the memory efficient attention
262
+ _ = xformers.ops.memory_efficient_attention(
263
+ torch.randn((1, 2, 40), device="cuda"),
264
+ torch.randn((1, 2, 40), device="cuda"),
265
+ torch.randn((1, 2, 40), device="cuda"),
266
+ )
267
+ except Exception as e:
268
+ raise e
269
+
270
+ if is_lora:
271
+ # TODO (sayakpaul): should we throw a warning if someone wants to use the xformers
272
+ # variant when using PT 2.0 now that we have LoRAAttnProcessor2_0?
273
+ processor = LoRAXFormersAttnProcessor(
274
+ hidden_size=self.processor.hidden_size,
275
+ cross_attention_dim=self.processor.cross_attention_dim,
276
+ rank=self.processor.rank,
277
+ attention_op=attention_op,
278
+ )
279
+ processor.load_state_dict(self.processor.state_dict())
280
+ processor.to(self.processor.to_q_lora.up.weight.device)
281
+ elif is_custom_diffusion:
282
+ processor = CustomDiffusionXFormersAttnProcessor(
283
+ train_kv=self.processor.train_kv,
284
+ train_q_out=self.processor.train_q_out,
285
+ hidden_size=self.processor.hidden_size,
286
+ cross_attention_dim=self.processor.cross_attention_dim,
287
+ attention_op=attention_op,
288
+ )
289
+ processor.load_state_dict(self.processor.state_dict())
290
+ if hasattr(self.processor, "to_k_custom_diffusion"):
291
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
292
+ elif is_added_kv_processor:
293
+ # TODO(Patrick, Suraj, William) - currently xformers doesn't work for UnCLIP
294
+ # which uses this type of cross attention ONLY because the attention mask of format
295
+ # [0, ..., -10.000, ..., 0, ...,] is not supported
296
+ # throw warning
297
+ logger.info(
298
+ "Memory efficient attention with `xformers` might currently not work correctly if an attention mask is required for the attention operation."
299
+ )
300
+ processor = XFormersAttnAddedKVProcessor(attention_op=attention_op)
301
+ else:
302
+ processor = XFormersAttnProcessor(attention_op=attention_op)
303
+ else:
304
+ if is_lora:
305
+ attn_processor_class = (
306
+ LoRAAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else LoRAAttnProcessor
307
+ )
308
+ processor = attn_processor_class(
309
+ hidden_size=self.processor.hidden_size,
310
+ cross_attention_dim=self.processor.cross_attention_dim,
311
+ rank=self.processor.rank,
312
+ )
313
+ processor.load_state_dict(self.processor.state_dict())
314
+ processor.to(self.processor.to_q_lora.up.weight.device)
315
+ elif is_custom_diffusion:
316
+ attn_processor_class = (
317
+ CustomDiffusionAttnProcessor2_0
318
+ if hasattr(F, "scaled_dot_product_attention")
319
+ else CustomDiffusionAttnProcessor
320
+ )
321
+ processor = attn_processor_class(
322
+ train_kv=self.processor.train_kv,
323
+ train_q_out=self.processor.train_q_out,
324
+ hidden_size=self.processor.hidden_size,
325
+ cross_attention_dim=self.processor.cross_attention_dim,
326
+ )
327
+ processor.load_state_dict(self.processor.state_dict())
328
+ if hasattr(self.processor, "to_k_custom_diffusion"):
329
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
330
+ else:
331
+ # set attention processor
332
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
333
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
334
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
335
+ processor = (
336
+ AttnProcessor2_0()
337
+ if hasattr(F, "scaled_dot_product_attention") and self.scale_qk
338
+ else AttnProcessor()
339
+ )
340
+
341
+ self.set_processor(processor)
342
+
343
+ def set_attention_slice(self, slice_size: int) -> None:
344
+ r"""
345
+ Set the slice size for attention computation.
346
+
347
+ Args:
348
+ slice_size (`int`):
349
+ The slice size for attention computation.
350
+ """
351
+ if slice_size is not None and slice_size > self.sliceable_head_dim:
352
+ raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
353
+
354
+ if slice_size is not None and self.added_kv_proj_dim is not None:
355
+ processor = SlicedAttnAddedKVProcessor(slice_size)
356
+ elif slice_size is not None:
357
+ processor = SlicedAttnProcessor(slice_size)
358
+ elif self.added_kv_proj_dim is not None:
359
+ processor = AttnAddedKVProcessor()
360
+ else:
361
+ # set attention processor
362
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
363
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
364
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
365
+ processor = (
366
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
367
+ )
368
+
369
+ self.set_processor(processor)
370
+
371
+ def set_processor(self, processor: "AttnProcessor", _remove_lora: bool = False) -> None:
372
+ r"""
373
+ Set the attention processor to use.
374
+
375
+ Args:
376
+ processor (`AttnProcessor`):
377
+ The attention processor to use.
378
+ _remove_lora (`bool`, *optional*, defaults to `False`):
379
+ Set to `True` to remove LoRA layers from the model.
380
+ """
381
+ if not USE_PEFT_BACKEND and hasattr(self, "processor") and _remove_lora and self.to_q.lora_layer is not None:
382
+ deprecate(
383
+ "set_processor to offload LoRA",
384
+ "0.26.0",
385
+ "In detail, removing LoRA layers via calling `set_default_attn_processor` is deprecated. Please make sure to call `pipe.unload_lora_weights()` instead.",
386
+ )
387
+ # TODO(Patrick, Sayak) - this can be deprecated once PEFT LoRA integration is complete
388
+ # We need to remove all LoRA layers
389
+ # Don't forget to remove ALL `_remove_lora` from the codebase
390
+ for module in self.modules():
391
+ if hasattr(module, "set_lora_layer"):
392
+ module.set_lora_layer(None)
393
+
394
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
395
+ # pop `processor` from `self._modules`
396
+ if (
397
+ hasattr(self, "processor")
398
+ and isinstance(self.processor, torch.nn.Module)
399
+ and not isinstance(processor, torch.nn.Module)
400
+ ):
401
+ logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}")
402
+ self._modules.pop("processor")
403
+
404
+ self.processor = processor
405
+
406
+ def get_processor(self, return_deprecated_lora: bool = False) -> "AttentionProcessor":
407
+ r"""
408
+ Get the attention processor in use.
409
+
410
+ Args:
411
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
412
+ Set to `True` to return the deprecated LoRA attention processor.
413
+
414
+ Returns:
415
+ "AttentionProcessor": The attention processor in use.
416
+ """
417
+ if not return_deprecated_lora:
418
+ return self.processor
419
+
420
+ # TODO(Sayak, Patrick). The rest of the function is needed to ensure backwards compatible
421
+ # serialization format for LoRA Attention Processors. It should be deleted once the integration
422
+ # with PEFT is completed.
423
+ is_lora_activated = {
424
+ name: module.lora_layer is not None
425
+ for name, module in self.named_modules()
426
+ if hasattr(module, "lora_layer")
427
+ }
428
+
429
+ # 1. if no layer has a LoRA activated we can return the processor as usual
430
+ if not any(is_lora_activated.values()):
431
+ return self.processor
432
+
433
+ # If doesn't apply LoRA do `add_k_proj` or `add_v_proj`
434
+ is_lora_activated.pop("add_k_proj", None)
435
+ is_lora_activated.pop("add_v_proj", None)
436
+ # 2. else it is not posssible that only some layers have LoRA activated
437
+ if not all(is_lora_activated.values()):
438
+ raise ValueError(
439
+ f"Make sure that either all layers or no layers have LoRA activated, but have {is_lora_activated}"
440
+ )
441
+
442
+ # 3. And we need to merge the current LoRA layers into the corresponding LoRA attention processor
443
+ non_lora_processor_cls_name = self.processor.__class__.__name__
444
+ lora_processor_cls = getattr(import_module(__name__), "LoRA" + non_lora_processor_cls_name)
445
+
446
+ hidden_size = self.inner_dim
447
+
448
+ # now create a LoRA attention processor from the LoRA layers
449
+ if lora_processor_cls in [LoRAAttnProcessor, LoRAAttnProcessor2_0, LoRAXFormersAttnProcessor]:
450
+ kwargs = {
451
+ "cross_attention_dim": self.cross_attention_dim,
452
+ "rank": self.to_q.lora_layer.rank,
453
+ "network_alpha": self.to_q.lora_layer.network_alpha,
454
+ "q_rank": self.to_q.lora_layer.rank,
455
+ "q_hidden_size": self.to_q.lora_layer.out_features,
456
+ "k_rank": self.to_k.lora_layer.rank,
457
+ "k_hidden_size": self.to_k.lora_layer.out_features,
458
+ "v_rank": self.to_v.lora_layer.rank,
459
+ "v_hidden_size": self.to_v.lora_layer.out_features,
460
+ "out_rank": self.to_out[0].lora_layer.rank,
461
+ "out_hidden_size": self.to_out[0].lora_layer.out_features,
462
+ }
463
+
464
+ if hasattr(self.processor, "attention_op"):
465
+ kwargs["attention_op"] = self.processor.attention_op
466
+
467
+ lora_processor = lora_processor_cls(hidden_size, **kwargs)
468
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
469
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
470
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
471
+ lora_processor.to_out_lora.load_state_dict(self.to_out[0].lora_layer.state_dict())
472
+ elif lora_processor_cls == LoRAAttnAddedKVProcessor:
473
+ lora_processor = lora_processor_cls(
474
+ hidden_size,
475
+ cross_attention_dim=self.add_k_proj.weight.shape[0],
476
+ rank=self.to_q.lora_layer.rank,
477
+ network_alpha=self.to_q.lora_layer.network_alpha,
478
+ )
479
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
480
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
481
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
482
+ lora_processor.to_out_lora.load_state_dict(self.to_out[0].lora_layer.state_dict())
483
+
484
+ # only save if used
485
+ if self.add_k_proj.lora_layer is not None:
486
+ lora_processor.add_k_proj_lora.load_state_dict(self.add_k_proj.lora_layer.state_dict())
487
+ lora_processor.add_v_proj_lora.load_state_dict(self.add_v_proj.lora_layer.state_dict())
488
+ else:
489
+ lora_processor.add_k_proj_lora = None
490
+ lora_processor.add_v_proj_lora = None
491
+ else:
492
+ raise ValueError(f"{lora_processor_cls} does not exist.")
493
+
494
+ return lora_processor
495
+
496
+ def forward(
497
+ self,
498
+ hidden_states: torch.FloatTensor,
499
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
500
+ attention_mask: Optional[torch.FloatTensor] = None,
501
+ **cross_attention_kwargs,
502
+ ) -> torch.Tensor:
503
+ r"""
504
+ The forward method of the `Attention` class.
505
+
506
+ Args:
507
+ hidden_states (`torch.Tensor`):
508
+ The hidden states of the query.
509
+ encoder_hidden_states (`torch.Tensor`, *optional*):
510
+ The hidden states of the encoder.
511
+ attention_mask (`torch.Tensor`, *optional*):
512
+ The attention mask to use. If `None`, no mask is applied.
513
+ **cross_attention_kwargs:
514
+ Additional keyword arguments to pass along to the cross attention.
515
+
516
+ Returns:
517
+ `torch.Tensor`: The output of the attention layer.
518
+ """
519
+ # The `Attention` class can call different attention processors / attention functions
520
+ # here we simply pass along all tensors to the selected processor class
521
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
522
+ return self.processor(
523
+ self,
524
+ hidden_states,
525
+ encoder_hidden_states=encoder_hidden_states,
526
+ attention_mask=attention_mask,
527
+ **cross_attention_kwargs,
528
+ )
529
+
530
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
531
+ r"""
532
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
533
+ is the number of heads initialized while constructing the `Attention` class.
534
+
535
+ Args:
536
+ tensor (`torch.Tensor`): The tensor to reshape.
537
+
538
+ Returns:
539
+ `torch.Tensor`: The reshaped tensor.
540
+ """
541
+ head_size = self.heads
542
+ batch_size, seq_len, dim = tensor.shape
543
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
544
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
545
+ return tensor
546
+
547
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
548
+ r"""
549
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
550
+ the number of heads initialized while constructing the `Attention` class.
551
+
552
+ Args:
553
+ tensor (`torch.Tensor`): The tensor to reshape.
554
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
555
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
556
+
557
+ Returns:
558
+ `torch.Tensor`: The reshaped tensor.
559
+ """
560
+ head_size = self.heads
561
+ batch_size, seq_len, dim = tensor.shape
562
+ tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
563
+ tensor = tensor.permute(0, 2, 1, 3)
564
+
565
+ if out_dim == 3:
566
+ tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
567
+
568
+ return tensor
569
+
570
+ def get_attention_scores(
571
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: torch.Tensor = None
572
+ ) -> torch.Tensor:
573
+ r"""
574
+ Compute the attention scores.
575
+
576
+ Args:
577
+ query (`torch.Tensor`): The query tensor.
578
+ key (`torch.Tensor`): The key tensor.
579
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
580
+
581
+ Returns:
582
+ `torch.Tensor`: The attention probabilities/scores.
583
+ """
584
+ dtype = query.dtype
585
+ if self.upcast_attention:
586
+ query = query.float()
587
+ key = key.float()
588
+
589
+ if attention_mask is None:
590
+ baddbmm_input = torch.empty(
591
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
592
+ )
593
+ beta = 0
594
+ else:
595
+ baddbmm_input = attention_mask
596
+ beta = 1
597
+
598
+ attention_scores = torch.baddbmm(
599
+ baddbmm_input,
600
+ query,
601
+ key.transpose(-1, -2),
602
+ beta=beta,
603
+ alpha=self.scale,
604
+ )
605
+ del baddbmm_input
606
+
607
+ if self.upcast_softmax:
608
+ attention_scores = attention_scores.float()
609
+
610
+ attention_probs = attention_scores.softmax(dim=-1)
611
+ del attention_scores
612
+
613
+ attention_probs = attention_probs.to(dtype)
614
+
615
+ return attention_probs
616
+
617
+ def prepare_attention_mask(
618
+ self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
619
+ ) -> torch.Tensor:
620
+ r"""
621
+ Prepare the attention mask for the attention computation.
622
+
623
+ Args:
624
+ attention_mask (`torch.Tensor`):
625
+ The attention mask to prepare.
626
+ target_length (`int`):
627
+ The target length of the attention mask. This is the length of the attention mask after padding.
628
+ batch_size (`int`):
629
+ The batch size, which is used to repeat the attention mask.
630
+ out_dim (`int`, *optional*, defaults to `3`):
631
+ The output dimension of the attention mask. Can be either `3` or `4`.
632
+
633
+ Returns:
634
+ `torch.Tensor`: The prepared attention mask.
635
+ """
636
+ head_size = self.heads
637
+ if attention_mask is None:
638
+ return attention_mask
639
+
640
+ current_length: int = attention_mask.shape[-1]
641
+ if current_length != target_length:
642
+ if attention_mask.device.type == "mps":
643
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
644
+ # Instead, we can manually construct the padding tensor.
645
+ padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
646
+ padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
647
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
648
+ else:
649
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
650
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
651
+ # remaining_length: int = target_length - current_length
652
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
653
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
654
+
655
+ if out_dim == 3:
656
+ if attention_mask.shape[0] < batch_size * head_size:
657
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
658
+ elif out_dim == 4:
659
+ attention_mask = attention_mask.unsqueeze(1)
660
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
661
+
662
+ return attention_mask
663
+
664
+ def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
665
+ r"""
666
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
667
+ `Attention` class.
668
+
669
+ Args:
670
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
671
+
672
+ Returns:
673
+ `torch.Tensor`: The normalized encoder hidden states.
674
+ """
675
+ assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
676
+
677
+ if isinstance(self.norm_cross, nn.LayerNorm):
678
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
679
+ elif isinstance(self.norm_cross, nn.GroupNorm):
680
+ # Group norm norms along the channels dimension and expects
681
+ # input to be in the shape of (N, C, *). In this case, we want
682
+ # to norm along the hidden dimension, so we need to move
683
+ # (batch_size, sequence_length, hidden_size) ->
684
+ # (batch_size, hidden_size, sequence_length)
685
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
686
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
687
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
688
+ else:
689
+ assert False
690
+
691
+ return encoder_hidden_states
692
+
693
+
694
+ class AttnProcessor:
695
+ r"""
696
+ Default processor for performing attention-related computations.
697
+ """
698
+
699
+ def __call__(
700
+ self,
701
+ attn: Attention,
702
+ hidden_states: torch.FloatTensor,
703
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
704
+ attention_mask: Optional[torch.FloatTensor] = None,
705
+ temb: Optional[torch.FloatTensor] = None,
706
+ scale: float = 1.0,
707
+ ) -> torch.Tensor:
708
+ residual = hidden_states
709
+
710
+ args = () if USE_PEFT_BACKEND else (scale,)
711
+
712
+ if attn.spatial_norm is not None:
713
+ hidden_states = attn.spatial_norm(hidden_states, temb)
714
+
715
+ input_ndim = hidden_states.ndim
716
+
717
+ if input_ndim == 4:
718
+ batch_size, channel, height, width = hidden_states.shape
719
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
720
+
721
+ batch_size, sequence_length, _ = (
722
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
723
+ )
724
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
725
+
726
+ if attn.group_norm is not None:
727
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
728
+
729
+ query = attn.to_q(hidden_states, *args)
730
+
731
+ if encoder_hidden_states is None:
732
+ encoder_hidden_states = hidden_states
733
+ elif attn.norm_cross:
734
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
735
+
736
+ key = attn.to_k(encoder_hidden_states, *args)
737
+ value = attn.to_v(encoder_hidden_states, *args)
738
+
739
+ query = attn.head_to_batch_dim(query)
740
+ key = attn.head_to_batch_dim(key)
741
+ value = attn.head_to_batch_dim(value)
742
+
743
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
744
+ hidden_states = torch.bmm(attention_probs, value)
745
+ hidden_states = attn.batch_to_head_dim(hidden_states)
746
+
747
+ # linear proj
748
+ hidden_states = attn.to_out[0](hidden_states, *args)
749
+ # dropout
750
+ hidden_states = attn.to_out[1](hidden_states)
751
+
752
+ if input_ndim == 4:
753
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
754
+
755
+ if attn.residual_connection:
756
+ hidden_states = hidden_states + residual
757
+
758
+ hidden_states = hidden_states / attn.rescale_output_factor
759
+
760
+ return hidden_states
761
+
762
+
763
+ class CustomDiffusionAttnProcessor(nn.Module):
764
+ r"""
765
+ Processor for implementing attention for the Custom Diffusion method.
766
+
767
+ Args:
768
+ train_kv (`bool`, defaults to `True`):
769
+ Whether to newly train the key and value matrices corresponding to the text features.
770
+ train_q_out (`bool`, defaults to `True`):
771
+ Whether to newly train query matrices corresponding to the latent image features.
772
+ hidden_size (`int`, *optional*, defaults to `None`):
773
+ The hidden size of the attention layer.
774
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
775
+ The number of channels in the `encoder_hidden_states`.
776
+ out_bias (`bool`, defaults to `True`):
777
+ Whether to include the bias parameter in `train_q_out`.
778
+ dropout (`float`, *optional*, defaults to 0.0):
779
+ The dropout probability to use.
780
+ """
781
+
782
+ def __init__(
783
+ self,
784
+ train_kv: bool = True,
785
+ train_q_out: bool = True,
786
+ hidden_size: Optional[int] = None,
787
+ cross_attention_dim: Optional[int] = None,
788
+ out_bias: bool = True,
789
+ dropout: float = 0.0,
790
+ ):
791
+ super().__init__()
792
+ self.train_kv = train_kv
793
+ self.train_q_out = train_q_out
794
+
795
+ self.hidden_size = hidden_size
796
+ self.cross_attention_dim = cross_attention_dim
797
+
798
+ # `_custom_diffusion` id for easy serialization and loading.
799
+ if self.train_kv:
800
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
801
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
802
+ if self.train_q_out:
803
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
804
+ self.to_out_custom_diffusion = nn.ModuleList([])
805
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
806
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
807
+
808
+ def __call__(
809
+ self,
810
+ attn: Attention,
811
+ hidden_states: torch.FloatTensor,
812
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
813
+ attention_mask: Optional[torch.FloatTensor] = None,
814
+ ) -> torch.Tensor:
815
+ batch_size, sequence_length, _ = hidden_states.shape
816
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
817
+ if self.train_q_out:
818
+ query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
819
+ else:
820
+ query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
821
+
822
+ if encoder_hidden_states is None:
823
+ crossattn = False
824
+ encoder_hidden_states = hidden_states
825
+ else:
826
+ crossattn = True
827
+ if attn.norm_cross:
828
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
829
+
830
+ if self.train_kv:
831
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
832
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
833
+ key = key.to(attn.to_q.weight.dtype)
834
+ value = value.to(attn.to_q.weight.dtype)
835
+ else:
836
+ key = attn.to_k(encoder_hidden_states)
837
+ value = attn.to_v(encoder_hidden_states)
838
+
839
+ if crossattn:
840
+ detach = torch.ones_like(key)
841
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
842
+ key = detach * key + (1 - detach) * key.detach()
843
+ value = detach * value + (1 - detach) * value.detach()
844
+
845
+ query = attn.head_to_batch_dim(query)
846
+ key = attn.head_to_batch_dim(key)
847
+ value = attn.head_to_batch_dim(value)
848
+
849
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
850
+ hidden_states = torch.bmm(attention_probs, value)
851
+ hidden_states = attn.batch_to_head_dim(hidden_states)
852
+
853
+ if self.train_q_out:
854
+ # linear proj
855
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
856
+ # dropout
857
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
858
+ else:
859
+ # linear proj
860
+ hidden_states = attn.to_out[0](hidden_states)
861
+ # dropout
862
+ hidden_states = attn.to_out[1](hidden_states)
863
+
864
+ return hidden_states
865
+
866
+
867
+ class AttnAddedKVProcessor:
868
+ r"""
869
+ Processor for performing attention-related computations with extra learnable key and value matrices for the text
870
+ encoder.
871
+ """
872
+
873
+ def __call__(
874
+ self,
875
+ attn: Attention,
876
+ hidden_states: torch.FloatTensor,
877
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
878
+ attention_mask: Optional[torch.FloatTensor] = None,
879
+ scale: float = 1.0,
880
+ ) -> torch.Tensor:
881
+ residual = hidden_states
882
+
883
+ args = () if USE_PEFT_BACKEND else (scale,)
884
+
885
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
886
+ batch_size, sequence_length, _ = hidden_states.shape
887
+
888
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
889
+
890
+ if encoder_hidden_states is None:
891
+ encoder_hidden_states = hidden_states
892
+ elif attn.norm_cross:
893
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
894
+
895
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
896
+
897
+ query = attn.to_q(hidden_states, *args)
898
+ query = attn.head_to_batch_dim(query)
899
+
900
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states, *args)
901
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states, *args)
902
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
903
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
904
+
905
+ if not attn.only_cross_attention:
906
+ key = attn.to_k(hidden_states, *args)
907
+ value = attn.to_v(hidden_states, *args)
908
+ key = attn.head_to_batch_dim(key)
909
+ value = attn.head_to_batch_dim(value)
910
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
911
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
912
+ else:
913
+ key = encoder_hidden_states_key_proj
914
+ value = encoder_hidden_states_value_proj
915
+
916
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
917
+ hidden_states = torch.bmm(attention_probs, value)
918
+ hidden_states = attn.batch_to_head_dim(hidden_states)
919
+
920
+ # linear proj
921
+ hidden_states = attn.to_out[0](hidden_states, *args)
922
+ # dropout
923
+ hidden_states = attn.to_out[1](hidden_states)
924
+
925
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
926
+ hidden_states = hidden_states + residual
927
+
928
+ return hidden_states
929
+
930
+
931
+ class AttnAddedKVProcessor2_0:
932
+ r"""
933
+ Processor for performing scaled dot-product attention (enabled by default if you're using PyTorch 2.0), with extra
934
+ learnable key and value matrices for the text encoder.
935
+ """
936
+
937
+ def __init__(self):
938
+ if not hasattr(F, "scaled_dot_product_attention"):
939
+ raise ImportError(
940
+ "AttnAddedKVProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
941
+ )
942
+
943
+ def __call__(
944
+ self,
945
+ attn: Attention,
946
+ hidden_states: torch.FloatTensor,
947
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
948
+ attention_mask: Optional[torch.FloatTensor] = None,
949
+ scale: float = 1.0,
950
+ ) -> torch.Tensor:
951
+ residual = hidden_states
952
+
953
+ args = () if USE_PEFT_BACKEND else (scale,)
954
+
955
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
956
+ batch_size, sequence_length, _ = hidden_states.shape
957
+
958
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size, out_dim=4)
959
+
960
+ if encoder_hidden_states is None:
961
+ encoder_hidden_states = hidden_states
962
+ elif attn.norm_cross:
963
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
964
+
965
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
966
+
967
+ query = attn.to_q(hidden_states, *args)
968
+ query = attn.head_to_batch_dim(query, out_dim=4)
969
+
970
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
971
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
972
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj, out_dim=4)
973
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj, out_dim=4)
974
+
975
+ if not attn.only_cross_attention:
976
+ key = attn.to_k(hidden_states, *args)
977
+ value = attn.to_v(hidden_states, *args)
978
+ key = attn.head_to_batch_dim(key, out_dim=4)
979
+ value = attn.head_to_batch_dim(value, out_dim=4)
980
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
981
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
982
+ else:
983
+ key = encoder_hidden_states_key_proj
984
+ value = encoder_hidden_states_value_proj
985
+
986
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
987
+ # TODO: add support for attn.scale when we move to Torch 2.1
988
+ hidden_states = F.scaled_dot_product_attention(
989
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
990
+ )
991
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, residual.shape[1])
992
+
993
+ # linear proj
994
+ hidden_states = attn.to_out[0](hidden_states, *args)
995
+ # dropout
996
+ hidden_states = attn.to_out[1](hidden_states)
997
+
998
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
999
+ hidden_states = hidden_states + residual
1000
+
1001
+ return hidden_states
1002
+
1003
+
1004
+ class XFormersAttnAddedKVProcessor:
1005
+ r"""
1006
+ Processor for implementing memory efficient attention using xFormers.
1007
+
1008
+ Args:
1009
+ attention_op (`Callable`, *optional*, defaults to `None`):
1010
+ The base
1011
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
1012
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
1013
+ operator.
1014
+ """
1015
+
1016
+ def __init__(self, attention_op: Optional[Callable] = None):
1017
+ self.attention_op = attention_op
1018
+
1019
+ def __call__(
1020
+ self,
1021
+ attn: Attention,
1022
+ hidden_states: torch.FloatTensor,
1023
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1024
+ attention_mask: Optional[torch.FloatTensor] = None,
1025
+ ) -> torch.Tensor:
1026
+ residual = hidden_states
1027
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
1028
+ batch_size, sequence_length, _ = hidden_states.shape
1029
+
1030
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1031
+
1032
+ if encoder_hidden_states is None:
1033
+ encoder_hidden_states = hidden_states
1034
+ elif attn.norm_cross:
1035
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1036
+
1037
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1038
+
1039
+ query = attn.to_q(hidden_states)
1040
+ query = attn.head_to_batch_dim(query)
1041
+
1042
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
1043
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
1044
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
1045
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
1046
+
1047
+ if not attn.only_cross_attention:
1048
+ key = attn.to_k(hidden_states)
1049
+ value = attn.to_v(hidden_states)
1050
+ key = attn.head_to_batch_dim(key)
1051
+ value = attn.head_to_batch_dim(value)
1052
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
1053
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
1054
+ else:
1055
+ key = encoder_hidden_states_key_proj
1056
+ value = encoder_hidden_states_value_proj
1057
+
1058
+ hidden_states = xformers.ops.memory_efficient_attention(
1059
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
1060
+ )
1061
+ hidden_states = hidden_states.to(query.dtype)
1062
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1063
+
1064
+ # linear proj
1065
+ hidden_states = attn.to_out[0](hidden_states)
1066
+ # dropout
1067
+ hidden_states = attn.to_out[1](hidden_states)
1068
+
1069
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
1070
+ hidden_states = hidden_states + residual
1071
+
1072
+ return hidden_states
1073
+
1074
+
1075
+ class XFormersAttnProcessor:
1076
+ r"""
1077
+ Processor for implementing memory efficient attention using xFormers.
1078
+
1079
+ Args:
1080
+ attention_op (`Callable`, *optional*, defaults to `None`):
1081
+ The base
1082
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
1083
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
1084
+ operator.
1085
+ """
1086
+
1087
+ def __init__(self, attention_op: Optional[Callable] = None):
1088
+ self.attention_op = attention_op
1089
+
1090
+ def __call__(
1091
+ self,
1092
+ attn: Attention,
1093
+ hidden_states: torch.FloatTensor,
1094
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1095
+ attention_mask: Optional[torch.FloatTensor] = None,
1096
+ temb: Optional[torch.FloatTensor] = None,
1097
+ scale: float = 1.0,
1098
+ ) -> torch.FloatTensor:
1099
+ residual = hidden_states
1100
+
1101
+ args = () if USE_PEFT_BACKEND else (scale,)
1102
+
1103
+ if attn.spatial_norm is not None:
1104
+ hidden_states = attn.spatial_norm(hidden_states, temb)
1105
+
1106
+ input_ndim = hidden_states.ndim
1107
+
1108
+ if input_ndim == 4:
1109
+ batch_size, channel, height, width = hidden_states.shape
1110
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1111
+
1112
+ batch_size, key_tokens, _ = (
1113
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1114
+ )
1115
+
1116
+ attention_mask = attn.prepare_attention_mask(attention_mask, key_tokens, batch_size)
1117
+ if attention_mask is not None:
1118
+ # expand our mask's singleton query_tokens dimension:
1119
+ # [batch*heads, 1, key_tokens] ->
1120
+ # [batch*heads, query_tokens, key_tokens]
1121
+ # so that it can be added as a bias onto the attention scores that xformers computes:
1122
+ # [batch*heads, query_tokens, key_tokens]
1123
+ # we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
1124
+ _, query_tokens, _ = hidden_states.shape
1125
+ attention_mask = attention_mask.expand(-1, query_tokens, -1)
1126
+
1127
+ if attn.group_norm is not None:
1128
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1129
+
1130
+ query = attn.to_q(hidden_states, *args)
1131
+
1132
+ if encoder_hidden_states is None:
1133
+ encoder_hidden_states = hidden_states
1134
+ elif attn.norm_cross:
1135
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1136
+
1137
+ key = attn.to_k(encoder_hidden_states, *args)
1138
+ value = attn.to_v(encoder_hidden_states, *args)
1139
+
1140
+ query = attn.head_to_batch_dim(query).contiguous()
1141
+ key = attn.head_to_batch_dim(key).contiguous()
1142
+ value = attn.head_to_batch_dim(value).contiguous()
1143
+
1144
+ hidden_states = xformers.ops.memory_efficient_attention(
1145
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
1146
+ )
1147
+ hidden_states = hidden_states.to(query.dtype)
1148
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1149
+
1150
+ # linear proj
1151
+ hidden_states = attn.to_out[0](hidden_states, *args)
1152
+ # dropout
1153
+ hidden_states = attn.to_out[1](hidden_states)
1154
+
1155
+ if input_ndim == 4:
1156
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
1157
+
1158
+ if attn.residual_connection:
1159
+ hidden_states = hidden_states + residual
1160
+
1161
+ hidden_states = hidden_states / attn.rescale_output_factor
1162
+
1163
+ return hidden_states
1164
+
1165
+
1166
+ class AttnProcessor2_0:
1167
+ r"""
1168
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
1169
+ """
1170
+
1171
+ def __init__(self):
1172
+ if not hasattr(F, "scaled_dot_product_attention"):
1173
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
1174
+
1175
+ def __call__(
1176
+ self,
1177
+ attn: Attention,
1178
+ hidden_states: torch.FloatTensor,
1179
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1180
+ attention_mask: Optional[torch.FloatTensor] = None,
1181
+ temb: Optional[torch.FloatTensor] = None,
1182
+ scale: float = 1.0,
1183
+ ) -> torch.FloatTensor:
1184
+ residual = hidden_states
1185
+
1186
+ args = () if USE_PEFT_BACKEND else (scale,)
1187
+
1188
+ if attn.spatial_norm is not None:
1189
+ hidden_states = attn.spatial_norm(hidden_states, temb)
1190
+
1191
+ input_ndim = hidden_states.ndim
1192
+
1193
+ if input_ndim == 4:
1194
+ batch_size, channel, height, width = hidden_states.shape
1195
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1196
+
1197
+ batch_size, sequence_length, _ = (
1198
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1199
+ )
1200
+
1201
+ if attention_mask is not None:
1202
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1203
+ # scaled_dot_product_attention expects attention_mask shape to be
1204
+ # (batch, heads, source_length, target_length)
1205
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
1206
+
1207
+ if attn.group_norm is not None:
1208
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1209
+
1210
+ args = () if USE_PEFT_BACKEND else (scale,)
1211
+ query = attn.to_q(hidden_states, *args)
1212
+
1213
+ if encoder_hidden_states is None:
1214
+ encoder_hidden_states = hidden_states
1215
+ elif attn.norm_cross:
1216
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1217
+
1218
+ key = attn.to_k(encoder_hidden_states, *args)
1219
+ value = attn.to_v(encoder_hidden_states, *args)
1220
+
1221
+ inner_dim = key.shape[-1]
1222
+ head_dim = inner_dim // attn.heads
1223
+
1224
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1225
+
1226
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1227
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1228
+
1229
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
1230
+ # TODO: add support for attn.scale when we move to Torch 2.1
1231
+ hidden_states = F.scaled_dot_product_attention(
1232
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
1233
+ )
1234
+
1235
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
1236
+ hidden_states = hidden_states.to(query.dtype)
1237
+
1238
+ # linear proj
1239
+ hidden_states = attn.to_out[0](hidden_states, *args)
1240
+ # dropout
1241
+ hidden_states = attn.to_out[1](hidden_states)
1242
+
1243
+ if input_ndim == 4:
1244
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
1245
+
1246
+ if attn.residual_connection:
1247
+ hidden_states = hidden_states + residual
1248
+
1249
+ hidden_states = hidden_states / attn.rescale_output_factor
1250
+
1251
+ return hidden_states
1252
+
1253
+
1254
+ class CustomDiffusionXFormersAttnProcessor(nn.Module):
1255
+ r"""
1256
+ Processor for implementing memory efficient attention using xFormers for the Custom Diffusion method.
1257
+
1258
+ Args:
1259
+ train_kv (`bool`, defaults to `True`):
1260
+ Whether to newly train the key and value matrices corresponding to the text features.
1261
+ train_q_out (`bool`, defaults to `True`):
1262
+ Whether to newly train query matrices corresponding to the latent image features.
1263
+ hidden_size (`int`, *optional*, defaults to `None`):
1264
+ The hidden size of the attention layer.
1265
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
1266
+ The number of channels in the `encoder_hidden_states`.
1267
+ out_bias (`bool`, defaults to `True`):
1268
+ Whether to include the bias parameter in `train_q_out`.
1269
+ dropout (`float`, *optional*, defaults to 0.0):
1270
+ The dropout probability to use.
1271
+ attention_op (`Callable`, *optional*, defaults to `None`):
1272
+ The base
1273
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to use
1274
+ as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best operator.
1275
+ """
1276
+
1277
+ def __init__(
1278
+ self,
1279
+ train_kv: bool = True,
1280
+ train_q_out: bool = False,
1281
+ hidden_size: Optional[int] = None,
1282
+ cross_attention_dim: Optional[int] = None,
1283
+ out_bias: bool = True,
1284
+ dropout: float = 0.0,
1285
+ attention_op: Optional[Callable] = None,
1286
+ ):
1287
+ super().__init__()
1288
+ self.train_kv = train_kv
1289
+ self.train_q_out = train_q_out
1290
+
1291
+ self.hidden_size = hidden_size
1292
+ self.cross_attention_dim = cross_attention_dim
1293
+ self.attention_op = attention_op
1294
+
1295
+ # `_custom_diffusion` id for easy serialization and loading.
1296
+ if self.train_kv:
1297
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
1298
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
1299
+ if self.train_q_out:
1300
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
1301
+ self.to_out_custom_diffusion = nn.ModuleList([])
1302
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
1303
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
1304
+
1305
+ def __call__(
1306
+ self,
1307
+ attn: Attention,
1308
+ hidden_states: torch.FloatTensor,
1309
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1310
+ attention_mask: Optional[torch.FloatTensor] = None,
1311
+ ) -> torch.FloatTensor:
1312
+ batch_size, sequence_length, _ = (
1313
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1314
+ )
1315
+
1316
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1317
+
1318
+ if self.train_q_out:
1319
+ query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
1320
+ else:
1321
+ query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
1322
+
1323
+ if encoder_hidden_states is None:
1324
+ crossattn = False
1325
+ encoder_hidden_states = hidden_states
1326
+ else:
1327
+ crossattn = True
1328
+ if attn.norm_cross:
1329
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1330
+
1331
+ if self.train_kv:
1332
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
1333
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
1334
+ key = key.to(attn.to_q.weight.dtype)
1335
+ value = value.to(attn.to_q.weight.dtype)
1336
+ else:
1337
+ key = attn.to_k(encoder_hidden_states)
1338
+ value = attn.to_v(encoder_hidden_states)
1339
+
1340
+ if crossattn:
1341
+ detach = torch.ones_like(key)
1342
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
1343
+ key = detach * key + (1 - detach) * key.detach()
1344
+ value = detach * value + (1 - detach) * value.detach()
1345
+
1346
+ query = attn.head_to_batch_dim(query).contiguous()
1347
+ key = attn.head_to_batch_dim(key).contiguous()
1348
+ value = attn.head_to_batch_dim(value).contiguous()
1349
+
1350
+ hidden_states = xformers.ops.memory_efficient_attention(
1351
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
1352
+ )
1353
+ hidden_states = hidden_states.to(query.dtype)
1354
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1355
+
1356
+ if self.train_q_out:
1357
+ # linear proj
1358
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
1359
+ # dropout
1360
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
1361
+ else:
1362
+ # linear proj
1363
+ hidden_states = attn.to_out[0](hidden_states)
1364
+ # dropout
1365
+ hidden_states = attn.to_out[1](hidden_states)
1366
+
1367
+ return hidden_states
1368
+
1369
+
1370
+ class CustomDiffusionAttnProcessor2_0(nn.Module):
1371
+ r"""
1372
+ Processor for implementing attention for the Custom Diffusion method using PyTorch 2.0’s memory-efficient scaled
1373
+ dot-product attention.
1374
+
1375
+ Args:
1376
+ train_kv (`bool`, defaults to `True`):
1377
+ Whether to newly train the key and value matrices corresponding to the text features.
1378
+ train_q_out (`bool`, defaults to `True`):
1379
+ Whether to newly train query matrices corresponding to the latent image features.
1380
+ hidden_size (`int`, *optional*, defaults to `None`):
1381
+ The hidden size of the attention layer.
1382
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
1383
+ The number of channels in the `encoder_hidden_states`.
1384
+ out_bias (`bool`, defaults to `True`):
1385
+ Whether to include the bias parameter in `train_q_out`.
1386
+ dropout (`float`, *optional*, defaults to 0.0):
1387
+ The dropout probability to use.
1388
+ """
1389
+
1390
+ def __init__(
1391
+ self,
1392
+ train_kv: bool = True,
1393
+ train_q_out: bool = True,
1394
+ hidden_size: Optional[int] = None,
1395
+ cross_attention_dim: Optional[int] = None,
1396
+ out_bias: bool = True,
1397
+ dropout: float = 0.0,
1398
+ ):
1399
+ super().__init__()
1400
+ self.train_kv = train_kv
1401
+ self.train_q_out = train_q_out
1402
+
1403
+ self.hidden_size = hidden_size
1404
+ self.cross_attention_dim = cross_attention_dim
1405
+
1406
+ # `_custom_diffusion` id for easy serialization and loading.
1407
+ if self.train_kv:
1408
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
1409
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
1410
+ if self.train_q_out:
1411
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
1412
+ self.to_out_custom_diffusion = nn.ModuleList([])
1413
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
1414
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
1415
+
1416
+ def __call__(
1417
+ self,
1418
+ attn: Attention,
1419
+ hidden_states: torch.FloatTensor,
1420
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1421
+ attention_mask: Optional[torch.FloatTensor] = None,
1422
+ ) -> torch.FloatTensor:
1423
+ batch_size, sequence_length, _ = hidden_states.shape
1424
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1425
+ if self.train_q_out:
1426
+ query = self.to_q_custom_diffusion(hidden_states)
1427
+ else:
1428
+ query = attn.to_q(hidden_states)
1429
+
1430
+ if encoder_hidden_states is None:
1431
+ crossattn = False
1432
+ encoder_hidden_states = hidden_states
1433
+ else:
1434
+ crossattn = True
1435
+ if attn.norm_cross:
1436
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1437
+
1438
+ if self.train_kv:
1439
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
1440
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
1441
+ key = key.to(attn.to_q.weight.dtype)
1442
+ value = value.to(attn.to_q.weight.dtype)
1443
+
1444
+ else:
1445
+ key = attn.to_k(encoder_hidden_states)
1446
+ value = attn.to_v(encoder_hidden_states)
1447
+
1448
+ if crossattn:
1449
+ detach = torch.ones_like(key)
1450
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
1451
+ key = detach * key + (1 - detach) * key.detach()
1452
+ value = detach * value + (1 - detach) * value.detach()
1453
+
1454
+ inner_dim = hidden_states.shape[-1]
1455
+
1456
+ head_dim = inner_dim // attn.heads
1457
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1458
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1459
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1460
+
1461
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
1462
+ # TODO: add support for attn.scale when we move to Torch 2.1
1463
+ hidden_states = F.scaled_dot_product_attention(
1464
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
1465
+ )
1466
+
1467
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
1468
+ hidden_states = hidden_states.to(query.dtype)
1469
+
1470
+ if self.train_q_out:
1471
+ # linear proj
1472
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
1473
+ # dropout
1474
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
1475
+ else:
1476
+ # linear proj
1477
+ hidden_states = attn.to_out[0](hidden_states)
1478
+ # dropout
1479
+ hidden_states = attn.to_out[1](hidden_states)
1480
+
1481
+ return hidden_states
1482
+
1483
+
1484
+ class SlicedAttnProcessor:
1485
+ r"""
1486
+ Processor for implementing sliced attention.
1487
+
1488
+ Args:
1489
+ slice_size (`int`, *optional*):
1490
+ The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
1491
+ `attention_head_dim` must be a multiple of the `slice_size`.
1492
+ """
1493
+
1494
+ def __init__(self, slice_size: int):
1495
+ self.slice_size = slice_size
1496
+
1497
+ def __call__(
1498
+ self,
1499
+ attn: Attention,
1500
+ hidden_states: torch.FloatTensor,
1501
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1502
+ attention_mask: Optional[torch.FloatTensor] = None,
1503
+ ) -> torch.FloatTensor:
1504
+ residual = hidden_states
1505
+
1506
+ input_ndim = hidden_states.ndim
1507
+
1508
+ if input_ndim == 4:
1509
+ batch_size, channel, height, width = hidden_states.shape
1510
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
1511
+
1512
+ batch_size, sequence_length, _ = (
1513
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
1514
+ )
1515
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1516
+
1517
+ if attn.group_norm is not None:
1518
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1519
+
1520
+ query = attn.to_q(hidden_states)
1521
+ dim = query.shape[-1]
1522
+ query = attn.head_to_batch_dim(query)
1523
+
1524
+ if encoder_hidden_states is None:
1525
+ encoder_hidden_states = hidden_states
1526
+ elif attn.norm_cross:
1527
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1528
+
1529
+ key = attn.to_k(encoder_hidden_states)
1530
+ value = attn.to_v(encoder_hidden_states)
1531
+ key = attn.head_to_batch_dim(key)
1532
+ value = attn.head_to_batch_dim(value)
1533
+
1534
+ batch_size_attention, query_tokens, _ = query.shape
1535
+ hidden_states = torch.zeros(
1536
+ (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
1537
+ )
1538
+
1539
+ for i in range(batch_size_attention // self.slice_size):
1540
+ start_idx = i * self.slice_size
1541
+ end_idx = (i + 1) * self.slice_size
1542
+
1543
+ query_slice = query[start_idx:end_idx]
1544
+ key_slice = key[start_idx:end_idx]
1545
+ attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
1546
+
1547
+ attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
1548
+
1549
+ attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
1550
+
1551
+ hidden_states[start_idx:end_idx] = attn_slice
1552
+
1553
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1554
+
1555
+ # linear proj
1556
+ hidden_states = attn.to_out[0](hidden_states)
1557
+ # dropout
1558
+ hidden_states = attn.to_out[1](hidden_states)
1559
+
1560
+ if input_ndim == 4:
1561
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
1562
+
1563
+ if attn.residual_connection:
1564
+ hidden_states = hidden_states + residual
1565
+
1566
+ hidden_states = hidden_states / attn.rescale_output_factor
1567
+
1568
+ return hidden_states
1569
+
1570
+
1571
+ class SlicedAttnAddedKVProcessor:
1572
+ r"""
1573
+ Processor for implementing sliced attention with extra learnable key and value matrices for the text encoder.
1574
+
1575
+ Args:
1576
+ slice_size (`int`, *optional*):
1577
+ The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
1578
+ `attention_head_dim` must be a multiple of the `slice_size`.
1579
+ """
1580
+
1581
+ def __init__(self, slice_size):
1582
+ self.slice_size = slice_size
1583
+
1584
+ def __call__(
1585
+ self,
1586
+ attn: "Attention",
1587
+ hidden_states: torch.FloatTensor,
1588
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1589
+ attention_mask: Optional[torch.FloatTensor] = None,
1590
+ temb: Optional[torch.FloatTensor] = None,
1591
+ ) -> torch.FloatTensor:
1592
+ residual = hidden_states
1593
+
1594
+ if attn.spatial_norm is not None:
1595
+ hidden_states = attn.spatial_norm(hidden_states, temb)
1596
+
1597
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
1598
+
1599
+ batch_size, sequence_length, _ = hidden_states.shape
1600
+
1601
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
1602
+
1603
+ if encoder_hidden_states is None:
1604
+ encoder_hidden_states = hidden_states
1605
+ elif attn.norm_cross:
1606
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
1607
+
1608
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
1609
+
1610
+ query = attn.to_q(hidden_states)
1611
+ dim = query.shape[-1]
1612
+ query = attn.head_to_batch_dim(query)
1613
+
1614
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
1615
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
1616
+
1617
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
1618
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
1619
+
1620
+ if not attn.only_cross_attention:
1621
+ key = attn.to_k(hidden_states)
1622
+ value = attn.to_v(hidden_states)
1623
+ key = attn.head_to_batch_dim(key)
1624
+ value = attn.head_to_batch_dim(value)
1625
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
1626
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
1627
+ else:
1628
+ key = encoder_hidden_states_key_proj
1629
+ value = encoder_hidden_states_value_proj
1630
+
1631
+ batch_size_attention, query_tokens, _ = query.shape
1632
+ hidden_states = torch.zeros(
1633
+ (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
1634
+ )
1635
+
1636
+ for i in range(batch_size_attention // self.slice_size):
1637
+ start_idx = i * self.slice_size
1638
+ end_idx = (i + 1) * self.slice_size
1639
+
1640
+ query_slice = query[start_idx:end_idx]
1641
+ key_slice = key[start_idx:end_idx]
1642
+ attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
1643
+
1644
+ attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
1645
+
1646
+ attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
1647
+
1648
+ hidden_states[start_idx:end_idx] = attn_slice
1649
+
1650
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1651
+
1652
+ # linear proj
1653
+ hidden_states = attn.to_out[0](hidden_states)
1654
+ # dropout
1655
+ hidden_states = attn.to_out[1](hidden_states)
1656
+
1657
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
1658
+ hidden_states = hidden_states + residual
1659
+
1660
+ return hidden_states
1661
+
1662
+
1663
+ class SpatialNorm(nn.Module):
1664
+ """
1665
+ Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002.
1666
+
1667
+ Args:
1668
+ f_channels (`int`):
1669
+ The number of channels for input to group normalization layer, and output of the spatial norm layer.
1670
+ zq_channels (`int`):
1671
+ The number of channels for the quantized vector as described in the paper.
1672
+ """
1673
+
1674
+ def __init__(
1675
+ self,
1676
+ f_channels: int,
1677
+ zq_channels: int,
1678
+ ):
1679
+ super().__init__()
1680
+ self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=32, eps=1e-6, affine=True)
1681
+ self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
1682
+ self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
1683
+
1684
+ def forward(self, f: torch.FloatTensor, zq: torch.FloatTensor) -> torch.FloatTensor:
1685
+ f_size = f.shape[-2:]
1686
+ zq = F.interpolate(zq, size=f_size, mode="nearest")
1687
+ norm_f = self.norm_layer(f)
1688
+ new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
1689
+ return new_f
1690
+
1691
+
1692
+ ## Deprecated
1693
+ class LoRAAttnProcessor(nn.Module):
1694
+ r"""
1695
+ Processor for implementing the LoRA attention mechanism.
1696
+
1697
+ Args:
1698
+ hidden_size (`int`, *optional*):
1699
+ The hidden size of the attention layer.
1700
+ cross_attention_dim (`int`, *optional*):
1701
+ The number of channels in the `encoder_hidden_states`.
1702
+ rank (`int`, defaults to 4):
1703
+ The dimension of the LoRA update matrices.
1704
+ network_alpha (`int`, *optional*):
1705
+ Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
1706
+ kwargs (`dict`):
1707
+ Additional keyword arguments to pass to the `LoRALinearLayer` layers.
1708
+ """
1709
+
1710
+ def __init__(
1711
+ self,
1712
+ hidden_size: int,
1713
+ cross_attention_dim: Optional[int] = None,
1714
+ rank: int = 4,
1715
+ network_alpha: Optional[int] = None,
1716
+ **kwargs,
1717
+ ):
1718
+ super().__init__()
1719
+
1720
+ self.hidden_size = hidden_size
1721
+ self.cross_attention_dim = cross_attention_dim
1722
+ self.rank = rank
1723
+
1724
+ q_rank = kwargs.pop("q_rank", None)
1725
+ q_hidden_size = kwargs.pop("q_hidden_size", None)
1726
+ q_rank = q_rank if q_rank is not None else rank
1727
+ q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
1728
+
1729
+ v_rank = kwargs.pop("v_rank", None)
1730
+ v_hidden_size = kwargs.pop("v_hidden_size", None)
1731
+ v_rank = v_rank if v_rank is not None else rank
1732
+ v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
1733
+
1734
+ out_rank = kwargs.pop("out_rank", None)
1735
+ out_hidden_size = kwargs.pop("out_hidden_size", None)
1736
+ out_rank = out_rank if out_rank is not None else rank
1737
+ out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
1738
+
1739
+ self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
1740
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
1741
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
1742
+ self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
1743
+
1744
+ def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
1745
+ self_cls_name = self.__class__.__name__
1746
+ deprecate(
1747
+ self_cls_name,
1748
+ "0.26.0",
1749
+ (
1750
+ f"Make sure use {self_cls_name[4:]} instead by setting"
1751
+ "LoRA layers to `self.{to_q,to_k,to_v,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
1752
+ " `LoraLoaderMixin.load_lora_weights`"
1753
+ ),
1754
+ )
1755
+ attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
1756
+ attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
1757
+ attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
1758
+ attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
1759
+
1760
+ attn._modules.pop("processor")
1761
+ attn.processor = AttnProcessor()
1762
+ return attn.processor(attn, hidden_states, *args, **kwargs)
1763
+
1764
+
1765
+ class LoRAAttnProcessor2_0(nn.Module):
1766
+ r"""
1767
+ Processor for implementing the LoRA attention mechanism using PyTorch 2.0's memory-efficient scaled dot-product
1768
+ attention.
1769
+
1770
+ Args:
1771
+ hidden_size (`int`):
1772
+ The hidden size of the attention layer.
1773
+ cross_attention_dim (`int`, *optional*):
1774
+ The number of channels in the `encoder_hidden_states`.
1775
+ rank (`int`, defaults to 4):
1776
+ The dimension of the LoRA update matrices.
1777
+ network_alpha (`int`, *optional*):
1778
+ Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
1779
+ kwargs (`dict`):
1780
+ Additional keyword arguments to pass to the `LoRALinearLayer` layers.
1781
+ """
1782
+
1783
+ def __init__(
1784
+ self,
1785
+ hidden_size: int,
1786
+ cross_attention_dim: Optional[int] = None,
1787
+ rank: int = 4,
1788
+ network_alpha: Optional[int] = None,
1789
+ **kwargs,
1790
+ ):
1791
+ super().__init__()
1792
+ if not hasattr(F, "scaled_dot_product_attention"):
1793
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
1794
+
1795
+ self.hidden_size = hidden_size
1796
+ self.cross_attention_dim = cross_attention_dim
1797
+ self.rank = rank
1798
+
1799
+ q_rank = kwargs.pop("q_rank", None)
1800
+ q_hidden_size = kwargs.pop("q_hidden_size", None)
1801
+ q_rank = q_rank if q_rank is not None else rank
1802
+ q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
1803
+
1804
+ v_rank = kwargs.pop("v_rank", None)
1805
+ v_hidden_size = kwargs.pop("v_hidden_size", None)
1806
+ v_rank = v_rank if v_rank is not None else rank
1807
+ v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
1808
+
1809
+ out_rank = kwargs.pop("out_rank", None)
1810
+ out_hidden_size = kwargs.pop("out_hidden_size", None)
1811
+ out_rank = out_rank if out_rank is not None else rank
1812
+ out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
1813
+
1814
+ self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
1815
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
1816
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
1817
+ self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
1818
+
1819
+ def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
1820
+ self_cls_name = self.__class__.__name__
1821
+ deprecate(
1822
+ self_cls_name,
1823
+ "0.26.0",
1824
+ (
1825
+ f"Make sure use {self_cls_name[4:]} instead by setting"
1826
+ "LoRA layers to `self.{to_q,to_k,to_v,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
1827
+ " `LoraLoaderMixin.load_lora_weights`"
1828
+ ),
1829
+ )
1830
+ attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
1831
+ attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
1832
+ attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
1833
+ attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
1834
+
1835
+ attn._modules.pop("processor")
1836
+ attn.processor = AttnProcessor2_0()
1837
+ return attn.processor(attn, hidden_states, *args, **kwargs)
1838
+
1839
+
1840
+ class LoRAXFormersAttnProcessor(nn.Module):
1841
+ r"""
1842
+ Processor for implementing the LoRA attention mechanism with memory efficient attention using xFormers.
1843
+
1844
+ Args:
1845
+ hidden_size (`int`, *optional*):
1846
+ The hidden size of the attention layer.
1847
+ cross_attention_dim (`int`, *optional*):
1848
+ The number of channels in the `encoder_hidden_states`.
1849
+ rank (`int`, defaults to 4):
1850
+ The dimension of the LoRA update matrices.
1851
+ attention_op (`Callable`, *optional*, defaults to `None`):
1852
+ The base
1853
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
1854
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
1855
+ operator.
1856
+ network_alpha (`int`, *optional*):
1857
+ Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
1858
+ kwargs (`dict`):
1859
+ Additional keyword arguments to pass to the `LoRALinearLayer` layers.
1860
+ """
1861
+
1862
+ def __init__(
1863
+ self,
1864
+ hidden_size: int,
1865
+ cross_attention_dim: int,
1866
+ rank: int = 4,
1867
+ attention_op: Optional[Callable] = None,
1868
+ network_alpha: Optional[int] = None,
1869
+ **kwargs,
1870
+ ):
1871
+ super().__init__()
1872
+
1873
+ self.hidden_size = hidden_size
1874
+ self.cross_attention_dim = cross_attention_dim
1875
+ self.rank = rank
1876
+ self.attention_op = attention_op
1877
+
1878
+ q_rank = kwargs.pop("q_rank", None)
1879
+ q_hidden_size = kwargs.pop("q_hidden_size", None)
1880
+ q_rank = q_rank if q_rank is not None else rank
1881
+ q_hidden_size = q_hidden_size if q_hidden_size is not None else hidden_size
1882
+
1883
+ v_rank = kwargs.pop("v_rank", None)
1884
+ v_hidden_size = kwargs.pop("v_hidden_size", None)
1885
+ v_rank = v_rank if v_rank is not None else rank
1886
+ v_hidden_size = v_hidden_size if v_hidden_size is not None else hidden_size
1887
+
1888
+ out_rank = kwargs.pop("out_rank", None)
1889
+ out_hidden_size = kwargs.pop("out_hidden_size", None)
1890
+ out_rank = out_rank if out_rank is not None else rank
1891
+ out_hidden_size = out_hidden_size if out_hidden_size is not None else hidden_size
1892
+
1893
+ self.to_q_lora = LoRALinearLayer(q_hidden_size, q_hidden_size, q_rank, network_alpha)
1894
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
1895
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or v_hidden_size, v_hidden_size, v_rank, network_alpha)
1896
+ self.to_out_lora = LoRALinearLayer(out_hidden_size, out_hidden_size, out_rank, network_alpha)
1897
+
1898
+ def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
1899
+ self_cls_name = self.__class__.__name__
1900
+ deprecate(
1901
+ self_cls_name,
1902
+ "0.26.0",
1903
+ (
1904
+ f"Make sure use {self_cls_name[4:]} instead by setting"
1905
+ "LoRA layers to `self.{to_q,to_k,to_v,add_k_proj,add_v_proj,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
1906
+ " `LoraLoaderMixin.load_lora_weights`"
1907
+ ),
1908
+ )
1909
+ attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
1910
+ attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
1911
+ attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
1912
+ attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
1913
+
1914
+ attn._modules.pop("processor")
1915
+ attn.processor = XFormersAttnProcessor()
1916
+ return attn.processor(attn, hidden_states, *args, **kwargs)
1917
+
1918
+
1919
+ class LoRAAttnAddedKVProcessor(nn.Module):
1920
+ r"""
1921
+ Processor for implementing the LoRA attention mechanism with extra learnable key and value matrices for the text
1922
+ encoder.
1923
+
1924
+ Args:
1925
+ hidden_size (`int`, *optional*):
1926
+ The hidden size of the attention layer.
1927
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
1928
+ The number of channels in the `encoder_hidden_states`.
1929
+ rank (`int`, defaults to 4):
1930
+ The dimension of the LoRA update matrices.
1931
+ network_alpha (`int`, *optional*):
1932
+ Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
1933
+ kwargs (`dict`):
1934
+ Additional keyword arguments to pass to the `LoRALinearLayer` layers.
1935
+ """
1936
+
1937
+ def __init__(
1938
+ self,
1939
+ hidden_size: int,
1940
+ cross_attention_dim: Optional[int] = None,
1941
+ rank: int = 4,
1942
+ network_alpha: Optional[int] = None,
1943
+ ):
1944
+ super().__init__()
1945
+
1946
+ self.hidden_size = hidden_size
1947
+ self.cross_attention_dim = cross_attention_dim
1948
+ self.rank = rank
1949
+
1950
+ self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
1951
+ self.add_k_proj_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
1952
+ self.add_v_proj_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
1953
+ self.to_k_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
1954
+ self.to_v_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
1955
+ self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
1956
+
1957
+ def __call__(self, attn: Attention, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
1958
+ self_cls_name = self.__class__.__name__
1959
+ deprecate(
1960
+ self_cls_name,
1961
+ "0.26.0",
1962
+ (
1963
+ f"Make sure use {self_cls_name[4:]} instead by setting"
1964
+ "LoRA layers to `self.{to_q,to_k,to_v,add_k_proj,add_v_proj,to_out[0]}.lora_layer` respectively. This will be done automatically when using"
1965
+ " `LoraLoaderMixin.load_lora_weights`"
1966
+ ),
1967
+ )
1968
+ attn.to_q.lora_layer = self.to_q_lora.to(hidden_states.device)
1969
+ attn.to_k.lora_layer = self.to_k_lora.to(hidden_states.device)
1970
+ attn.to_v.lora_layer = self.to_v_lora.to(hidden_states.device)
1971
+ attn.to_out[0].lora_layer = self.to_out_lora.to(hidden_states.device)
1972
+
1973
+ attn._modules.pop("processor")
1974
+ attn.processor = AttnAddedKVProcessor()
1975
+ return attn.processor(attn, hidden_states, *args, **kwargs)
1976
+
1977
+
1978
+ class IPAdapterAttnProcessor(nn.Module):
1979
+ r"""
1980
+ Attention processor for IP-Adapater.
1981
+
1982
+ Args:
1983
+ hidden_size (`int`):
1984
+ The hidden size of the attention layer.
1985
+ cross_attention_dim (`int`):
1986
+ The number of channels in the `encoder_hidden_states`.
1987
+ num_tokens (`int`, defaults to 4):
1988
+ The context length of the image features.
1989
+ scale (`float`, defaults to 1.0):
1990
+ the weight scale of image prompt.
1991
+ """
1992
+
1993
+ def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
1994
+ super().__init__()
1995
+
1996
+ self.hidden_size = hidden_size
1997
+ self.cross_attention_dim = cross_attention_dim
1998
+ self.num_tokens = num_tokens
1999
+ self.scale = scale
2000
+
2001
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2002
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2003
+
2004
+ def __call__(
2005
+ self,
2006
+ attn,
2007
+ hidden_states,
2008
+ encoder_hidden_states=None,
2009
+ attention_mask=None,
2010
+ temb=None,
2011
+ scale=1.0,
2012
+ ):
2013
+ if scale != 1.0:
2014
+ logger.warning("`scale` of IPAttnProcessor should be set with `set_ip_adapter_scale`.")
2015
+ residual = hidden_states
2016
+
2017
+ if attn.spatial_norm is not None:
2018
+ hidden_states = attn.spatial_norm(hidden_states, temb)
2019
+
2020
+ input_ndim = hidden_states.ndim
2021
+
2022
+ if input_ndim == 4:
2023
+ batch_size, channel, height, width = hidden_states.shape
2024
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2025
+
2026
+ batch_size, sequence_length, _ = (
2027
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2028
+ )
2029
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
2030
+
2031
+ if attn.group_norm is not None:
2032
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
2033
+
2034
+ query = attn.to_q(hidden_states)
2035
+
2036
+ if encoder_hidden_states is None:
2037
+ encoder_hidden_states = hidden_states
2038
+ elif attn.norm_cross:
2039
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
2040
+
2041
+ # split hidden states
2042
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
2043
+ encoder_hidden_states, ip_hidden_states = (
2044
+ encoder_hidden_states[:, :end_pos, :],
2045
+ encoder_hidden_states[:, end_pos:, :],
2046
+ )
2047
+
2048
+ key = attn.to_k(encoder_hidden_states)
2049
+ value = attn.to_v(encoder_hidden_states)
2050
+
2051
+ query = attn.head_to_batch_dim(query)
2052
+ key = attn.head_to_batch_dim(key)
2053
+ value = attn.head_to_batch_dim(value)
2054
+
2055
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
2056
+ hidden_states = torch.bmm(attention_probs, value)
2057
+ hidden_states = attn.batch_to_head_dim(hidden_states)
2058
+
2059
+ # for ip-adapter
2060
+ ip_key = self.to_k_ip(ip_hidden_states)
2061
+ ip_value = self.to_v_ip(ip_hidden_states)
2062
+
2063
+ ip_key = attn.head_to_batch_dim(ip_key)
2064
+ ip_value = attn.head_to_batch_dim(ip_value)
2065
+
2066
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
2067
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
2068
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
2069
+
2070
+ hidden_states = hidden_states + self.scale * ip_hidden_states
2071
+
2072
+ # linear proj
2073
+ hidden_states = attn.to_out[0](hidden_states)
2074
+ # dropout
2075
+ hidden_states = attn.to_out[1](hidden_states)
2076
+
2077
+ if input_ndim == 4:
2078
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
2079
+
2080
+ if attn.residual_connection:
2081
+ hidden_states = hidden_states + residual
2082
+
2083
+ hidden_states = hidden_states / attn.rescale_output_factor
2084
+
2085
+ return hidden_states
2086
+
2087
+
2088
+ class IPAdapterAttnProcessor2_0(torch.nn.Module):
2089
+ r"""
2090
+ Attention processor for IP-Adapater for PyTorch 2.0.
2091
+
2092
+ Args:
2093
+ hidden_size (`int`):
2094
+ The hidden size of the attention layer.
2095
+ cross_attention_dim (`int`):
2096
+ The number of channels in the `encoder_hidden_states`.
2097
+ num_tokens (`int`, defaults to 4):
2098
+ The context length of the image features.
2099
+ scale (`float`, defaults to 1.0):
2100
+ the weight scale of image prompt.
2101
+ """
2102
+
2103
+ def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=4, scale=1.0):
2104
+ super().__init__()
2105
+
2106
+ if not hasattr(F, "scaled_dot_product_attention"):
2107
+ raise ImportError(
2108
+ f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
2109
+ )
2110
+
2111
+ self.hidden_size = hidden_size
2112
+ self.cross_attention_dim = cross_attention_dim
2113
+ self.num_tokens = num_tokens
2114
+ self.scale = scale
2115
+
2116
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2117
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
2118
+
2119
+ def __call__(
2120
+ self,
2121
+ attn,
2122
+ hidden_states,
2123
+ encoder_hidden_states=None,
2124
+ attention_mask=None,
2125
+ temb=None,
2126
+ scale=1.0,
2127
+ ):
2128
+ if scale != 1.0:
2129
+ logger.warning("`scale` of IPAttnProcessor should be set by `set_ip_adapter_scale`.")
2130
+ residual = hidden_states
2131
+
2132
+ if attn.spatial_norm is not None:
2133
+ hidden_states = attn.spatial_norm(hidden_states, temb)
2134
+
2135
+ input_ndim = hidden_states.ndim
2136
+
2137
+ if input_ndim == 4:
2138
+ batch_size, channel, height, width = hidden_states.shape
2139
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
2140
+
2141
+ batch_size, sequence_length, _ = (
2142
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
2143
+ )
2144
+
2145
+ if attention_mask is not None:
2146
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
2147
+ # scaled_dot_product_attention expects attention_mask shape to be
2148
+ # (batch, heads, source_length, target_length)
2149
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
2150
+
2151
+ if attn.group_norm is not None:
2152
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
2153
+
2154
+ query = attn.to_q(hidden_states)
2155
+
2156
+ if encoder_hidden_states is None:
2157
+ encoder_hidden_states = hidden_states
2158
+ elif attn.norm_cross:
2159
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
2160
+
2161
+ # split hidden states
2162
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
2163
+ encoder_hidden_states, ip_hidden_states = (
2164
+ encoder_hidden_states[:, :end_pos, :],
2165
+ encoder_hidden_states[:, end_pos:, :],
2166
+ )
2167
+
2168
+ key = attn.to_k(encoder_hidden_states)
2169
+ value = attn.to_v(encoder_hidden_states)
2170
+
2171
+ inner_dim = key.shape[-1]
2172
+ head_dim = inner_dim // attn.heads
2173
+
2174
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
2175
+
2176
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
2177
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
2178
+
2179
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
2180
+ # TODO: add support for attn.scale when we move to Torch 2.1
2181
+ hidden_states = F.scaled_dot_product_attention(
2182
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
2183
+ )
2184
+
2185
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
2186
+ hidden_states = hidden_states.to(query.dtype)
2187
+
2188
+ # for ip-adapter
2189
+ ip_key = self.to_k_ip(ip_hidden_states)
2190
+ ip_value = self.to_v_ip(ip_hidden_states)
2191
+
2192
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
2193
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
2194
+
2195
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
2196
+ # TODO: add support for attn.scale when we move to Torch 2.1
2197
+ ip_hidden_states = F.scaled_dot_product_attention(
2198
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
2199
+ )
2200
+
2201
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
2202
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
2203
+
2204
+ hidden_states = hidden_states + self.scale * ip_hidden_states
2205
+
2206
+ # linear proj
2207
+ hidden_states = attn.to_out[0](hidden_states)
2208
+ # dropout
2209
+ hidden_states = attn.to_out[1](hidden_states)
2210
+
2211
+ if input_ndim == 4:
2212
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
2213
+
2214
+ if attn.residual_connection:
2215
+ hidden_states = hidden_states + residual
2216
+
2217
+ hidden_states = hidden_states / attn.rescale_output_factor
2218
+
2219
+ return hidden_states
2220
+
2221
+
2222
+ # TODO(Yiyi): This class should not exist, we can replace it with a normal attention processor I believe
2223
+ # this way torch.compile and co. will work as well
2224
+ class Kandi3AttnProcessor:
2225
+ r"""
2226
+ Default kandinsky3 proccesor for performing attention-related computations.
2227
+ """
2228
+
2229
+ @staticmethod
2230
+ def _reshape(hid_states, h):
2231
+ b, n, f = hid_states.shape
2232
+ d = f // h
2233
+ return hid_states.unsqueeze(-1).reshape(b, n, h, d).permute(0, 2, 1, 3)
2234
+
2235
+ def __call__(
2236
+ self,
2237
+ attn,
2238
+ x,
2239
+ context,
2240
+ context_mask=None,
2241
+ ):
2242
+ query = self._reshape(attn.to_q(x), h=attn.num_heads)
2243
+ key = self._reshape(attn.to_k(context), h=attn.num_heads)
2244
+ value = self._reshape(attn.to_v(context), h=attn.num_heads)
2245
+
2246
+ attention_matrix = einsum("b h i d, b h j d -> b h i j", query, key)
2247
+
2248
+ if context_mask is not None:
2249
+ max_neg_value = -torch.finfo(attention_matrix.dtype).max
2250
+ context_mask = context_mask.unsqueeze(1).unsqueeze(1)
2251
+ attention_matrix = attention_matrix.masked_fill(~(context_mask != 0), max_neg_value)
2252
+ attention_matrix = (attention_matrix * attn.scale).softmax(dim=-1)
2253
+
2254
+ out = einsum("b h i j, b h j d -> b h i d", attention_matrix, value)
2255
+ out = out.permute(0, 2, 1, 3).reshape(out.shape[0], out.shape[2], -1)
2256
+ out = attn.to_out[0](out)
2257
+ return out
2258
+
2259
+
2260
+ LORA_ATTENTION_PROCESSORS = (
2261
+ LoRAAttnProcessor,
2262
+ LoRAAttnProcessor2_0,
2263
+ LoRAXFormersAttnProcessor,
2264
+ LoRAAttnAddedKVProcessor,
2265
+ )
2266
+
2267
+ ADDED_KV_ATTENTION_PROCESSORS = (
2268
+ AttnAddedKVProcessor,
2269
+ SlicedAttnAddedKVProcessor,
2270
+ AttnAddedKVProcessor2_0,
2271
+ XFormersAttnAddedKVProcessor,
2272
+ LoRAAttnAddedKVProcessor,
2273
+ )
2274
+
2275
+ CROSS_ATTENTION_PROCESSORS = (
2276
+ AttnProcessor,
2277
+ AttnProcessor2_0,
2278
+ XFormersAttnProcessor,
2279
+ SlicedAttnProcessor,
2280
+ LoRAAttnProcessor,
2281
+ LoRAAttnProcessor2_0,
2282
+ LoRAXFormersAttnProcessor,
2283
+ IPAdapterAttnProcessor,
2284
+ IPAdapterAttnProcessor2_0,
2285
+ Kandi3AttnProcessor,
2286
+ )
2287
+
2288
+ AttentionProcessor = Union[
2289
+ AttnProcessor,
2290
+ AttnProcessor2_0,
2291
+ XFormersAttnProcessor,
2292
+ SlicedAttnProcessor,
2293
+ AttnAddedKVProcessor,
2294
+ SlicedAttnAddedKVProcessor,
2295
+ AttnAddedKVProcessor2_0,
2296
+ XFormersAttnAddedKVProcessor,
2297
+ CustomDiffusionAttnProcessor,
2298
+ CustomDiffusionXFormersAttnProcessor,
2299
+ CustomDiffusionAttnProcessor2_0,
2300
+ # deprecated
2301
+ LoRAAttnProcessor,
2302
+ LoRAAttnProcessor2_0,
2303
+ LoRAXFormersAttnProcessor,
2304
+ LoRAAttnAddedKVProcessor,
2305
+ ]
diffusers/models/autoencoder_asym_kl.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 Optional, Tuple, Union
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+
19
+ from ..configuration_utils import ConfigMixin, register_to_config
20
+ from ..utils.accelerate_utils import apply_forward_hook
21
+ from .modeling_outputs import AutoencoderKLOutput
22
+ from .modeling_utils import ModelMixin
23
+ from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder, MaskConditionDecoder
24
+
25
+
26
+ class AsymmetricAutoencoderKL(ModelMixin, ConfigMixin):
27
+ r"""
28
+ Designing a Better Asymmetric VQGAN for StableDiffusion https://arxiv.org/abs/2306.04632 . A VAE model with KL loss
29
+ for encoding images into latents and decoding latent representations into images.
30
+
31
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
32
+ for all models (such as downloading or saving).
33
+
34
+ Parameters:
35
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
36
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
37
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
38
+ Tuple of downsample block types.
39
+ down_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
40
+ Tuple of down block output channels.
41
+ layers_per_down_block (`int`, *optional*, defaults to `1`):
42
+ Number layers for down block.
43
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
44
+ Tuple of upsample block types.
45
+ up_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
46
+ Tuple of up block output channels.
47
+ layers_per_up_block (`int`, *optional*, defaults to `1`):
48
+ Number layers for up block.
49
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
50
+ latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
51
+ sample_size (`int`, *optional*, defaults to `32`): Sample input size.
52
+ norm_num_groups (`int`, *optional*, defaults to `32`):
53
+ Number of groups to use for the first normalization layer in ResNet blocks.
54
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
55
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
56
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
57
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
58
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
59
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
60
+ Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
61
+ """
62
+
63
+ @register_to_config
64
+ def __init__(
65
+ self,
66
+ in_channels: int = 3,
67
+ out_channels: int = 3,
68
+ down_block_types: Tuple[str, ...] = ("DownEncoderBlock2D",),
69
+ down_block_out_channels: Tuple[int, ...] = (64,),
70
+ layers_per_down_block: int = 1,
71
+ up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
72
+ up_block_out_channels: Tuple[int, ...] = (64,),
73
+ layers_per_up_block: int = 1,
74
+ act_fn: str = "silu",
75
+ latent_channels: int = 4,
76
+ norm_num_groups: int = 32,
77
+ sample_size: int = 32,
78
+ scaling_factor: float = 0.18215,
79
+ ) -> None:
80
+ super().__init__()
81
+
82
+ # pass init params to Encoder
83
+ self.encoder = Encoder(
84
+ in_channels=in_channels,
85
+ out_channels=latent_channels,
86
+ down_block_types=down_block_types,
87
+ block_out_channels=down_block_out_channels,
88
+ layers_per_block=layers_per_down_block,
89
+ act_fn=act_fn,
90
+ norm_num_groups=norm_num_groups,
91
+ double_z=True,
92
+ )
93
+
94
+ # pass init params to Decoder
95
+ self.decoder = MaskConditionDecoder(
96
+ in_channels=latent_channels,
97
+ out_channels=out_channels,
98
+ up_block_types=up_block_types,
99
+ block_out_channels=up_block_out_channels,
100
+ layers_per_block=layers_per_up_block,
101
+ act_fn=act_fn,
102
+ norm_num_groups=norm_num_groups,
103
+ )
104
+
105
+ self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
106
+ self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1)
107
+
108
+ self.use_slicing = False
109
+ self.use_tiling = False
110
+
111
+ self.register_to_config(block_out_channels=up_block_out_channels)
112
+ self.register_to_config(force_upcast=False)
113
+
114
+ @apply_forward_hook
115
+ def encode(
116
+ self, x: torch.FloatTensor, return_dict: bool = True
117
+ ) -> Union[AutoencoderKLOutput, Tuple[torch.FloatTensor]]:
118
+ h = self.encoder(x)
119
+ moments = self.quant_conv(h)
120
+ posterior = DiagonalGaussianDistribution(moments)
121
+
122
+ if not return_dict:
123
+ return (posterior,)
124
+
125
+ return AutoencoderKLOutput(latent_dist=posterior)
126
+
127
+ def _decode(
128
+ self,
129
+ z: torch.FloatTensor,
130
+ image: Optional[torch.FloatTensor] = None,
131
+ mask: Optional[torch.FloatTensor] = None,
132
+ return_dict: bool = True,
133
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
134
+ z = self.post_quant_conv(z)
135
+ dec = self.decoder(z, image, mask)
136
+
137
+ if not return_dict:
138
+ return (dec,)
139
+
140
+ return DecoderOutput(sample=dec)
141
+
142
+ @apply_forward_hook
143
+ def decode(
144
+ self,
145
+ z: torch.FloatTensor,
146
+ generator: Optional[torch.Generator] = None,
147
+ image: Optional[torch.FloatTensor] = None,
148
+ mask: Optional[torch.FloatTensor] = None,
149
+ return_dict: bool = True,
150
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
151
+ decoded = self._decode(z, image, mask).sample
152
+
153
+ if not return_dict:
154
+ return (decoded,)
155
+
156
+ return DecoderOutput(sample=decoded)
157
+
158
+ def forward(
159
+ self,
160
+ sample: torch.FloatTensor,
161
+ mask: Optional[torch.FloatTensor] = None,
162
+ sample_posterior: bool = False,
163
+ return_dict: bool = True,
164
+ generator: Optional[torch.Generator] = None,
165
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
166
+ r"""
167
+ Args:
168
+ sample (`torch.FloatTensor`): Input sample.
169
+ mask (`torch.FloatTensor`, *optional*, defaults to `None`): Optional inpainting mask.
170
+ sample_posterior (`bool`, *optional*, defaults to `False`):
171
+ Whether to sample from the posterior.
172
+ return_dict (`bool`, *optional*, defaults to `True`):
173
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
174
+ """
175
+ x = sample
176
+ posterior = self.encode(x).latent_dist
177
+ if sample_posterior:
178
+ z = posterior.sample(generator=generator)
179
+ else:
180
+ z = posterior.mode()
181
+ dec = self.decode(z, sample, mask).sample
182
+
183
+ if not return_dict:
184
+ return (dec,)
185
+
186
+ return DecoderOutput(sample=dec)
{diffuserss → diffusers}/models/autoencoder_kl.py RENAMED
@@ -447,4 +447,4 @@ class AutoencoderKL(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
447
  if not return_dict:
448
  return (dec,)
449
 
450
- return DecoderOutput(sample=dec)
 
447
  if not return_dict:
448
  return (dec,)
449
 
450
+ return DecoderOutput(sample=dec)
diffusers/models/autoencoder_kl_temporal_decoder.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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, Optional, Tuple, Union
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+
19
+ from ..configuration_utils import ConfigMixin, register_to_config
20
+ from ..loaders import FromOriginalVAEMixin
21
+ from ..utils import is_torch_version
22
+ from ..utils.accelerate_utils import apply_forward_hook
23
+ from .attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
24
+ from .modeling_outputs import AutoencoderKLOutput
25
+ from .modeling_utils import ModelMixin
26
+ from .unet_3d_blocks import MidBlockTemporalDecoder, UpBlockTemporalDecoder
27
+ from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
28
+
29
+
30
+ class TemporalDecoder(nn.Module):
31
+ def __init__(
32
+ self,
33
+ in_channels: int = 4,
34
+ out_channels: int = 3,
35
+ block_out_channels: Tuple[int] = (128, 256, 512, 512),
36
+ layers_per_block: int = 2,
37
+ ):
38
+ super().__init__()
39
+ self.layers_per_block = layers_per_block
40
+
41
+ self.conv_in = nn.Conv2d(in_channels, block_out_channels[-1], kernel_size=3, stride=1, padding=1)
42
+ self.mid_block = MidBlockTemporalDecoder(
43
+ num_layers=self.layers_per_block,
44
+ in_channels=block_out_channels[-1],
45
+ out_channels=block_out_channels[-1],
46
+ attention_head_dim=block_out_channels[-1],
47
+ )
48
+
49
+ # up
50
+ self.up_blocks = nn.ModuleList([])
51
+ reversed_block_out_channels = list(reversed(block_out_channels))
52
+ output_channel = reversed_block_out_channels[0]
53
+ for i in range(len(block_out_channels)):
54
+ prev_output_channel = output_channel
55
+ output_channel = reversed_block_out_channels[i]
56
+
57
+ is_final_block = i == len(block_out_channels) - 1
58
+ up_block = UpBlockTemporalDecoder(
59
+ num_layers=self.layers_per_block + 1,
60
+ in_channels=prev_output_channel,
61
+ out_channels=output_channel,
62
+ add_upsample=not is_final_block,
63
+ )
64
+ self.up_blocks.append(up_block)
65
+ prev_output_channel = output_channel
66
+
67
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-6)
68
+
69
+ self.conv_act = nn.SiLU()
70
+ self.conv_out = torch.nn.Conv2d(
71
+ in_channels=block_out_channels[0],
72
+ out_channels=out_channels,
73
+ kernel_size=3,
74
+ padding=1,
75
+ )
76
+
77
+ conv_out_kernel_size = (3, 1, 1)
78
+ padding = [int(k // 2) for k in conv_out_kernel_size]
79
+ self.time_conv_out = torch.nn.Conv3d(
80
+ in_channels=out_channels,
81
+ out_channels=out_channels,
82
+ kernel_size=conv_out_kernel_size,
83
+ padding=padding,
84
+ )
85
+
86
+ self.gradient_checkpointing = False
87
+
88
+ def forward(
89
+ self,
90
+ sample: torch.FloatTensor,
91
+ image_only_indicator: torch.FloatTensor,
92
+ num_frames: int = 1,
93
+ ) -> torch.FloatTensor:
94
+ r"""The forward method of the `Decoder` class."""
95
+
96
+ sample = self.conv_in(sample)
97
+
98
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
99
+ if self.training and self.gradient_checkpointing:
100
+
101
+ def create_custom_forward(module):
102
+ def custom_forward(*inputs):
103
+ return module(*inputs)
104
+
105
+ return custom_forward
106
+
107
+ if is_torch_version(">=", "1.11.0"):
108
+ # middle
109
+ sample = torch.utils.checkpoint.checkpoint(
110
+ create_custom_forward(self.mid_block),
111
+ sample,
112
+ image_only_indicator,
113
+ use_reentrant=False,
114
+ )
115
+ sample = sample.to(upscale_dtype)
116
+
117
+ # up
118
+ for up_block in self.up_blocks:
119
+ sample = torch.utils.checkpoint.checkpoint(
120
+ create_custom_forward(up_block),
121
+ sample,
122
+ image_only_indicator,
123
+ use_reentrant=False,
124
+ )
125
+ else:
126
+ # middle
127
+ sample = torch.utils.checkpoint.checkpoint(
128
+ create_custom_forward(self.mid_block),
129
+ sample,
130
+ image_only_indicator,
131
+ )
132
+ sample = sample.to(upscale_dtype)
133
+
134
+ # up
135
+ for up_block in self.up_blocks:
136
+ sample = torch.utils.checkpoint.checkpoint(
137
+ create_custom_forward(up_block),
138
+ sample,
139
+ image_only_indicator,
140
+ )
141
+ else:
142
+ # middle
143
+ sample = self.mid_block(sample, image_only_indicator=image_only_indicator)
144
+ sample = sample.to(upscale_dtype)
145
+
146
+ # up
147
+ for up_block in self.up_blocks:
148
+ sample = up_block(sample, image_only_indicator=image_only_indicator)
149
+
150
+ # post-process
151
+ sample = self.conv_norm_out(sample)
152
+ sample = self.conv_act(sample)
153
+ sample = self.conv_out(sample)
154
+
155
+ batch_frames, channels, height, width = sample.shape
156
+ batch_size = batch_frames // num_frames
157
+ sample = sample[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
158
+ sample = self.time_conv_out(sample)
159
+
160
+ sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
161
+
162
+ return sample
163
+
164
+
165
+ class AutoencoderKLTemporalDecoder(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
166
+ r"""
167
+ A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
168
+
169
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
170
+ for all models (such as downloading or saving).
171
+
172
+ Parameters:
173
+ in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
174
+ out_channels (int, *optional*, defaults to 3): Number of channels in the output.
175
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
176
+ Tuple of downsample block types.
177
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
178
+ Tuple of block output channels.
179
+ layers_per_block: (`int`, *optional*, defaults to 1): Number of layers per block.
180
+ latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
181
+ sample_size (`int`, *optional*, defaults to `32`): Sample input size.
182
+ scaling_factor (`float`, *optional*, defaults to 0.18215):
183
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
184
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
185
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
186
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
187
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
188
+ Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
189
+ force_upcast (`bool`, *optional*, default to `True`):
190
+ If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
191
+ can be fine-tuned / trained to a lower range without loosing too much precision in which case
192
+ `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
193
+ """
194
+
195
+ _supports_gradient_checkpointing = True
196
+
197
+ @register_to_config
198
+ def __init__(
199
+ self,
200
+ in_channels: int = 3,
201
+ out_channels: int = 3,
202
+ down_block_types: Tuple[str] = ("DownEncoderBlock2D",),
203
+ block_out_channels: Tuple[int] = (64,),
204
+ layers_per_block: int = 1,
205
+ latent_channels: int = 4,
206
+ sample_size: int = 32,
207
+ scaling_factor: float = 0.18215,
208
+ force_upcast: float = True,
209
+ ):
210
+ super().__init__()
211
+
212
+ # pass init params to Encoder
213
+ self.encoder = Encoder(
214
+ in_channels=in_channels,
215
+ out_channels=latent_channels,
216
+ down_block_types=down_block_types,
217
+ block_out_channels=block_out_channels,
218
+ layers_per_block=layers_per_block,
219
+ double_z=True,
220
+ )
221
+
222
+ # pass init params to Decoder
223
+ self.decoder = TemporalDecoder(
224
+ in_channels=latent_channels,
225
+ out_channels=out_channels,
226
+ block_out_channels=block_out_channels,
227
+ layers_per_block=layers_per_block,
228
+ )
229
+
230
+ self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
231
+
232
+ sample_size = (
233
+ self.config.sample_size[0]
234
+ if isinstance(self.config.sample_size, (list, tuple))
235
+ else self.config.sample_size
236
+ )
237
+ self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
238
+ self.tile_overlap_factor = 0.25
239
+
240
+ def _set_gradient_checkpointing(self, module, value=False):
241
+ if isinstance(module, (Encoder, TemporalDecoder)):
242
+ module.gradient_checkpointing = value
243
+
244
+ @property
245
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
246
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
247
+ r"""
248
+ Returns:
249
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
250
+ indexed by its weight name.
251
+ """
252
+ # set recursively
253
+ processors = {}
254
+
255
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
256
+ if hasattr(module, "get_processor"):
257
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
258
+
259
+ for sub_name, child in module.named_children():
260
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
261
+
262
+ return processors
263
+
264
+ for name, module in self.named_children():
265
+ fn_recursive_add_processors(name, module, processors)
266
+
267
+ return processors
268
+
269
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
270
+ def set_attn_processor(
271
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
272
+ ):
273
+ r"""
274
+ Sets the attention processor to use to compute attention.
275
+
276
+ Parameters:
277
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
278
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
279
+ for **all** `Attention` layers.
280
+
281
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
282
+ processor. This is strongly recommended when setting trainable attention processors.
283
+
284
+ """
285
+ count = len(self.attn_processors.keys())
286
+
287
+ if isinstance(processor, dict) and len(processor) != count:
288
+ raise ValueError(
289
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
290
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
291
+ )
292
+
293
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
294
+ if hasattr(module, "set_processor"):
295
+ if not isinstance(processor, dict):
296
+ module.set_processor(processor, _remove_lora=_remove_lora)
297
+ else:
298
+ module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
299
+
300
+ for sub_name, child in module.named_children():
301
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
302
+
303
+ for name, module in self.named_children():
304
+ fn_recursive_attn_processor(name, module, processor)
305
+
306
+ def set_default_attn_processor(self):
307
+ """
308
+ Disables custom attention processors and sets the default attention implementation.
309
+ """
310
+ if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
311
+ processor = AttnProcessor()
312
+ else:
313
+ raise ValueError(
314
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
315
+ )
316
+
317
+ self.set_attn_processor(processor, _remove_lora=True)
318
+
319
+ @apply_forward_hook
320
+ def encode(
321
+ self, x: torch.FloatTensor, return_dict: bool = True
322
+ ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
323
+ """
324
+ Encode a batch of images into latents.
325
+
326
+ Args:
327
+ x (`torch.FloatTensor`): Input batch of images.
328
+ return_dict (`bool`, *optional*, defaults to `True`):
329
+ Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
330
+
331
+ Returns:
332
+ The latent representations of the encoded images. If `return_dict` is True, a
333
+ [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
334
+ """
335
+ h = self.encoder(x)
336
+ moments = self.quant_conv(h)
337
+ posterior = DiagonalGaussianDistribution(moments)
338
+
339
+ if not return_dict:
340
+ return (posterior,)
341
+
342
+ return AutoencoderKLOutput(latent_dist=posterior)
343
+
344
+ @apply_forward_hook
345
+ def decode(
346
+ self,
347
+ z: torch.FloatTensor,
348
+ num_frames: int,
349
+ return_dict: bool = True,
350
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
351
+ """
352
+ Decode a batch of images.
353
+
354
+ Args:
355
+ z (`torch.FloatTensor`): Input batch of latent vectors.
356
+ return_dict (`bool`, *optional*, defaults to `True`):
357
+ Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
358
+
359
+ Returns:
360
+ [`~models.vae.DecoderOutput`] or `tuple`:
361
+ If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
362
+ returned.
363
+
364
+ """
365
+ batch_size = z.shape[0] // num_frames
366
+ image_only_indicator = torch.zeros(batch_size, num_frames, dtype=z.dtype, device=z.device)
367
+ decoded = self.decoder(z, num_frames=num_frames, image_only_indicator=image_only_indicator)
368
+
369
+ if not return_dict:
370
+ return (decoded,)
371
+
372
+ return DecoderOutput(sample=decoded)
373
+
374
+ def forward(
375
+ self,
376
+ sample: torch.FloatTensor,
377
+ sample_posterior: bool = False,
378
+ return_dict: bool = True,
379
+ generator: Optional[torch.Generator] = None,
380
+ num_frames: int = 1,
381
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
382
+ r"""
383
+ Args:
384
+ sample (`torch.FloatTensor`): Input sample.
385
+ sample_posterior (`bool`, *optional*, defaults to `False`):
386
+ Whether to sample from the posterior.
387
+ return_dict (`bool`, *optional*, defaults to `True`):
388
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
389
+ """
390
+ x = sample
391
+ posterior = self.encode(x).latent_dist
392
+ if sample_posterior:
393
+ z = posterior.sample(generator=generator)
394
+ else:
395
+ z = posterior.mode()
396
+
397
+ dec = self.decode(z, num_frames=num_frames).sample
398
+
399
+ if not return_dict:
400
+ return (dec,)
401
+
402
+ return DecoderOutput(sample=dec)
diffusers/models/autoencoder_tiny.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Ollin Boer Bohan and 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
+ from dataclasses import dataclass
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+
21
+ from ..configuration_utils import ConfigMixin, register_to_config
22
+ from ..utils import BaseOutput
23
+ from ..utils.accelerate_utils import apply_forward_hook
24
+ from .modeling_utils import ModelMixin
25
+ from .vae import DecoderOutput, DecoderTiny, EncoderTiny
26
+
27
+
28
+ @dataclass
29
+ class AutoencoderTinyOutput(BaseOutput):
30
+ """
31
+ Output of AutoencoderTiny encoding method.
32
+
33
+ Args:
34
+ latents (`torch.Tensor`): Encoded outputs of the `Encoder`.
35
+
36
+ """
37
+
38
+ latents: torch.Tensor
39
+
40
+
41
+ class AutoencoderTiny(ModelMixin, ConfigMixin):
42
+ r"""
43
+ A tiny distilled VAE model for encoding images into latents and decoding latent representations into images.
44
+
45
+ [`AutoencoderTiny`] is a wrapper around the original implementation of `TAESD`.
46
+
47
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for its generic methods implemented for
48
+ all models (such as downloading or saving).
49
+
50
+ Parameters:
51
+ in_channels (`int`, *optional*, defaults to 3): Number of channels in the input image.
52
+ out_channels (`int`, *optional*, defaults to 3): Number of channels in the output.
53
+ encoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
54
+ Tuple of integers representing the number of output channels for each encoder block. The length of the
55
+ tuple should be equal to the number of encoder blocks.
56
+ decoder_block_out_channels (`Tuple[int]`, *optional*, defaults to `(64, 64, 64, 64)`):
57
+ Tuple of integers representing the number of output channels for each decoder block. The length of the
58
+ tuple should be equal to the number of decoder blocks.
59
+ act_fn (`str`, *optional*, defaults to `"relu"`):
60
+ Activation function to be used throughout the model.
61
+ latent_channels (`int`, *optional*, defaults to 4):
62
+ Number of channels in the latent representation. The latent space acts as a compressed representation of
63
+ the input image.
64
+ upsampling_scaling_factor (`int`, *optional*, defaults to 2):
65
+ Scaling factor for upsampling in the decoder. It determines the size of the output image during the
66
+ upsampling process.
67
+ num_encoder_blocks (`Tuple[int]`, *optional*, defaults to `(1, 3, 3, 3)`):
68
+ Tuple of integers representing the number of encoder blocks at each stage of the encoding process. The
69
+ length of the tuple should be equal to the number of stages in the encoder. Each stage has a different
70
+ number of encoder blocks.
71
+ num_decoder_blocks (`Tuple[int]`, *optional*, defaults to `(3, 3, 3, 1)`):
72
+ Tuple of integers representing the number of decoder blocks at each stage of the decoding process. The
73
+ length of the tuple should be equal to the number of stages in the decoder. Each stage has a different
74
+ number of decoder blocks.
75
+ latent_magnitude (`float`, *optional*, defaults to 3.0):
76
+ Magnitude of the latent representation. This parameter scales the latent representation values to control
77
+ the extent of information preservation.
78
+ latent_shift (float, *optional*, defaults to 0.5):
79
+ Shift applied to the latent representation. This parameter controls the center of the latent space.
80
+ scaling_factor (`float`, *optional*, defaults to 1.0):
81
+ The component-wise standard deviation of the trained latent space computed using the first batch of the
82
+ training set. This is used to scale the latent space to have unit variance when training the diffusion
83
+ model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
84
+ diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
85
+ / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
86
+ Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper. For this Autoencoder,
87
+ however, no such scaling factor was used, hence the value of 1.0 as the default.
88
+ force_upcast (`bool`, *optional*, default to `False`):
89
+ If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
90
+ can be fine-tuned / trained to a lower range without losing too much precision, in which case
91
+ `force_upcast` can be set to `False` (see this fp16-friendly
92
+ [AutoEncoder](https://huggingface.co/madebyollin/sdxl-vae-fp16-fix)).
93
+ """
94
+
95
+ _supports_gradient_checkpointing = True
96
+
97
+ @register_to_config
98
+ def __init__(
99
+ self,
100
+ in_channels: int = 3,
101
+ out_channels: int = 3,
102
+ encoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64),
103
+ decoder_block_out_channels: Tuple[int, ...] = (64, 64, 64, 64),
104
+ act_fn: str = "relu",
105
+ latent_channels: int = 4,
106
+ upsampling_scaling_factor: int = 2,
107
+ num_encoder_blocks: Tuple[int, ...] = (1, 3, 3, 3),
108
+ num_decoder_blocks: Tuple[int, ...] = (3, 3, 3, 1),
109
+ latent_magnitude: int = 3,
110
+ latent_shift: float = 0.5,
111
+ force_upcast: bool = False,
112
+ scaling_factor: float = 1.0,
113
+ ):
114
+ super().__init__()
115
+
116
+ if len(encoder_block_out_channels) != len(num_encoder_blocks):
117
+ raise ValueError("`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.")
118
+ if len(decoder_block_out_channels) != len(num_decoder_blocks):
119
+ raise ValueError("`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.")
120
+
121
+ self.encoder = EncoderTiny(
122
+ in_channels=in_channels,
123
+ out_channels=latent_channels,
124
+ num_blocks=num_encoder_blocks,
125
+ block_out_channels=encoder_block_out_channels,
126
+ act_fn=act_fn,
127
+ )
128
+
129
+ self.decoder = DecoderTiny(
130
+ in_channels=latent_channels,
131
+ out_channels=out_channels,
132
+ num_blocks=num_decoder_blocks,
133
+ block_out_channels=decoder_block_out_channels,
134
+ upsampling_scaling_factor=upsampling_scaling_factor,
135
+ act_fn=act_fn,
136
+ )
137
+
138
+ self.latent_magnitude = latent_magnitude
139
+ self.latent_shift = latent_shift
140
+ self.scaling_factor = scaling_factor
141
+
142
+ self.use_slicing = False
143
+ self.use_tiling = False
144
+
145
+ # only relevant if vae tiling is enabled
146
+ self.spatial_scale_factor = 2**out_channels
147
+ self.tile_overlap_factor = 0.125
148
+ self.tile_sample_min_size = 512
149
+ self.tile_latent_min_size = self.tile_sample_min_size // self.spatial_scale_factor
150
+
151
+ self.register_to_config(block_out_channels=decoder_block_out_channels)
152
+ self.register_to_config(force_upcast=False)
153
+
154
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
155
+ if isinstance(module, (EncoderTiny, DecoderTiny)):
156
+ module.gradient_checkpointing = value
157
+
158
+ def scale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
159
+ """raw latents -> [0, 1]"""
160
+ return x.div(2 * self.latent_magnitude).add(self.latent_shift).clamp(0, 1)
161
+
162
+ def unscale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
163
+ """[0, 1] -> raw latents"""
164
+ return x.sub(self.latent_shift).mul(2 * self.latent_magnitude)
165
+
166
+ def enable_slicing(self) -> None:
167
+ r"""
168
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
169
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
170
+ """
171
+ self.use_slicing = True
172
+
173
+ def disable_slicing(self) -> None:
174
+ r"""
175
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
176
+ decoding in one step.
177
+ """
178
+ self.use_slicing = False
179
+
180
+ def enable_tiling(self, use_tiling: bool = True) -> None:
181
+ r"""
182
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
183
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
184
+ processing larger images.
185
+ """
186
+ self.use_tiling = use_tiling
187
+
188
+ def disable_tiling(self) -> None:
189
+ r"""
190
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
191
+ decoding in one step.
192
+ """
193
+ self.enable_tiling(False)
194
+
195
+ def _tiled_encode(self, x: torch.FloatTensor) -> torch.FloatTensor:
196
+ r"""Encode a batch of images using a tiled encoder.
197
+
198
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
199
+ steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
200
+ tiles overlap and are blended together to form a smooth output.
201
+
202
+ Args:
203
+ x (`torch.FloatTensor`): Input batch of images.
204
+
205
+ Returns:
206
+ `torch.FloatTensor`: Encoded batch of images.
207
+ """
208
+ # scale of encoder output relative to input
209
+ sf = self.spatial_scale_factor
210
+ tile_size = self.tile_sample_min_size
211
+
212
+ # number of pixels to blend and to traverse between tile
213
+ blend_size = int(tile_size * self.tile_overlap_factor)
214
+ traverse_size = tile_size - blend_size
215
+
216
+ # tiles index (up/left)
217
+ ti = range(0, x.shape[-2], traverse_size)
218
+ tj = range(0, x.shape[-1], traverse_size)
219
+
220
+ # mask for blending
221
+ blend_masks = torch.stack(
222
+ torch.meshgrid([torch.arange(tile_size / sf) / (blend_size / sf - 1)] * 2, indexing="ij")
223
+ )
224
+ blend_masks = blend_masks.clamp(0, 1).to(x.device)
225
+
226
+ # output array
227
+ out = torch.zeros(x.shape[0], 4, x.shape[-2] // sf, x.shape[-1] // sf, device=x.device)
228
+ for i in ti:
229
+ for j in tj:
230
+ tile_in = x[..., i : i + tile_size, j : j + tile_size]
231
+ # tile result
232
+ tile_out = out[..., i // sf : (i + tile_size) // sf, j // sf : (j + tile_size) // sf]
233
+ tile = self.encoder(tile_in)
234
+ h, w = tile.shape[-2], tile.shape[-1]
235
+ # blend tile result into output
236
+ blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
237
+ blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
238
+ blend_mask = blend_mask_i * blend_mask_j
239
+ tile, blend_mask = tile[..., :h, :w], blend_mask[..., :h, :w]
240
+ tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
241
+ return out
242
+
243
+ def _tiled_decode(self, x: torch.FloatTensor) -> torch.FloatTensor:
244
+ r"""Encode a batch of images using a tiled encoder.
245
+
246
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
247
+ steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
248
+ tiles overlap and are blended together to form a smooth output.
249
+
250
+ Args:
251
+ x (`torch.FloatTensor`): Input batch of images.
252
+
253
+ Returns:
254
+ `torch.FloatTensor`: Encoded batch of images.
255
+ """
256
+ # scale of decoder output relative to input
257
+ sf = self.spatial_scale_factor
258
+ tile_size = self.tile_latent_min_size
259
+
260
+ # number of pixels to blend and to traverse between tiles
261
+ blend_size = int(tile_size * self.tile_overlap_factor)
262
+ traverse_size = tile_size - blend_size
263
+
264
+ # tiles index (up/left)
265
+ ti = range(0, x.shape[-2], traverse_size)
266
+ tj = range(0, x.shape[-1], traverse_size)
267
+
268
+ # mask for blending
269
+ blend_masks = torch.stack(
270
+ torch.meshgrid([torch.arange(tile_size * sf) / (blend_size * sf - 1)] * 2, indexing="ij")
271
+ )
272
+ blend_masks = blend_masks.clamp(0, 1).to(x.device)
273
+
274
+ # output array
275
+ out = torch.zeros(x.shape[0], 3, x.shape[-2] * sf, x.shape[-1] * sf, device=x.device)
276
+ for i in ti:
277
+ for j in tj:
278
+ tile_in = x[..., i : i + tile_size, j : j + tile_size]
279
+ # tile result
280
+ tile_out = out[..., i * sf : (i + tile_size) * sf, j * sf : (j + tile_size) * sf]
281
+ tile = self.decoder(tile_in)
282
+ h, w = tile.shape[-2], tile.shape[-1]
283
+ # blend tile result into output
284
+ blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
285
+ blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
286
+ blend_mask = (blend_mask_i * blend_mask_j)[..., :h, :w]
287
+ tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
288
+ return out
289
+
290
+ @apply_forward_hook
291
+ def encode(
292
+ self, x: torch.FloatTensor, return_dict: bool = True
293
+ ) -> Union[AutoencoderTinyOutput, Tuple[torch.FloatTensor]]:
294
+ if self.use_slicing and x.shape[0] > 1:
295
+ output = [self._tiled_encode(x_slice) if self.use_tiling else self.encoder(x) for x_slice in x.split(1)]
296
+ output = torch.cat(output)
297
+ else:
298
+ output = self._tiled_encode(x) if self.use_tiling else self.encoder(x)
299
+
300
+ if not return_dict:
301
+ return (output,)
302
+
303
+ return AutoencoderTinyOutput(latents=output)
304
+
305
+ @apply_forward_hook
306
+ def decode(
307
+ self, x: torch.FloatTensor, generator: Optional[torch.Generator] = None, return_dict: bool = True
308
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
309
+ if self.use_slicing and x.shape[0] > 1:
310
+ output = [self._tiled_decode(x_slice) if self.use_tiling else self.decoder(x) for x_slice in x.split(1)]
311
+ output = torch.cat(output)
312
+ else:
313
+ output = self._tiled_decode(x) if self.use_tiling else self.decoder(x)
314
+
315
+ if not return_dict:
316
+ return (output,)
317
+
318
+ return DecoderOutput(sample=output)
319
+
320
+ def forward(
321
+ self,
322
+ sample: torch.FloatTensor,
323
+ return_dict: bool = True,
324
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
325
+ r"""
326
+ Args:
327
+ sample (`torch.FloatTensor`): Input sample.
328
+ return_dict (`bool`, *optional*, defaults to `True`):
329
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
330
+ """
331
+ enc = self.encode(sample).latents
332
+
333
+ # scale latents to be in [0, 1], then quantize latents to a byte tensor,
334
+ # as if we were storing the latents in an RGBA uint8 image.
335
+ scaled_enc = self.scale_latents(enc).mul_(255).round_().byte()
336
+
337
+ # unquantize latents back into [0, 1], then unscale latents back to their original range,
338
+ # as if we were loading the latents from an RGBA uint8 image.
339
+ unscaled_enc = self.unscale_latents(scaled_enc / 255.0)
340
+
341
+ dec = self.decode(unscaled_enc)
342
+
343
+ if not return_dict:
344
+ return (dec,)
345
+ return DecoderOutput(sample=dec)
diffusers/models/consistency_decoder_vae.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 dataclasses import dataclass
15
+ from typing import Dict, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from ..configuration_utils import ConfigMixin, register_to_config
22
+ from ..schedulers import ConsistencyDecoderScheduler
23
+ from ..utils import BaseOutput
24
+ from ..utils.accelerate_utils import apply_forward_hook
25
+ from ..utils.torch_utils import randn_tensor
26
+ from .attention_processor import (
27
+ ADDED_KV_ATTENTION_PROCESSORS,
28
+ CROSS_ATTENTION_PROCESSORS,
29
+ AttentionProcessor,
30
+ AttnAddedKVProcessor,
31
+ AttnProcessor,
32
+ )
33
+ from .modeling_utils import ModelMixin
34
+ from .unet_2d import UNet2DModel
35
+ from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
36
+
37
+
38
+ @dataclass
39
+ class ConsistencyDecoderVAEOutput(BaseOutput):
40
+ """
41
+ Output of encoding method.
42
+
43
+ Args:
44
+ latent_dist (`DiagonalGaussianDistribution`):
45
+ Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
46
+ `DiagonalGaussianDistribution` allows for sampling latents from the distribution.
47
+ """
48
+
49
+ latent_dist: "DiagonalGaussianDistribution"
50
+
51
+
52
+ class ConsistencyDecoderVAE(ModelMixin, ConfigMixin):
53
+ r"""
54
+ The consistency decoder used with DALL-E 3.
55
+
56
+ Examples:
57
+ ```py
58
+ >>> import torch
59
+ >>> from diffusers import StableDiffusionPipeline, ConsistencyDecoderVAE
60
+
61
+ >>> vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16)
62
+ >>> pipe = StableDiffusionPipeline.from_pretrained(
63
+ ... "runwayml/stable-diffusion-v1-5", vae=vae, torch_dtype=torch.float16
64
+ ... ).to("cuda")
65
+
66
+ >>> pipe("horse", generator=torch.manual_seed(0)).images
67
+ ```
68
+ """
69
+
70
+ @register_to_config
71
+ def __init__(
72
+ self,
73
+ scaling_factor: float = 0.18215,
74
+ latent_channels: int = 4,
75
+ encoder_act_fn: str = "silu",
76
+ encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
77
+ encoder_double_z: bool = True,
78
+ encoder_down_block_types: Tuple[str, ...] = (
79
+ "DownEncoderBlock2D",
80
+ "DownEncoderBlock2D",
81
+ "DownEncoderBlock2D",
82
+ "DownEncoderBlock2D",
83
+ ),
84
+ encoder_in_channels: int = 3,
85
+ encoder_layers_per_block: int = 2,
86
+ encoder_norm_num_groups: int = 32,
87
+ encoder_out_channels: int = 4,
88
+ decoder_add_attention: bool = False,
89
+ decoder_block_out_channels: Tuple[int, ...] = (320, 640, 1024, 1024),
90
+ decoder_down_block_types: Tuple[str, ...] = (
91
+ "ResnetDownsampleBlock2D",
92
+ "ResnetDownsampleBlock2D",
93
+ "ResnetDownsampleBlock2D",
94
+ "ResnetDownsampleBlock2D",
95
+ ),
96
+ decoder_downsample_padding: int = 1,
97
+ decoder_in_channels: int = 7,
98
+ decoder_layers_per_block: int = 3,
99
+ decoder_norm_eps: float = 1e-05,
100
+ decoder_norm_num_groups: int = 32,
101
+ decoder_num_train_timesteps: int = 1024,
102
+ decoder_out_channels: int = 6,
103
+ decoder_resnet_time_scale_shift: str = "scale_shift",
104
+ decoder_time_embedding_type: str = "learned",
105
+ decoder_up_block_types: Tuple[str, ...] = (
106
+ "ResnetUpsampleBlock2D",
107
+ "ResnetUpsampleBlock2D",
108
+ "ResnetUpsampleBlock2D",
109
+ "ResnetUpsampleBlock2D",
110
+ ),
111
+ ):
112
+ super().__init__()
113
+ self.encoder = Encoder(
114
+ act_fn=encoder_act_fn,
115
+ block_out_channels=encoder_block_out_channels,
116
+ double_z=encoder_double_z,
117
+ down_block_types=encoder_down_block_types,
118
+ in_channels=encoder_in_channels,
119
+ layers_per_block=encoder_layers_per_block,
120
+ norm_num_groups=encoder_norm_num_groups,
121
+ out_channels=encoder_out_channels,
122
+ )
123
+
124
+ self.decoder_unet = UNet2DModel(
125
+ add_attention=decoder_add_attention,
126
+ block_out_channels=decoder_block_out_channels,
127
+ down_block_types=decoder_down_block_types,
128
+ downsample_padding=decoder_downsample_padding,
129
+ in_channels=decoder_in_channels,
130
+ layers_per_block=decoder_layers_per_block,
131
+ norm_eps=decoder_norm_eps,
132
+ norm_num_groups=decoder_norm_num_groups,
133
+ num_train_timesteps=decoder_num_train_timesteps,
134
+ out_channels=decoder_out_channels,
135
+ resnet_time_scale_shift=decoder_resnet_time_scale_shift,
136
+ time_embedding_type=decoder_time_embedding_type,
137
+ up_block_types=decoder_up_block_types,
138
+ )
139
+ self.decoder_scheduler = ConsistencyDecoderScheduler()
140
+ self.register_to_config(block_out_channels=encoder_block_out_channels)
141
+ self.register_to_config(force_upcast=False)
142
+ self.register_buffer(
143
+ "means",
144
+ torch.tensor([0.38862467, 0.02253063, 0.07381133, -0.0171294])[None, :, None, None],
145
+ persistent=False,
146
+ )
147
+ self.register_buffer(
148
+ "stds", torch.tensor([0.9654121, 1.0440036, 0.76147926, 0.77022034])[None, :, None, None], persistent=False
149
+ )
150
+
151
+ self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
152
+
153
+ self.use_slicing = False
154
+ self.use_tiling = False
155
+
156
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_tiling
157
+ def enable_tiling(self, use_tiling: bool = True):
158
+ r"""
159
+ Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
160
+ compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
161
+ processing larger images.
162
+ """
163
+ self.use_tiling = use_tiling
164
+
165
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_tiling
166
+ def disable_tiling(self):
167
+ r"""
168
+ Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
169
+ decoding in one step.
170
+ """
171
+ self.enable_tiling(False)
172
+
173
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.enable_slicing
174
+ def enable_slicing(self):
175
+ r"""
176
+ Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
177
+ compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
178
+ """
179
+ self.use_slicing = True
180
+
181
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.disable_slicing
182
+ def disable_slicing(self):
183
+ r"""
184
+ Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
185
+ decoding in one step.
186
+ """
187
+ self.use_slicing = False
188
+
189
+ @property
190
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
191
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
192
+ r"""
193
+ Returns:
194
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
195
+ indexed by its weight name.
196
+ """
197
+ # set recursively
198
+ processors = {}
199
+
200
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
201
+ if hasattr(module, "get_processor"):
202
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
203
+
204
+ for sub_name, child in module.named_children():
205
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
206
+
207
+ return processors
208
+
209
+ for name, module in self.named_children():
210
+ fn_recursive_add_processors(name, module, processors)
211
+
212
+ return processors
213
+
214
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
215
+ def set_attn_processor(
216
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
217
+ ):
218
+ r"""
219
+ Sets the attention processor to use to compute attention.
220
+
221
+ Parameters:
222
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
223
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
224
+ for **all** `Attention` layers.
225
+
226
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
227
+ processor. This is strongly recommended when setting trainable attention processors.
228
+
229
+ """
230
+ count = len(self.attn_processors.keys())
231
+
232
+ if isinstance(processor, dict) and len(processor) != count:
233
+ raise ValueError(
234
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
235
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
236
+ )
237
+
238
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
239
+ if hasattr(module, "set_processor"):
240
+ if not isinstance(processor, dict):
241
+ module.set_processor(processor, _remove_lora=_remove_lora)
242
+ else:
243
+ module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
244
+
245
+ for sub_name, child in module.named_children():
246
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
247
+
248
+ for name, module in self.named_children():
249
+ fn_recursive_attn_processor(name, module, processor)
250
+
251
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
252
+ def set_default_attn_processor(self):
253
+ """
254
+ Disables custom attention processors and sets the default attention implementation.
255
+ """
256
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
257
+ processor = AttnAddedKVProcessor()
258
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
259
+ processor = AttnProcessor()
260
+ else:
261
+ raise ValueError(
262
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
263
+ )
264
+
265
+ self.set_attn_processor(processor, _remove_lora=True)
266
+
267
+ @apply_forward_hook
268
+ def encode(
269
+ self, x: torch.FloatTensor, return_dict: bool = True
270
+ ) -> Union[ConsistencyDecoderVAEOutput, Tuple[DiagonalGaussianDistribution]]:
271
+ """
272
+ Encode a batch of images into latents.
273
+
274
+ Args:
275
+ x (`torch.FloatTensor`): Input batch of images.
276
+ return_dict (`bool`, *optional*, defaults to `True`):
277
+ Whether to return a [`~models.consistecy_decoder_vae.ConsistencyDecoderOoutput`] instead of a plain
278
+ tuple.
279
+
280
+ Returns:
281
+ The latent representations of the encoded images. If `return_dict` is True, a
282
+ [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned, otherwise a plain `tuple`
283
+ is returned.
284
+ """
285
+ if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
286
+ return self.tiled_encode(x, return_dict=return_dict)
287
+
288
+ if self.use_slicing and x.shape[0] > 1:
289
+ encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
290
+ h = torch.cat(encoded_slices)
291
+ else:
292
+ h = self.encoder(x)
293
+
294
+ moments = self.quant_conv(h)
295
+ posterior = DiagonalGaussianDistribution(moments)
296
+
297
+ if not return_dict:
298
+ return (posterior,)
299
+
300
+ return ConsistencyDecoderVAEOutput(latent_dist=posterior)
301
+
302
+ @apply_forward_hook
303
+ def decode(
304
+ self,
305
+ z: torch.FloatTensor,
306
+ generator: Optional[torch.Generator] = None,
307
+ return_dict: bool = True,
308
+ num_inference_steps: int = 2,
309
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
310
+ z = (z * self.config.scaling_factor - self.means) / self.stds
311
+
312
+ scale_factor = 2 ** (len(self.config.block_out_channels) - 1)
313
+ z = F.interpolate(z, mode="nearest", scale_factor=scale_factor)
314
+
315
+ batch_size, _, height, width = z.shape
316
+
317
+ self.decoder_scheduler.set_timesteps(num_inference_steps, device=self.device)
318
+
319
+ x_t = self.decoder_scheduler.init_noise_sigma * randn_tensor(
320
+ (batch_size, 3, height, width), generator=generator, dtype=z.dtype, device=z.device
321
+ )
322
+
323
+ for t in self.decoder_scheduler.timesteps:
324
+ model_input = torch.concat([self.decoder_scheduler.scale_model_input(x_t, t), z], dim=1)
325
+ model_output = self.decoder_unet(model_input, t).sample[:, :3, :, :]
326
+ prev_sample = self.decoder_scheduler.step(model_output, t, x_t, generator).prev_sample
327
+ x_t = prev_sample
328
+
329
+ x_0 = x_t
330
+
331
+ if not return_dict:
332
+ return (x_0,)
333
+
334
+ return DecoderOutput(sample=x_0)
335
+
336
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_v
337
+ def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
338
+ blend_extent = min(a.shape[2], b.shape[2], blend_extent)
339
+ for y in range(blend_extent):
340
+ b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
341
+ return b
342
+
343
+ # Copied from diffusers.models.autoencoder_kl.AutoencoderKL.blend_h
344
+ def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
345
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
346
+ for x in range(blend_extent):
347
+ b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
348
+ return b
349
+
350
+ def tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True) -> ConsistencyDecoderVAEOutput:
351
+ r"""Encode a batch of images using a tiled encoder.
352
+
353
+ When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
354
+ steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
355
+ different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
356
+ tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
357
+ output, but they should be much less noticeable.
358
+
359
+ Args:
360
+ x (`torch.FloatTensor`): Input batch of images.
361
+ return_dict (`bool`, *optional*, defaults to `True`):
362
+ Whether or not to return a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] instead of a
363
+ plain tuple.
364
+
365
+ Returns:
366
+ [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] or `tuple`:
367
+ If return_dict is True, a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned,
368
+ otherwise a plain `tuple` is returned.
369
+ """
370
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
371
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
372
+ row_limit = self.tile_latent_min_size - blend_extent
373
+
374
+ # Split the image into 512x512 tiles and encode them separately.
375
+ rows = []
376
+ for i in range(0, x.shape[2], overlap_size):
377
+ row = []
378
+ for j in range(0, x.shape[3], overlap_size):
379
+ tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
380
+ tile = self.encoder(tile)
381
+ tile = self.quant_conv(tile)
382
+ row.append(tile)
383
+ rows.append(row)
384
+ result_rows = []
385
+ for i, row in enumerate(rows):
386
+ result_row = []
387
+ for j, tile in enumerate(row):
388
+ # blend the above tile and the left tile
389
+ # to the current tile and add the current tile to the result row
390
+ if i > 0:
391
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
392
+ if j > 0:
393
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
394
+ result_row.append(tile[:, :, :row_limit, :row_limit])
395
+ result_rows.append(torch.cat(result_row, dim=3))
396
+
397
+ moments = torch.cat(result_rows, dim=2)
398
+ posterior = DiagonalGaussianDistribution(moments)
399
+
400
+ if not return_dict:
401
+ return (posterior,)
402
+
403
+ return ConsistencyDecoderVAEOutput(latent_dist=posterior)
404
+
405
+ def forward(
406
+ self,
407
+ sample: torch.FloatTensor,
408
+ sample_posterior: bool = False,
409
+ return_dict: bool = True,
410
+ generator: Optional[torch.Generator] = None,
411
+ ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
412
+ r"""
413
+ Args:
414
+ sample (`torch.FloatTensor`): Input sample.
415
+ sample_posterior (`bool`, *optional*, defaults to `False`):
416
+ Whether to sample from the posterior.
417
+ return_dict (`bool`, *optional*, defaults to `True`):
418
+ Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
419
+ generator (`torch.Generator`, *optional*, defaults to `None`):
420
+ Generator to use for sampling.
421
+
422
+ Returns:
423
+ [`DecoderOutput`] or `tuple`:
424
+ If return_dict is True, a [`DecoderOutput`] is returned, otherwise a plain `tuple` is returned.
425
+ """
426
+ x = sample
427
+ posterior = self.encode(x).latent_dist
428
+ if sample_posterior:
429
+ z = posterior.sample(generator=generator)
430
+ else:
431
+ z = posterior.mode()
432
+ dec = self.decode(z, generator=generator).sample
433
+
434
+ if not return_dict:
435
+ return (dec,)
436
+
437
+ return DecoderOutput(sample=dec)
diffusers/models/controlnet.py ADDED
@@ -0,0 +1,864 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ from ..configuration_utils import ConfigMixin, register_to_config
22
+ from ..loaders import FromOriginalControlnetMixin
23
+ from ..utils import BaseOutput, logging
24
+ from .attention_processor import (
25
+ ADDED_KV_ATTENTION_PROCESSORS,
26
+ CROSS_ATTENTION_PROCESSORS,
27
+ AttentionProcessor,
28
+ AttnAddedKVProcessor,
29
+ AttnProcessor,
30
+ )
31
+ from .embeddings import TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps
32
+ from .modeling_utils import ModelMixin
33
+ from .unet_2d_blocks import CrossAttnDownBlock2D, DownBlock2D, UNetMidBlock2D, UNetMidBlock2DCrossAttn, get_down_block
34
+ from .unet_2d_condition import UNet2DConditionModel
35
+
36
+
37
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
+
39
+
40
+ @dataclass
41
+ class ControlNetOutput(BaseOutput):
42
+ """
43
+ The output of [`ControlNetModel`].
44
+
45
+ Args:
46
+ down_block_res_samples (`tuple[torch.Tensor]`):
47
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
48
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
49
+ used to condition the original UNet's downsampling activations.
50
+ mid_down_block_re_sample (`torch.Tensor`):
51
+ The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
52
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
53
+ Output can be used to condition the original UNet's middle block activation.
54
+ """
55
+
56
+ down_block_res_samples: Tuple[torch.Tensor]
57
+ mid_block_res_sample: torch.Tensor
58
+
59
+
60
+ class ControlNetConditioningEmbedding(nn.Module):
61
+ """
62
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
63
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
64
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
65
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
66
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
67
+ model) to encode image-space conditions ... into feature maps ..."
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ conditioning_embedding_channels: int,
73
+ conditioning_channels: int = 3,
74
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
75
+ ):
76
+ super().__init__()
77
+
78
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
79
+
80
+ self.blocks = nn.ModuleList([])
81
+
82
+ for i in range(len(block_out_channels) - 1):
83
+ channel_in = block_out_channels[i]
84
+ channel_out = block_out_channels[i + 1]
85
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
86
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
87
+
88
+ self.conv_out = zero_module(
89
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
90
+ )
91
+
92
+ def forward(self, conditioning):
93
+ embedding = self.conv_in(conditioning)
94
+ embedding = F.silu(embedding)
95
+
96
+ for block in self.blocks:
97
+ embedding = block(embedding)
98
+ embedding = F.silu(embedding)
99
+
100
+ embedding = self.conv_out(embedding)
101
+
102
+ return embedding
103
+
104
+
105
+ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlnetMixin):
106
+ """
107
+ A ControlNet model.
108
+
109
+ Args:
110
+ in_channels (`int`, defaults to 4):
111
+ The number of channels in the input sample.
112
+ flip_sin_to_cos (`bool`, defaults to `True`):
113
+ Whether to flip the sin to cos in the time embedding.
114
+ freq_shift (`int`, defaults to 0):
115
+ The frequency shift to apply to the time embedding.
116
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
117
+ The tuple of downsample blocks to use.
118
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
119
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
120
+ The tuple of output channels for each block.
121
+ layers_per_block (`int`, defaults to 2):
122
+ The number of layers per block.
123
+ downsample_padding (`int`, defaults to 1):
124
+ The padding to use for the downsampling convolution.
125
+ mid_block_scale_factor (`float`, defaults to 1):
126
+ The scale factor to use for the mid block.
127
+ act_fn (`str`, defaults to "silu"):
128
+ The activation function to use.
129
+ norm_num_groups (`int`, *optional*, defaults to 32):
130
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
131
+ in post-processing.
132
+ norm_eps (`float`, defaults to 1e-5):
133
+ The epsilon to use for the normalization.
134
+ cross_attention_dim (`int`, defaults to 1280):
135
+ The dimension of the cross attention features.
136
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
137
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
138
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
139
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
140
+ encoder_hid_dim (`int`, *optional*, defaults to None):
141
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
142
+ dimension to `cross_attention_dim`.
143
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
144
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
145
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
146
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
147
+ The dimension of the attention heads.
148
+ use_linear_projection (`bool`, defaults to `False`):
149
+ class_embed_type (`str`, *optional*, defaults to `None`):
150
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
151
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
152
+ addition_embed_type (`str`, *optional*, defaults to `None`):
153
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
154
+ "text". "text" will use the `TextTimeEmbedding` layer.
155
+ num_class_embeds (`int`, *optional*, defaults to 0):
156
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
157
+ class conditioning with `class_embed_type` equal to `None`.
158
+ upcast_attention (`bool`, defaults to `False`):
159
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
160
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
161
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
162
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
163
+ `class_embed_type="projection"`.
164
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
165
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
166
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
167
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
168
+ global_pool_conditions (`bool`, defaults to `False`):
169
+ TODO(Patrick) - unused parameter.
170
+ addition_embed_type_num_heads (`int`, defaults to 64):
171
+ The number of heads to use for the `TextTimeEmbedding` layer.
172
+ """
173
+
174
+ _supports_gradient_checkpointing = True
175
+
176
+ @register_to_config
177
+ def __init__(
178
+ self,
179
+ in_channels: int = 4,
180
+ conditioning_channels: int = 3,
181
+ flip_sin_to_cos: bool = True,
182
+ freq_shift: int = 0,
183
+ down_block_types: Tuple[str, ...] = (
184
+ "CrossAttnDownBlock2D",
185
+ "CrossAttnDownBlock2D",
186
+ "CrossAttnDownBlock2D",
187
+ "DownBlock2D",
188
+ ),
189
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
190
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
191
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
192
+ layers_per_block: int = 2,
193
+ downsample_padding: int = 1,
194
+ mid_block_scale_factor: float = 1,
195
+ act_fn: str = "silu",
196
+ norm_num_groups: Optional[int] = 32,
197
+ norm_eps: float = 1e-5,
198
+ cross_attention_dim: int = 1280,
199
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
200
+ encoder_hid_dim: Optional[int] = None,
201
+ encoder_hid_dim_type: Optional[str] = None,
202
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
203
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
204
+ use_linear_projection: bool = False,
205
+ class_embed_type: Optional[str] = None,
206
+ addition_embed_type: Optional[str] = None,
207
+ addition_time_embed_dim: Optional[int] = None,
208
+ num_class_embeds: Optional[int] = None,
209
+ upcast_attention: bool = False,
210
+ resnet_time_scale_shift: str = "default",
211
+ projection_class_embeddings_input_dim: Optional[int] = None,
212
+ controlnet_conditioning_channel_order: str = "rgb",
213
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
214
+ global_pool_conditions: bool = False,
215
+ addition_embed_type_num_heads: int = 64,
216
+ ):
217
+ super().__init__()
218
+
219
+ # If `num_attention_heads` is not defined (which is the case for most models)
220
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
221
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
222
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
223
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
224
+ # which is why we correct for the naming here.
225
+ num_attention_heads = num_attention_heads or attention_head_dim
226
+
227
+ # Check inputs
228
+ if len(block_out_channels) != len(down_block_types):
229
+ raise ValueError(
230
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
231
+ )
232
+
233
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
234
+ raise ValueError(
235
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
236
+ )
237
+
238
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
239
+ raise ValueError(
240
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
241
+ )
242
+
243
+ if isinstance(transformer_layers_per_block, int):
244
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
245
+
246
+ # input
247
+ conv_in_kernel = 3
248
+ conv_in_padding = (conv_in_kernel - 1) // 2
249
+ self.conv_in = nn.Conv2d(
250
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
251
+ )
252
+
253
+ # time
254
+ time_embed_dim = block_out_channels[0] * 4
255
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
256
+ timestep_input_dim = block_out_channels[0]
257
+ self.time_embedding = TimestepEmbedding(
258
+ timestep_input_dim,
259
+ time_embed_dim,
260
+ act_fn=act_fn,
261
+ )
262
+
263
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
264
+ encoder_hid_dim_type = "text_proj"
265
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
266
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
267
+
268
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
269
+ raise ValueError(
270
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
271
+ )
272
+
273
+ if encoder_hid_dim_type == "text_proj":
274
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
275
+ elif encoder_hid_dim_type == "text_image_proj":
276
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
277
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
278
+ # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
279
+ self.encoder_hid_proj = TextImageProjection(
280
+ text_embed_dim=encoder_hid_dim,
281
+ image_embed_dim=cross_attention_dim,
282
+ cross_attention_dim=cross_attention_dim,
283
+ )
284
+
285
+ elif encoder_hid_dim_type is not None:
286
+ raise ValueError(
287
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
288
+ )
289
+ else:
290
+ self.encoder_hid_proj = None
291
+
292
+ # class embedding
293
+ if class_embed_type is None and num_class_embeds is not None:
294
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
295
+ elif class_embed_type == "timestep":
296
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
297
+ elif class_embed_type == "identity":
298
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
299
+ elif class_embed_type == "projection":
300
+ if projection_class_embeddings_input_dim is None:
301
+ raise ValueError(
302
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
303
+ )
304
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
305
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
306
+ # 2. it projects from an arbitrary input dimension.
307
+ #
308
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
309
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
310
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
311
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
312
+ else:
313
+ self.class_embedding = None
314
+
315
+ if addition_embed_type == "text":
316
+ if encoder_hid_dim is not None:
317
+ text_time_embedding_from_dim = encoder_hid_dim
318
+ else:
319
+ text_time_embedding_from_dim = cross_attention_dim
320
+
321
+ self.add_embedding = TextTimeEmbedding(
322
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
323
+ )
324
+ elif addition_embed_type == "text_image":
325
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
326
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
327
+ # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
328
+ self.add_embedding = TextImageTimeEmbedding(
329
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
330
+ )
331
+ elif addition_embed_type == "text_time":
332
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
333
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
334
+
335
+ elif addition_embed_type is not None:
336
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
337
+
338
+ # control net conditioning embedding
339
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
340
+ conditioning_embedding_channels=block_out_channels[0],
341
+ block_out_channels=conditioning_embedding_out_channels,
342
+ conditioning_channels=conditioning_channels,
343
+ )
344
+
345
+ self.down_blocks = nn.ModuleList([])
346
+ self.controlnet_down_blocks = nn.ModuleList([])
347
+
348
+ if isinstance(only_cross_attention, bool):
349
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
350
+
351
+ if isinstance(attention_head_dim, int):
352
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
353
+
354
+ if isinstance(num_attention_heads, int):
355
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
356
+
357
+ # down
358
+ output_channel = block_out_channels[0]
359
+
360
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
361
+ controlnet_block = zero_module(controlnet_block)
362
+ self.controlnet_down_blocks.append(controlnet_block)
363
+
364
+ for i, down_block_type in enumerate(down_block_types):
365
+ input_channel = output_channel
366
+ output_channel = block_out_channels[i]
367
+ is_final_block = i == len(block_out_channels) - 1
368
+
369
+ down_block = get_down_block(
370
+ down_block_type,
371
+ num_layers=layers_per_block,
372
+ transformer_layers_per_block=transformer_layers_per_block[i],
373
+ in_channels=input_channel,
374
+ out_channels=output_channel,
375
+ temb_channels=time_embed_dim,
376
+ add_downsample=not is_final_block,
377
+ resnet_eps=norm_eps,
378
+ resnet_act_fn=act_fn,
379
+ resnet_groups=norm_num_groups,
380
+ cross_attention_dim=cross_attention_dim,
381
+ num_attention_heads=num_attention_heads[i],
382
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
383
+ downsample_padding=downsample_padding,
384
+ use_linear_projection=use_linear_projection,
385
+ only_cross_attention=only_cross_attention[i],
386
+ upcast_attention=upcast_attention,
387
+ resnet_time_scale_shift=resnet_time_scale_shift,
388
+ )
389
+ self.down_blocks.append(down_block)
390
+
391
+ for _ in range(layers_per_block):
392
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
393
+ controlnet_block = zero_module(controlnet_block)
394
+ self.controlnet_down_blocks.append(controlnet_block)
395
+
396
+ if not is_final_block:
397
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
398
+ controlnet_block = zero_module(controlnet_block)
399
+ self.controlnet_down_blocks.append(controlnet_block)
400
+
401
+ # mid
402
+ mid_block_channel = block_out_channels[-1]
403
+
404
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
405
+ controlnet_block = zero_module(controlnet_block)
406
+ self.controlnet_mid_block = controlnet_block
407
+
408
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
409
+ self.mid_block = UNetMidBlock2DCrossAttn(
410
+ transformer_layers_per_block=transformer_layers_per_block[-1],
411
+ in_channels=mid_block_channel,
412
+ temb_channels=time_embed_dim,
413
+ resnet_eps=norm_eps,
414
+ resnet_act_fn=act_fn,
415
+ output_scale_factor=mid_block_scale_factor,
416
+ resnet_time_scale_shift=resnet_time_scale_shift,
417
+ cross_attention_dim=cross_attention_dim,
418
+ num_attention_heads=num_attention_heads[-1],
419
+ resnet_groups=norm_num_groups,
420
+ use_linear_projection=use_linear_projection,
421
+ upcast_attention=upcast_attention,
422
+ )
423
+ elif mid_block_type == "UNetMidBlock2D":
424
+ self.mid_block = UNetMidBlock2D(
425
+ in_channels=block_out_channels[-1],
426
+ temb_channels=time_embed_dim,
427
+ num_layers=0,
428
+ resnet_eps=norm_eps,
429
+ resnet_act_fn=act_fn,
430
+ output_scale_factor=mid_block_scale_factor,
431
+ resnet_groups=norm_num_groups,
432
+ resnet_time_scale_shift=resnet_time_scale_shift,
433
+ add_attention=False,
434
+ )
435
+ else:
436
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
437
+
438
+ @classmethod
439
+ def from_unet(
440
+ cls,
441
+ unet: UNet2DConditionModel,
442
+ controlnet_conditioning_channel_order: str = "rgb",
443
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
444
+ load_weights_from_unet: bool = True,
445
+ conditioning_channels: int = 3,
446
+ ):
447
+ r"""
448
+ Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
449
+
450
+ Parameters:
451
+ unet (`UNet2DConditionModel`):
452
+ The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
453
+ where applicable.
454
+ """
455
+ transformer_layers_per_block = (
456
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
457
+ )
458
+ encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
459
+ encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
460
+ addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
461
+ addition_time_embed_dim = (
462
+ unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
463
+ )
464
+
465
+ controlnet = cls(
466
+ encoder_hid_dim=encoder_hid_dim,
467
+ encoder_hid_dim_type=encoder_hid_dim_type,
468
+ addition_embed_type=addition_embed_type,
469
+ addition_time_embed_dim=addition_time_embed_dim,
470
+ transformer_layers_per_block=transformer_layers_per_block,
471
+ in_channels=unet.config.in_channels,
472
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
473
+ freq_shift=unet.config.freq_shift,
474
+ down_block_types=unet.config.down_block_types,
475
+ only_cross_attention=unet.config.only_cross_attention,
476
+ block_out_channels=unet.config.block_out_channels,
477
+ layers_per_block=unet.config.layers_per_block,
478
+ downsample_padding=unet.config.downsample_padding,
479
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
480
+ act_fn=unet.config.act_fn,
481
+ norm_num_groups=unet.config.norm_num_groups,
482
+ norm_eps=unet.config.norm_eps,
483
+ cross_attention_dim=unet.config.cross_attention_dim,
484
+ attention_head_dim=unet.config.attention_head_dim,
485
+ num_attention_heads=unet.config.num_attention_heads,
486
+ use_linear_projection=unet.config.use_linear_projection,
487
+ class_embed_type=unet.config.class_embed_type,
488
+ num_class_embeds=unet.config.num_class_embeds,
489
+ upcast_attention=unet.config.upcast_attention,
490
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
491
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
492
+ mid_block_type=unet.config.mid_block_type,
493
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
494
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
495
+ conditioning_channels=conditioning_channels,
496
+ )
497
+
498
+ if load_weights_from_unet:
499
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
500
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
501
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
502
+
503
+ if controlnet.class_embedding:
504
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
505
+
506
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
507
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
508
+
509
+ return controlnet
510
+
511
+ @property
512
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
513
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
514
+ r"""
515
+ Returns:
516
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
517
+ indexed by its weight name.
518
+ """
519
+ # set recursively
520
+ processors = {}
521
+
522
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
523
+ if hasattr(module, "get_processor"):
524
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
525
+
526
+ for sub_name, child in module.named_children():
527
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
528
+
529
+ return processors
530
+
531
+ for name, module in self.named_children():
532
+ fn_recursive_add_processors(name, module, processors)
533
+
534
+ return processors
535
+
536
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
537
+ def set_attn_processor(
538
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
539
+ ):
540
+ r"""
541
+ Sets the attention processor to use to compute attention.
542
+
543
+ Parameters:
544
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
545
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
546
+ for **all** `Attention` layers.
547
+
548
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
549
+ processor. This is strongly recommended when setting trainable attention processors.
550
+
551
+ """
552
+ count = len(self.attn_processors.keys())
553
+
554
+ if isinstance(processor, dict) and len(processor) != count:
555
+ raise ValueError(
556
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
557
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
558
+ )
559
+
560
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
561
+ if hasattr(module, "set_processor"):
562
+ if not isinstance(processor, dict):
563
+ module.set_processor(processor, _remove_lora=_remove_lora)
564
+ else:
565
+ module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
566
+
567
+ for sub_name, child in module.named_children():
568
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
569
+
570
+ for name, module in self.named_children():
571
+ fn_recursive_attn_processor(name, module, processor)
572
+
573
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
574
+ def set_default_attn_processor(self):
575
+ """
576
+ Disables custom attention processors and sets the default attention implementation.
577
+ """
578
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
579
+ processor = AttnAddedKVProcessor()
580
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
581
+ processor = AttnProcessor()
582
+ else:
583
+ raise ValueError(
584
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
585
+ )
586
+
587
+ self.set_attn_processor(processor, _remove_lora=True)
588
+
589
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
590
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
591
+ r"""
592
+ Enable sliced attention computation.
593
+
594
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
595
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
596
+
597
+ Args:
598
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
599
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
600
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
601
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
602
+ must be a multiple of `slice_size`.
603
+ """
604
+ sliceable_head_dims = []
605
+
606
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
607
+ if hasattr(module, "set_attention_slice"):
608
+ sliceable_head_dims.append(module.sliceable_head_dim)
609
+
610
+ for child in module.children():
611
+ fn_recursive_retrieve_sliceable_dims(child)
612
+
613
+ # retrieve number of attention layers
614
+ for module in self.children():
615
+ fn_recursive_retrieve_sliceable_dims(module)
616
+
617
+ num_sliceable_layers = len(sliceable_head_dims)
618
+
619
+ if slice_size == "auto":
620
+ # half the attention head size is usually a good trade-off between
621
+ # speed and memory
622
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
623
+ elif slice_size == "max":
624
+ # make smallest slice possible
625
+ slice_size = num_sliceable_layers * [1]
626
+
627
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
628
+
629
+ if len(slice_size) != len(sliceable_head_dims):
630
+ raise ValueError(
631
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
632
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
633
+ )
634
+
635
+ for i in range(len(slice_size)):
636
+ size = slice_size[i]
637
+ dim = sliceable_head_dims[i]
638
+ if size is not None and size > dim:
639
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
640
+
641
+ # Recursively walk through all the children.
642
+ # Any children which exposes the set_attention_slice method
643
+ # gets the message
644
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
645
+ if hasattr(module, "set_attention_slice"):
646
+ module.set_attention_slice(slice_size.pop())
647
+
648
+ for child in module.children():
649
+ fn_recursive_set_attention_slice(child, slice_size)
650
+
651
+ reversed_slice_size = list(reversed(slice_size))
652
+ for module in self.children():
653
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
654
+
655
+ def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
656
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
657
+ module.gradient_checkpointing = value
658
+
659
+ def forward(
660
+ self,
661
+ sample: torch.FloatTensor,
662
+ timestep: Union[torch.Tensor, float, int],
663
+ encoder_hidden_states: torch.Tensor,
664
+ controlnet_cond: torch.FloatTensor,
665
+ conditioning_scale: float = 1.0,
666
+ class_labels: Optional[torch.Tensor] = None,
667
+ timestep_cond: Optional[torch.Tensor] = None,
668
+ attention_mask: Optional[torch.Tensor] = None,
669
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
670
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
671
+ guess_mode: bool = False,
672
+ return_dict: bool = True,
673
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
674
+ """
675
+ The [`ControlNetModel`] forward method.
676
+
677
+ Args:
678
+ sample (`torch.FloatTensor`):
679
+ The noisy input tensor.
680
+ timestep (`Union[torch.Tensor, float, int]`):
681
+ The number of timesteps to denoise an input.
682
+ encoder_hidden_states (`torch.Tensor`):
683
+ The encoder hidden states.
684
+ controlnet_cond (`torch.FloatTensor`):
685
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
686
+ conditioning_scale (`float`, defaults to `1.0`):
687
+ The scale factor for ControlNet outputs.
688
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
689
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
690
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
691
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
692
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
693
+ embeddings.
694
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
695
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
696
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
697
+ negative values to the attention scores corresponding to "discard" tokens.
698
+ added_cond_kwargs (`dict`):
699
+ Additional conditions for the Stable Diffusion XL UNet.
700
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
701
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
702
+ guess_mode (`bool`, defaults to `False`):
703
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
704
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
705
+ return_dict (`bool`, defaults to `True`):
706
+ Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
707
+
708
+ Returns:
709
+ [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
710
+ If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
711
+ returned where the first element is the sample tensor.
712
+ """
713
+ # check channel order
714
+ channel_order = self.config.controlnet_conditioning_channel_order
715
+
716
+ if channel_order == "rgb":
717
+ # in rgb order by default
718
+ ...
719
+ elif channel_order == "bgr":
720
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
721
+ else:
722
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
723
+
724
+ # prepare attention_mask
725
+ if attention_mask is not None:
726
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
727
+ attention_mask = attention_mask.unsqueeze(1)
728
+
729
+ # 1. time
730
+ timesteps = timestep
731
+ if not torch.is_tensor(timesteps):
732
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
733
+ # This would be a good case for the `match` statement (Python 3.10+)
734
+ is_mps = sample.device.type == "mps"
735
+ if isinstance(timestep, float):
736
+ dtype = torch.float32 if is_mps else torch.float64
737
+ else:
738
+ dtype = torch.int32 if is_mps else torch.int64
739
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
740
+ elif len(timesteps.shape) == 0:
741
+ timesteps = timesteps[None].to(sample.device)
742
+
743
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
744
+ timesteps = timesteps.expand(sample.shape[0])
745
+
746
+ t_emb = self.time_proj(timesteps)
747
+
748
+ # timesteps does not contain any weights and will always return f32 tensors
749
+ # but time_embedding might actually be running in fp16. so we need to cast here.
750
+ # there might be better ways to encapsulate this.
751
+ t_emb = t_emb.to(dtype=sample.dtype)
752
+
753
+ emb = self.time_embedding(t_emb, timestep_cond)
754
+ aug_emb = None
755
+
756
+ if self.class_embedding is not None:
757
+ if class_labels is None:
758
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
759
+
760
+ if self.config.class_embed_type == "timestep":
761
+ class_labels = self.time_proj(class_labels)
762
+
763
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
764
+ emb = emb + class_emb
765
+
766
+ if self.config.addition_embed_type is not None:
767
+ if self.config.addition_embed_type == "text":
768
+ aug_emb = self.add_embedding(encoder_hidden_states)
769
+
770
+ elif self.config.addition_embed_type == "text_time":
771
+ if "text_embeds" not in added_cond_kwargs:
772
+ raise ValueError(
773
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
774
+ )
775
+ text_embeds = added_cond_kwargs.get("text_embeds")
776
+ if "time_ids" not in added_cond_kwargs:
777
+ raise ValueError(
778
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
779
+ )
780
+ time_ids = added_cond_kwargs.get("time_ids")
781
+ time_embeds = self.add_time_proj(time_ids.flatten())
782
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
783
+
784
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
785
+ add_embeds = add_embeds.to(emb.dtype)
786
+ aug_emb = self.add_embedding(add_embeds)
787
+
788
+ emb = emb + aug_emb if aug_emb is not None else emb
789
+
790
+ # 2. pre-process
791
+ sample = self.conv_in(sample)
792
+
793
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
794
+ sample = sample + controlnet_cond
795
+
796
+ # 3. down
797
+ down_block_res_samples = (sample,)
798
+ for downsample_block in self.down_blocks:
799
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
800
+ sample, res_samples = downsample_block(
801
+ hidden_states=sample,
802
+ temb=emb,
803
+ encoder_hidden_states=encoder_hidden_states,
804
+ attention_mask=attention_mask,
805
+ cross_attention_kwargs=cross_attention_kwargs,
806
+ )
807
+ else:
808
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
809
+
810
+ down_block_res_samples += res_samples
811
+
812
+ # 4. mid
813
+ if self.mid_block is not None:
814
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
815
+ sample = self.mid_block(
816
+ sample,
817
+ emb,
818
+ encoder_hidden_states=encoder_hidden_states,
819
+ attention_mask=attention_mask,
820
+ cross_attention_kwargs=cross_attention_kwargs,
821
+ )
822
+ else:
823
+ sample = self.mid_block(sample, emb)
824
+
825
+ # 5. Control net blocks
826
+
827
+ controlnet_down_block_res_samples = ()
828
+
829
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
830
+ down_block_res_sample = controlnet_block(down_block_res_sample)
831
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
832
+
833
+ down_block_res_samples = controlnet_down_block_res_samples
834
+
835
+ mid_block_res_sample = self.controlnet_mid_block(sample)
836
+
837
+ # 6. scaling
838
+ if guess_mode and not self.config.global_pool_conditions:
839
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
840
+ scales = scales * conditioning_scale
841
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
842
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
843
+ else:
844
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
845
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
846
+
847
+ if self.config.global_pool_conditions:
848
+ down_block_res_samples = [
849
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
850
+ ]
851
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
852
+
853
+ if not return_dict:
854
+ return (down_block_res_samples, mid_block_res_sample)
855
+
856
+ return ControlNetOutput(
857
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
858
+ )
859
+
860
+
861
+ def zero_module(module):
862
+ for p in module.parameters():
863
+ nn.init.zeros_(p)
864
+ return module
diffusers/models/controlnet_flax.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 Optional, Tuple, Union
15
+
16
+ import flax
17
+ import flax.linen as nn
18
+ import jax
19
+ import jax.numpy as jnp
20
+ from flax.core.frozen_dict import FrozenDict
21
+
22
+ from ..configuration_utils import ConfigMixin, flax_register_to_config
23
+ from ..utils import BaseOutput
24
+ from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
25
+ from .modeling_flax_utils import FlaxModelMixin
26
+ from .unet_2d_blocks_flax import (
27
+ FlaxCrossAttnDownBlock2D,
28
+ FlaxDownBlock2D,
29
+ FlaxUNetMidBlock2DCrossAttn,
30
+ )
31
+
32
+
33
+ @flax.struct.dataclass
34
+ class FlaxControlNetOutput(BaseOutput):
35
+ """
36
+ The output of [`FlaxControlNetModel`].
37
+
38
+ Args:
39
+ down_block_res_samples (`jnp.ndarray`):
40
+ mid_block_res_sample (`jnp.ndarray`):
41
+ """
42
+
43
+ down_block_res_samples: jnp.ndarray
44
+ mid_block_res_sample: jnp.ndarray
45
+
46
+
47
+ class FlaxControlNetConditioningEmbedding(nn.Module):
48
+ conditioning_embedding_channels: int
49
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
50
+ dtype: jnp.dtype = jnp.float32
51
+
52
+ def setup(self) -> None:
53
+ self.conv_in = nn.Conv(
54
+ self.block_out_channels[0],
55
+ kernel_size=(3, 3),
56
+ padding=((1, 1), (1, 1)),
57
+ dtype=self.dtype,
58
+ )
59
+
60
+ blocks = []
61
+ for i in range(len(self.block_out_channels) - 1):
62
+ channel_in = self.block_out_channels[i]
63
+ channel_out = self.block_out_channels[i + 1]
64
+ conv1 = nn.Conv(
65
+ channel_in,
66
+ kernel_size=(3, 3),
67
+ padding=((1, 1), (1, 1)),
68
+ dtype=self.dtype,
69
+ )
70
+ blocks.append(conv1)
71
+ conv2 = nn.Conv(
72
+ channel_out,
73
+ kernel_size=(3, 3),
74
+ strides=(2, 2),
75
+ padding=((1, 1), (1, 1)),
76
+ dtype=self.dtype,
77
+ )
78
+ blocks.append(conv2)
79
+ self.blocks = blocks
80
+
81
+ self.conv_out = nn.Conv(
82
+ self.conditioning_embedding_channels,
83
+ kernel_size=(3, 3),
84
+ padding=((1, 1), (1, 1)),
85
+ kernel_init=nn.initializers.zeros_init(),
86
+ bias_init=nn.initializers.zeros_init(),
87
+ dtype=self.dtype,
88
+ )
89
+
90
+ def __call__(self, conditioning: jnp.ndarray) -> jnp.ndarray:
91
+ embedding = self.conv_in(conditioning)
92
+ embedding = nn.silu(embedding)
93
+
94
+ for block in self.blocks:
95
+ embedding = block(embedding)
96
+ embedding = nn.silu(embedding)
97
+
98
+ embedding = self.conv_out(embedding)
99
+
100
+ return embedding
101
+
102
+
103
+ @flax_register_to_config
104
+ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
105
+ r"""
106
+ A ControlNet model.
107
+
108
+ This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for it’s generic methods
109
+ implemented for all models (such as downloading or saving).
110
+
111
+ This model is also a Flax Linen [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module)
112
+ subclass. Use it as a regular Flax Linen module and refer to the Flax documentation for all matters related to its
113
+ general usage and behavior.
114
+
115
+ Inherent JAX features such as the following are supported:
116
+
117
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
118
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
119
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
120
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
121
+
122
+ Parameters:
123
+ sample_size (`int`, *optional*):
124
+ The size of the input sample.
125
+ in_channels (`int`, *optional*, defaults to 4):
126
+ The number of channels in the input sample.
127
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D")`):
128
+ The tuple of downsample blocks to use.
129
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
130
+ The tuple of output channels for each block.
131
+ layers_per_block (`int`, *optional*, defaults to 2):
132
+ The number of layers per block.
133
+ attention_head_dim (`int` or `Tuple[int]`, *optional*, defaults to 8):
134
+ The dimension of the attention heads.
135
+ num_attention_heads (`int` or `Tuple[int]`, *optional*):
136
+ The number of attention heads.
137
+ cross_attention_dim (`int`, *optional*, defaults to 768):
138
+ The dimension of the cross attention features.
139
+ dropout (`float`, *optional*, defaults to 0):
140
+ Dropout probability for down, up and bottleneck blocks.
141
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
142
+ Whether to flip the sin to cos in the time embedding.
143
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
144
+ controlnet_conditioning_channel_order (`str`, *optional*, defaults to `rgb`):
145
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
146
+ conditioning_embedding_out_channels (`tuple`, *optional*, defaults to `(16, 32, 96, 256)`):
147
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
148
+ """
149
+
150
+ sample_size: int = 32
151
+ in_channels: int = 4
152
+ down_block_types: Tuple[str, ...] = (
153
+ "CrossAttnDownBlock2D",
154
+ "CrossAttnDownBlock2D",
155
+ "CrossAttnDownBlock2D",
156
+ "DownBlock2D",
157
+ )
158
+ only_cross_attention: Union[bool, Tuple[bool, ...]] = False
159
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280)
160
+ layers_per_block: int = 2
161
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8
162
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None
163
+ cross_attention_dim: int = 1280
164
+ dropout: float = 0.0
165
+ use_linear_projection: bool = False
166
+ dtype: jnp.dtype = jnp.float32
167
+ flip_sin_to_cos: bool = True
168
+ freq_shift: int = 0
169
+ controlnet_conditioning_channel_order: str = "rgb"
170
+ conditioning_embedding_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
171
+
172
+ def init_weights(self, rng: jax.Array) -> FrozenDict:
173
+ # init input tensors
174
+ sample_shape = (1, self.in_channels, self.sample_size, self.sample_size)
175
+ sample = jnp.zeros(sample_shape, dtype=jnp.float32)
176
+ timesteps = jnp.ones((1,), dtype=jnp.int32)
177
+ encoder_hidden_states = jnp.zeros((1, 1, self.cross_attention_dim), dtype=jnp.float32)
178
+ controlnet_cond_shape = (1, 3, self.sample_size * 8, self.sample_size * 8)
179
+ controlnet_cond = jnp.zeros(controlnet_cond_shape, dtype=jnp.float32)
180
+
181
+ params_rng, dropout_rng = jax.random.split(rng)
182
+ rngs = {"params": params_rng, "dropout": dropout_rng}
183
+
184
+ return self.init(rngs, sample, timesteps, encoder_hidden_states, controlnet_cond)["params"]
185
+
186
+ def setup(self) -> None:
187
+ block_out_channels = self.block_out_channels
188
+ time_embed_dim = block_out_channels[0] * 4
189
+
190
+ # If `num_attention_heads` is not defined (which is the case for most models)
191
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
192
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
193
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
194
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
195
+ # which is why we correct for the naming here.
196
+ num_attention_heads = self.num_attention_heads or self.attention_head_dim
197
+
198
+ # input
199
+ self.conv_in = nn.Conv(
200
+ block_out_channels[0],
201
+ kernel_size=(3, 3),
202
+ strides=(1, 1),
203
+ padding=((1, 1), (1, 1)),
204
+ dtype=self.dtype,
205
+ )
206
+
207
+ # time
208
+ self.time_proj = FlaxTimesteps(
209
+ block_out_channels[0], flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.config.freq_shift
210
+ )
211
+ self.time_embedding = FlaxTimestepEmbedding(time_embed_dim, dtype=self.dtype)
212
+
213
+ self.controlnet_cond_embedding = FlaxControlNetConditioningEmbedding(
214
+ conditioning_embedding_channels=block_out_channels[0],
215
+ block_out_channels=self.conditioning_embedding_out_channels,
216
+ )
217
+
218
+ only_cross_attention = self.only_cross_attention
219
+ if isinstance(only_cross_attention, bool):
220
+ only_cross_attention = (only_cross_attention,) * len(self.down_block_types)
221
+
222
+ if isinstance(num_attention_heads, int):
223
+ num_attention_heads = (num_attention_heads,) * len(self.down_block_types)
224
+
225
+ # down
226
+ down_blocks = []
227
+ controlnet_down_blocks = []
228
+
229
+ output_channel = block_out_channels[0]
230
+
231
+ controlnet_block = nn.Conv(
232
+ output_channel,
233
+ kernel_size=(1, 1),
234
+ padding="VALID",
235
+ kernel_init=nn.initializers.zeros_init(),
236
+ bias_init=nn.initializers.zeros_init(),
237
+ dtype=self.dtype,
238
+ )
239
+ controlnet_down_blocks.append(controlnet_block)
240
+
241
+ for i, down_block_type in enumerate(self.down_block_types):
242
+ input_channel = output_channel
243
+ output_channel = block_out_channels[i]
244
+ is_final_block = i == len(block_out_channels) - 1
245
+
246
+ if down_block_type == "CrossAttnDownBlock2D":
247
+ down_block = FlaxCrossAttnDownBlock2D(
248
+ in_channels=input_channel,
249
+ out_channels=output_channel,
250
+ dropout=self.dropout,
251
+ num_layers=self.layers_per_block,
252
+ num_attention_heads=num_attention_heads[i],
253
+ add_downsample=not is_final_block,
254
+ use_linear_projection=self.use_linear_projection,
255
+ only_cross_attention=only_cross_attention[i],
256
+ dtype=self.dtype,
257
+ )
258
+ else:
259
+ down_block = FlaxDownBlock2D(
260
+ in_channels=input_channel,
261
+ out_channels=output_channel,
262
+ dropout=self.dropout,
263
+ num_layers=self.layers_per_block,
264
+ add_downsample=not is_final_block,
265
+ dtype=self.dtype,
266
+ )
267
+
268
+ down_blocks.append(down_block)
269
+
270
+ for _ in range(self.layers_per_block):
271
+ controlnet_block = nn.Conv(
272
+ output_channel,
273
+ kernel_size=(1, 1),
274
+ padding="VALID",
275
+ kernel_init=nn.initializers.zeros_init(),
276
+ bias_init=nn.initializers.zeros_init(),
277
+ dtype=self.dtype,
278
+ )
279
+ controlnet_down_blocks.append(controlnet_block)
280
+
281
+ if not is_final_block:
282
+ controlnet_block = nn.Conv(
283
+ output_channel,
284
+ kernel_size=(1, 1),
285
+ padding="VALID",
286
+ kernel_init=nn.initializers.zeros_init(),
287
+ bias_init=nn.initializers.zeros_init(),
288
+ dtype=self.dtype,
289
+ )
290
+ controlnet_down_blocks.append(controlnet_block)
291
+
292
+ self.down_blocks = down_blocks
293
+ self.controlnet_down_blocks = controlnet_down_blocks
294
+
295
+ # mid
296
+ mid_block_channel = block_out_channels[-1]
297
+ self.mid_block = FlaxUNetMidBlock2DCrossAttn(
298
+ in_channels=mid_block_channel,
299
+ dropout=self.dropout,
300
+ num_attention_heads=num_attention_heads[-1],
301
+ use_linear_projection=self.use_linear_projection,
302
+ dtype=self.dtype,
303
+ )
304
+
305
+ self.controlnet_mid_block = nn.Conv(
306
+ mid_block_channel,
307
+ kernel_size=(1, 1),
308
+ padding="VALID",
309
+ kernel_init=nn.initializers.zeros_init(),
310
+ bias_init=nn.initializers.zeros_init(),
311
+ dtype=self.dtype,
312
+ )
313
+
314
+ def __call__(
315
+ self,
316
+ sample: jnp.ndarray,
317
+ timesteps: Union[jnp.ndarray, float, int],
318
+ encoder_hidden_states: jnp.ndarray,
319
+ controlnet_cond: jnp.ndarray,
320
+ conditioning_scale: float = 1.0,
321
+ return_dict: bool = True,
322
+ train: bool = False,
323
+ ) -> Union[FlaxControlNetOutput, Tuple[Tuple[jnp.ndarray, ...], jnp.ndarray]]:
324
+ r"""
325
+ Args:
326
+ sample (`jnp.ndarray`): (batch, channel, height, width) noisy inputs tensor
327
+ timestep (`jnp.ndarray` or `float` or `int`): timesteps
328
+ encoder_hidden_states (`jnp.ndarray`): (batch_size, sequence_length, hidden_size) encoder hidden states
329
+ controlnet_cond (`jnp.ndarray`): (batch, channel, height, width) the conditional input tensor
330
+ conditioning_scale (`float`, *optional*, defaults to `1.0`): the scale factor for controlnet outputs
331
+ return_dict (`bool`, *optional*, defaults to `True`):
332
+ Whether or not to return a [`models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] instead of a
333
+ plain tuple.
334
+ train (`bool`, *optional*, defaults to `False`):
335
+ Use deterministic functions and disable dropout when not training.
336
+
337
+ Returns:
338
+ [`~models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] or `tuple`:
339
+ [`~models.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise a
340
+ `tuple`. When returning a tuple, the first element is the sample tensor.
341
+ """
342
+ channel_order = self.controlnet_conditioning_channel_order
343
+ if channel_order == "bgr":
344
+ controlnet_cond = jnp.flip(controlnet_cond, axis=1)
345
+
346
+ # 1. time
347
+ if not isinstance(timesteps, jnp.ndarray):
348
+ timesteps = jnp.array([timesteps], dtype=jnp.int32)
349
+ elif isinstance(timesteps, jnp.ndarray) and len(timesteps.shape) == 0:
350
+ timesteps = timesteps.astype(dtype=jnp.float32)
351
+ timesteps = jnp.expand_dims(timesteps, 0)
352
+
353
+ t_emb = self.time_proj(timesteps)
354
+ t_emb = self.time_embedding(t_emb)
355
+
356
+ # 2. pre-process
357
+ sample = jnp.transpose(sample, (0, 2, 3, 1))
358
+ sample = self.conv_in(sample)
359
+
360
+ controlnet_cond = jnp.transpose(controlnet_cond, (0, 2, 3, 1))
361
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
362
+ sample += controlnet_cond
363
+
364
+ # 3. down
365
+ down_block_res_samples = (sample,)
366
+ for down_block in self.down_blocks:
367
+ if isinstance(down_block, FlaxCrossAttnDownBlock2D):
368
+ sample, res_samples = down_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
369
+ else:
370
+ sample, res_samples = down_block(sample, t_emb, deterministic=not train)
371
+ down_block_res_samples += res_samples
372
+
373
+ # 4. mid
374
+ sample = self.mid_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
375
+
376
+ # 5. contronet blocks
377
+ controlnet_down_block_res_samples = ()
378
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
379
+ down_block_res_sample = controlnet_block(down_block_res_sample)
380
+ controlnet_down_block_res_samples += (down_block_res_sample,)
381
+
382
+ down_block_res_samples = controlnet_down_block_res_samples
383
+
384
+ mid_block_res_sample = self.controlnet_mid_block(sample)
385
+
386
+ # 6. scaling
387
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
388
+ mid_block_res_sample *= conditioning_scale
389
+
390
+ if not return_dict:
391
+ return (down_block_res_samples, mid_block_res_sample)
392
+
393
+ return FlaxControlNetOutput(
394
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
395
+ )
diffusers/models/dual_transformer_2d.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 Optional
15
+
16
+ from torch import nn
17
+
18
+ from .transformer_2d import Transformer2DModel, Transformer2DModelOutput
19
+
20
+
21
+ class DualTransformer2DModel(nn.Module):
22
+ """
23
+ Dual transformer wrapper that combines two `Transformer2DModel`s for mixed inference.
24
+
25
+ Parameters:
26
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
27
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
28
+ in_channels (`int`, *optional*):
29
+ Pass if the input is continuous. The number of channels in the input and output.
30
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
31
+ dropout (`float`, *optional*, defaults to 0.1): The dropout probability to use.
32
+ cross_attention_dim (`int`, *optional*): The number of encoder_hidden_states dimensions to use.
33
+ sample_size (`int`, *optional*): Pass if the input is discrete. The width of the latent images.
34
+ Note that this is fixed at training time as it is used for learning a number of position embeddings. See
35
+ `ImagePositionalEmbeddings`.
36
+ num_vector_embeds (`int`, *optional*):
37
+ Pass if the input is discrete. The number of classes of the vector embeddings of the latent pixels.
38
+ Includes the class for the masked latent pixel.
39
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
40
+ num_embeds_ada_norm ( `int`, *optional*): Pass if at least one of the norm_layers is `AdaLayerNorm`.
41
+ The number of diffusion steps used during training. Note that this is fixed at training time as it is used
42
+ to learn a number of embeddings that are added to the hidden states. During inference, you can denoise for
43
+ up to but not more than steps than `num_embeds_ada_norm`.
44
+ attention_bias (`bool`, *optional*):
45
+ Configure if the TransformerBlocks' attention should contain a bias parameter.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ num_attention_heads: int = 16,
51
+ attention_head_dim: int = 88,
52
+ in_channels: Optional[int] = None,
53
+ num_layers: int = 1,
54
+ dropout: float = 0.0,
55
+ norm_num_groups: int = 32,
56
+ cross_attention_dim: Optional[int] = None,
57
+ attention_bias: bool = False,
58
+ sample_size: Optional[int] = None,
59
+ num_vector_embeds: Optional[int] = None,
60
+ activation_fn: str = "geglu",
61
+ num_embeds_ada_norm: Optional[int] = None,
62
+ ):
63
+ super().__init__()
64
+ self.transformers = nn.ModuleList(
65
+ [
66
+ Transformer2DModel(
67
+ num_attention_heads=num_attention_heads,
68
+ attention_head_dim=attention_head_dim,
69
+ in_channels=in_channels,
70
+ num_layers=num_layers,
71
+ dropout=dropout,
72
+ norm_num_groups=norm_num_groups,
73
+ cross_attention_dim=cross_attention_dim,
74
+ attention_bias=attention_bias,
75
+ sample_size=sample_size,
76
+ num_vector_embeds=num_vector_embeds,
77
+ activation_fn=activation_fn,
78
+ num_embeds_ada_norm=num_embeds_ada_norm,
79
+ )
80
+ for _ in range(2)
81
+ ]
82
+ )
83
+
84
+ # Variables that can be set by a pipeline:
85
+
86
+ # The ratio of transformer1 to transformer2's output states to be combined during inference
87
+ self.mix_ratio = 0.5
88
+
89
+ # The shape of `encoder_hidden_states` is expected to be
90
+ # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)`
91
+ self.condition_lengths = [77, 257]
92
+
93
+ # Which transformer to use to encode which condition.
94
+ # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])`
95
+ self.transformer_index_for_condition = [1, 0]
96
+
97
+ def forward(
98
+ self,
99
+ hidden_states,
100
+ encoder_hidden_states,
101
+ timestep=None,
102
+ attention_mask=None,
103
+ cross_attention_kwargs=None,
104
+ return_dict: bool = True,
105
+ ):
106
+ """
107
+ Args:
108
+ hidden_states ( When discrete, `torch.LongTensor` of shape `(batch size, num latent pixels)`.
109
+ When continuous, `torch.FloatTensor` of shape `(batch size, channel, height, width)`): Input
110
+ hidden_states.
111
+ encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
112
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
113
+ self-attention.
114
+ timestep ( `torch.long`, *optional*):
115
+ Optional timestep to be applied as an embedding in AdaLayerNorm's. Used to indicate denoising step.
116
+ attention_mask (`torch.FloatTensor`, *optional*):
117
+ Optional attention mask to be applied in Attention.
118
+ cross_attention_kwargs (`dict`, *optional*):
119
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
120
+ `self.processor` in
121
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
122
+ return_dict (`bool`, *optional*, defaults to `True`):
123
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
124
+
125
+ Returns:
126
+ [`~models.transformer_2d.Transformer2DModelOutput`] or `tuple`:
127
+ [`~models.transformer_2d.Transformer2DModelOutput`] if `return_dict` is True, otherwise a `tuple`. When
128
+ returning a tuple, the first element is the sample tensor.
129
+ """
130
+ input_states = hidden_states
131
+
132
+ encoded_states = []
133
+ tokens_start = 0
134
+ # attention_mask is not used yet
135
+ for i in range(2):
136
+ # for each of the two transformers, pass the corresponding condition tokens
137
+ condition_state = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]]
138
+ transformer_index = self.transformer_index_for_condition[i]
139
+ encoded_state = self.transformers[transformer_index](
140
+ input_states,
141
+ encoder_hidden_states=condition_state,
142
+ timestep=timestep,
143
+ cross_attention_kwargs=cross_attention_kwargs,
144
+ return_dict=False,
145
+ )[0]
146
+ encoded_states.append(encoded_state - input_states)
147
+ tokens_start += self.condition_lengths[i]
148
+
149
+ output_states = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio)
150
+ output_states = output_states + input_states
151
+
152
+ if not return_dict:
153
+ return (output_states,)
154
+
155
+ return Transformer2DModelOutput(sample=output_states)
diffusers/models/embeddings.py ADDED
@@ -0,0 +1,792 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 math
15
+ from typing import Optional
16
+
17
+ import numpy as np
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ..utils import USE_PEFT_BACKEND
22
+ from .activations import get_activation
23
+ from .lora import LoRACompatibleLinear
24
+
25
+
26
+ def get_timestep_embedding(
27
+ timesteps: torch.Tensor,
28
+ embedding_dim: int,
29
+ flip_sin_to_cos: bool = False,
30
+ downscale_freq_shift: float = 1,
31
+ scale: float = 1,
32
+ max_period: int = 10000,
33
+ ):
34
+ """
35
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
36
+
37
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
38
+ These may be fractional.
39
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
40
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
41
+ """
42
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
43
+
44
+ half_dim = embedding_dim // 2
45
+ exponent = -math.log(max_period) * torch.arange(
46
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
47
+ )
48
+ exponent = exponent / (half_dim - downscale_freq_shift)
49
+
50
+ emb = torch.exp(exponent)
51
+ emb = timesteps[:, None].float() * emb[None, :]
52
+
53
+ # scale embeddings
54
+ emb = scale * emb
55
+
56
+ # concat sine and cosine embeddings
57
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
58
+
59
+ # flip sine and cosine embeddings
60
+ if flip_sin_to_cos:
61
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
62
+
63
+ # zero pad
64
+ if embedding_dim % 2 == 1:
65
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
66
+ return emb
67
+
68
+
69
+ def get_2d_sincos_pos_embed(
70
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
71
+ ):
72
+ """
73
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
74
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
75
+ """
76
+ if isinstance(grid_size, int):
77
+ grid_size = (grid_size, grid_size)
78
+
79
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
80
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
81
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
82
+ grid = np.stack(grid, axis=0)
83
+
84
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
85
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
86
+ if cls_token and extra_tokens > 0:
87
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
88
+ return pos_embed
89
+
90
+
91
+ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
92
+ if embed_dim % 2 != 0:
93
+ raise ValueError("embed_dim must be divisible by 2")
94
+
95
+ # use half of dimensions to encode grid_h
96
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
97
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
98
+
99
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
100
+ return emb
101
+
102
+
103
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
104
+ """
105
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
106
+ """
107
+ if embed_dim % 2 != 0:
108
+ raise ValueError("embed_dim must be divisible by 2")
109
+
110
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
111
+ omega /= embed_dim / 2.0
112
+ omega = 1.0 / 10000**omega # (D/2,)
113
+
114
+ pos = pos.reshape(-1) # (M,)
115
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
116
+
117
+ emb_sin = np.sin(out) # (M, D/2)
118
+ emb_cos = np.cos(out) # (M, D/2)
119
+
120
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
121
+ return emb
122
+
123
+
124
+ class PatchEmbed(nn.Module):
125
+ """2D Image to Patch Embedding"""
126
+
127
+ def __init__(
128
+ self,
129
+ height=224,
130
+ width=224,
131
+ patch_size=16,
132
+ in_channels=3,
133
+ embed_dim=768,
134
+ layer_norm=False,
135
+ flatten=True,
136
+ bias=True,
137
+ interpolation_scale=1,
138
+ ):
139
+ super().__init__()
140
+
141
+ num_patches = (height // patch_size) * (width // patch_size)
142
+ self.flatten = flatten
143
+ self.layer_norm = layer_norm
144
+
145
+ self.proj = nn.Conv2d(
146
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
147
+ )
148
+ if layer_norm:
149
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
150
+ else:
151
+ self.norm = None
152
+
153
+ self.patch_size = patch_size
154
+ # See:
155
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
156
+ self.height, self.width = height // patch_size, width // patch_size
157
+ self.base_size = height // patch_size
158
+ self.interpolation_scale = interpolation_scale
159
+ pos_embed = get_2d_sincos_pos_embed(
160
+ embed_dim, int(num_patches**0.5), base_size=self.base_size, interpolation_scale=self.interpolation_scale
161
+ )
162
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
163
+
164
+ def forward(self, latent):
165
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
166
+
167
+ latent = self.proj(latent)
168
+ if self.flatten:
169
+ latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
170
+ if self.layer_norm:
171
+ latent = self.norm(latent)
172
+
173
+ # Interpolate positional embeddings if needed.
174
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
175
+ if self.height != height or self.width != width:
176
+ pos_embed = get_2d_sincos_pos_embed(
177
+ embed_dim=self.pos_embed.shape[-1],
178
+ grid_size=(height, width),
179
+ base_size=self.base_size,
180
+ interpolation_scale=self.interpolation_scale,
181
+ )
182
+ pos_embed = torch.from_numpy(pos_embed)
183
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
184
+ else:
185
+ pos_embed = self.pos_embed
186
+
187
+ return (latent + pos_embed).to(latent.dtype)
188
+
189
+
190
+ class TimestepEmbedding(nn.Module):
191
+ def __init__(
192
+ self,
193
+ in_channels: int,
194
+ time_embed_dim: int,
195
+ act_fn: str = "silu",
196
+ out_dim: int = None,
197
+ post_act_fn: Optional[str] = None,
198
+ cond_proj_dim=None,
199
+ ):
200
+ super().__init__()
201
+ linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
202
+
203
+ self.linear_1 = linear_cls(in_channels, time_embed_dim)
204
+
205
+ if cond_proj_dim is not None:
206
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
207
+ else:
208
+ self.cond_proj = None
209
+
210
+ self.act = get_activation(act_fn)
211
+
212
+ if out_dim is not None:
213
+ time_embed_dim_out = out_dim
214
+ else:
215
+ time_embed_dim_out = time_embed_dim
216
+ self.linear_2 = linear_cls(time_embed_dim, time_embed_dim_out)
217
+
218
+ if post_act_fn is None:
219
+ self.post_act = None
220
+ else:
221
+ self.post_act = get_activation(post_act_fn)
222
+
223
+ def forward(self, sample, condition=None):
224
+ if condition is not None:
225
+ sample = sample + self.cond_proj(condition)
226
+ sample = self.linear_1(sample)
227
+
228
+ if self.act is not None:
229
+ sample = self.act(sample)
230
+
231
+ sample = self.linear_2(sample)
232
+
233
+ if self.post_act is not None:
234
+ sample = self.post_act(sample)
235
+ return sample
236
+
237
+
238
+ class Timesteps(nn.Module):
239
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float):
240
+ super().__init__()
241
+ self.num_channels = num_channels
242
+ self.flip_sin_to_cos = flip_sin_to_cos
243
+ self.downscale_freq_shift = downscale_freq_shift
244
+
245
+ def forward(self, timesteps):
246
+ t_emb = get_timestep_embedding(
247
+ timesteps,
248
+ self.num_channels,
249
+ flip_sin_to_cos=self.flip_sin_to_cos,
250
+ downscale_freq_shift=self.downscale_freq_shift,
251
+ )
252
+ return t_emb
253
+
254
+
255
+ class GaussianFourierProjection(nn.Module):
256
+ """Gaussian Fourier embeddings for noise levels."""
257
+
258
+ def __init__(
259
+ self, embedding_size: int = 256, scale: float = 1.0, set_W_to_weight=True, log=True, flip_sin_to_cos=False
260
+ ):
261
+ super().__init__()
262
+ self.weight = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
263
+ self.log = log
264
+ self.flip_sin_to_cos = flip_sin_to_cos
265
+
266
+ if set_W_to_weight:
267
+ # to delete later
268
+ self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
269
+
270
+ self.weight = self.W
271
+
272
+ def forward(self, x):
273
+ if self.log:
274
+ x = torch.log(x)
275
+
276
+ x_proj = x[:, None] * self.weight[None, :] * 2 * np.pi
277
+
278
+ if self.flip_sin_to_cos:
279
+ out = torch.cat([torch.cos(x_proj), torch.sin(x_proj)], dim=-1)
280
+ else:
281
+ out = torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
282
+ return out
283
+
284
+
285
+ class SinusoidalPositionalEmbedding(nn.Module):
286
+ """Apply positional information to a sequence of embeddings.
287
+
288
+ Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to
289
+ them
290
+
291
+ Args:
292
+ embed_dim: (int): Dimension of the positional embedding.
293
+ max_seq_length: Maximum sequence length to apply positional embeddings
294
+
295
+ """
296
+
297
+ def __init__(self, embed_dim: int, max_seq_length: int = 32):
298
+ super().__init__()
299
+ position = torch.arange(max_seq_length).unsqueeze(1)
300
+ div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim))
301
+ pe = torch.zeros(1, max_seq_length, embed_dim)
302
+ pe[0, :, 0::2] = torch.sin(position * div_term)
303
+ pe[0, :, 1::2] = torch.cos(position * div_term)
304
+ self.register_buffer("pe", pe)
305
+
306
+ def forward(self, x):
307
+ _, seq_length, _ = x.shape
308
+ x = x + self.pe[:, :seq_length]
309
+ return x
310
+
311
+
312
+ class ImagePositionalEmbeddings(nn.Module):
313
+ """
314
+ Converts latent image classes into vector embeddings. Sums the vector embeddings with positional embeddings for the
315
+ height and width of the latent space.
316
+
317
+ For more details, see figure 10 of the dall-e paper: https://arxiv.org/abs/2102.12092
318
+
319
+ For VQ-diffusion:
320
+
321
+ Output vector embeddings are used as input for the transformer.
322
+
323
+ Note that the vector embeddings for the transformer are different than the vector embeddings from the VQVAE.
324
+
325
+ Args:
326
+ num_embed (`int`):
327
+ Number of embeddings for the latent pixels embeddings.
328
+ height (`int`):
329
+ Height of the latent image i.e. the number of height embeddings.
330
+ width (`int`):
331
+ Width of the latent image i.e. the number of width embeddings.
332
+ embed_dim (`int`):
333
+ Dimension of the produced vector embeddings. Used for the latent pixel, height, and width embeddings.
334
+ """
335
+
336
+ def __init__(
337
+ self,
338
+ num_embed: int,
339
+ height: int,
340
+ width: int,
341
+ embed_dim: int,
342
+ ):
343
+ super().__init__()
344
+
345
+ self.height = height
346
+ self.width = width
347
+ self.num_embed = num_embed
348
+ self.embed_dim = embed_dim
349
+
350
+ self.emb = nn.Embedding(self.num_embed, embed_dim)
351
+ self.height_emb = nn.Embedding(self.height, embed_dim)
352
+ self.width_emb = nn.Embedding(self.width, embed_dim)
353
+
354
+ def forward(self, index):
355
+ emb = self.emb(index)
356
+
357
+ height_emb = self.height_emb(torch.arange(self.height, device=index.device).view(1, self.height))
358
+
359
+ # 1 x H x D -> 1 x H x 1 x D
360
+ height_emb = height_emb.unsqueeze(2)
361
+
362
+ width_emb = self.width_emb(torch.arange(self.width, device=index.device).view(1, self.width))
363
+
364
+ # 1 x W x D -> 1 x 1 x W x D
365
+ width_emb = width_emb.unsqueeze(1)
366
+
367
+ pos_emb = height_emb + width_emb
368
+
369
+ # 1 x H x W x D -> 1 x L xD
370
+ pos_emb = pos_emb.view(1, self.height * self.width, -1)
371
+
372
+ emb = emb + pos_emb[:, : emb.shape[1], :]
373
+
374
+ return emb
375
+
376
+
377
+ class LabelEmbedding(nn.Module):
378
+ """
379
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
380
+
381
+ Args:
382
+ num_classes (`int`): The number of classes.
383
+ hidden_size (`int`): The size of the vector embeddings.
384
+ dropout_prob (`float`): The probability of dropping a label.
385
+ """
386
+
387
+ def __init__(self, num_classes, hidden_size, dropout_prob):
388
+ super().__init__()
389
+ use_cfg_embedding = dropout_prob > 0
390
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
391
+ self.num_classes = num_classes
392
+ self.dropout_prob = dropout_prob
393
+
394
+ def token_drop(self, labels, force_drop_ids=None):
395
+ """
396
+ Drops labels to enable classifier-free guidance.
397
+ """
398
+ if force_drop_ids is None:
399
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
400
+ else:
401
+ drop_ids = torch.tensor(force_drop_ids == 1)
402
+ labels = torch.where(drop_ids, self.num_classes, labels)
403
+ return labels
404
+
405
+ def forward(self, labels: torch.LongTensor, force_drop_ids=None):
406
+ use_dropout = self.dropout_prob > 0
407
+ if (self.training and use_dropout) or (force_drop_ids is not None):
408
+ labels = self.token_drop(labels, force_drop_ids)
409
+ embeddings = self.embedding_table(labels)
410
+ return embeddings
411
+
412
+
413
+ class TextImageProjection(nn.Module):
414
+ def __init__(
415
+ self,
416
+ text_embed_dim: int = 1024,
417
+ image_embed_dim: int = 768,
418
+ cross_attention_dim: int = 768,
419
+ num_image_text_embeds: int = 10,
420
+ ):
421
+ super().__init__()
422
+
423
+ self.num_image_text_embeds = num_image_text_embeds
424
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
425
+ self.text_proj = nn.Linear(text_embed_dim, cross_attention_dim)
426
+
427
+ def forward(self, text_embeds: torch.FloatTensor, image_embeds: torch.FloatTensor):
428
+ batch_size = text_embeds.shape[0]
429
+
430
+ # image
431
+ image_text_embeds = self.image_embeds(image_embeds)
432
+ image_text_embeds = image_text_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
433
+
434
+ # text
435
+ text_embeds = self.text_proj(text_embeds)
436
+
437
+ return torch.cat([image_text_embeds, text_embeds], dim=1)
438
+
439
+
440
+ class ImageProjection(nn.Module):
441
+ def __init__(
442
+ self,
443
+ image_embed_dim: int = 768,
444
+ cross_attention_dim: int = 768,
445
+ num_image_text_embeds: int = 32,
446
+ ):
447
+ super().__init__()
448
+
449
+ self.num_image_text_embeds = num_image_text_embeds
450
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
451
+ self.norm = nn.LayerNorm(cross_attention_dim)
452
+
453
+ def forward(self, image_embeds: torch.FloatTensor):
454
+ batch_size = image_embeds.shape[0]
455
+
456
+ # image
457
+ image_embeds = self.image_embeds(image_embeds)
458
+ image_embeds = image_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
459
+ image_embeds = self.norm(image_embeds)
460
+ return image_embeds
461
+
462
+
463
+ class CombinedTimestepLabelEmbeddings(nn.Module):
464
+ def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
465
+ super().__init__()
466
+
467
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1)
468
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
469
+ self.class_embedder = LabelEmbedding(num_classes, embedding_dim, class_dropout_prob)
470
+
471
+ def forward(self, timestep, class_labels, hidden_dtype=None):
472
+ timesteps_proj = self.time_proj(timestep)
473
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
474
+
475
+ class_labels = self.class_embedder(class_labels) # (N, D)
476
+
477
+ conditioning = timesteps_emb + class_labels # (N, D)
478
+
479
+ return conditioning
480
+
481
+
482
+ class TextTimeEmbedding(nn.Module):
483
+ def __init__(self, encoder_dim: int, time_embed_dim: int, num_heads: int = 64):
484
+ super().__init__()
485
+ self.norm1 = nn.LayerNorm(encoder_dim)
486
+ self.pool = AttentionPooling(num_heads, encoder_dim)
487
+ self.proj = nn.Linear(encoder_dim, time_embed_dim)
488
+ self.norm2 = nn.LayerNorm(time_embed_dim)
489
+
490
+ def forward(self, hidden_states):
491
+ hidden_states = self.norm1(hidden_states)
492
+ hidden_states = self.pool(hidden_states)
493
+ hidden_states = self.proj(hidden_states)
494
+ hidden_states = self.norm2(hidden_states)
495
+ return hidden_states
496
+
497
+
498
+ class TextImageTimeEmbedding(nn.Module):
499
+ def __init__(self, text_embed_dim: int = 768, image_embed_dim: int = 768, time_embed_dim: int = 1536):
500
+ super().__init__()
501
+ self.text_proj = nn.Linear(text_embed_dim, time_embed_dim)
502
+ self.text_norm = nn.LayerNorm(time_embed_dim)
503
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
504
+
505
+ def forward(self, text_embeds: torch.FloatTensor, image_embeds: torch.FloatTensor):
506
+ # text
507
+ time_text_embeds = self.text_proj(text_embeds)
508
+ time_text_embeds = self.text_norm(time_text_embeds)
509
+
510
+ # image
511
+ time_image_embeds = self.image_proj(image_embeds)
512
+
513
+ return time_image_embeds + time_text_embeds
514
+
515
+
516
+ class ImageTimeEmbedding(nn.Module):
517
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
518
+ super().__init__()
519
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
520
+ self.image_norm = nn.LayerNorm(time_embed_dim)
521
+
522
+ def forward(self, image_embeds: torch.FloatTensor):
523
+ # image
524
+ time_image_embeds = self.image_proj(image_embeds)
525
+ time_image_embeds = self.image_norm(time_image_embeds)
526
+ return time_image_embeds
527
+
528
+
529
+ class ImageHintTimeEmbedding(nn.Module):
530
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
531
+ super().__init__()
532
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
533
+ self.image_norm = nn.LayerNorm(time_embed_dim)
534
+ self.input_hint_block = nn.Sequential(
535
+ nn.Conv2d(3, 16, 3, padding=1),
536
+ nn.SiLU(),
537
+ nn.Conv2d(16, 16, 3, padding=1),
538
+ nn.SiLU(),
539
+ nn.Conv2d(16, 32, 3, padding=1, stride=2),
540
+ nn.SiLU(),
541
+ nn.Conv2d(32, 32, 3, padding=1),
542
+ nn.SiLU(),
543
+ nn.Conv2d(32, 96, 3, padding=1, stride=2),
544
+ nn.SiLU(),
545
+ nn.Conv2d(96, 96, 3, padding=1),
546
+ nn.SiLU(),
547
+ nn.Conv2d(96, 256, 3, padding=1, stride=2),
548
+ nn.SiLU(),
549
+ nn.Conv2d(256, 4, 3, padding=1),
550
+ )
551
+
552
+ def forward(self, image_embeds: torch.FloatTensor, hint: torch.FloatTensor):
553
+ # image
554
+ time_image_embeds = self.image_proj(image_embeds)
555
+ time_image_embeds = self.image_norm(time_image_embeds)
556
+ hint = self.input_hint_block(hint)
557
+ return time_image_embeds, hint
558
+
559
+
560
+ class AttentionPooling(nn.Module):
561
+ # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54
562
+
563
+ def __init__(self, num_heads, embed_dim, dtype=None):
564
+ super().__init__()
565
+ self.dtype = dtype
566
+ self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5)
567
+ self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
568
+ self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
569
+ self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
570
+ self.num_heads = num_heads
571
+ self.dim_per_head = embed_dim // self.num_heads
572
+
573
+ def forward(self, x):
574
+ bs, length, width = x.size()
575
+
576
+ def shape(x):
577
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
578
+ x = x.view(bs, -1, self.num_heads, self.dim_per_head)
579
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
580
+ x = x.transpose(1, 2)
581
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
582
+ x = x.reshape(bs * self.num_heads, -1, self.dim_per_head)
583
+ # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
584
+ x = x.transpose(1, 2)
585
+ return x
586
+
587
+ class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype)
588
+ x = torch.cat([class_token, x], dim=1) # (bs, length+1, width)
589
+
590
+ # (bs*n_heads, class_token_length, dim_per_head)
591
+ q = shape(self.q_proj(class_token))
592
+ # (bs*n_heads, length+class_token_length, dim_per_head)
593
+ k = shape(self.k_proj(x))
594
+ v = shape(self.v_proj(x))
595
+
596
+ # (bs*n_heads, class_token_length, length+class_token_length):
597
+ scale = 1 / math.sqrt(math.sqrt(self.dim_per_head))
598
+ weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards
599
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
600
+
601
+ # (bs*n_heads, dim_per_head, class_token_length)
602
+ a = torch.einsum("bts,bcs->bct", weight, v)
603
+
604
+ # (bs, length+1, width)
605
+ a = a.reshape(bs, -1, 1).transpose(1, 2)
606
+
607
+ return a[:, 0, :] # cls_token
608
+
609
+
610
+ class FourierEmbedder(nn.Module):
611
+ def __init__(self, num_freqs=64, temperature=100):
612
+ super().__init__()
613
+
614
+ self.num_freqs = num_freqs
615
+ self.temperature = temperature
616
+
617
+ freq_bands = temperature ** (torch.arange(num_freqs) / num_freqs)
618
+ freq_bands = freq_bands[None, None, None]
619
+ self.register_buffer("freq_bands", freq_bands, persistent=False)
620
+
621
+ def __call__(self, x):
622
+ x = self.freq_bands * x.unsqueeze(-1)
623
+ return torch.stack((x.sin(), x.cos()), dim=-1).permute(0, 1, 3, 4, 2).reshape(*x.shape[:2], -1)
624
+
625
+
626
+ class PositionNet(nn.Module):
627
+ def __init__(self, positive_len, out_dim, feature_type="text-only", fourier_freqs=8):
628
+ super().__init__()
629
+ self.positive_len = positive_len
630
+ self.out_dim = out_dim
631
+
632
+ self.fourier_embedder = FourierEmbedder(num_freqs=fourier_freqs)
633
+ self.position_dim = fourier_freqs * 2 * 4 # 2: sin/cos, 4: xyxy
634
+
635
+ if isinstance(out_dim, tuple):
636
+ out_dim = out_dim[0]
637
+
638
+ if feature_type == "text-only":
639
+ self.linears = nn.Sequential(
640
+ nn.Linear(self.positive_len + self.position_dim, 512),
641
+ nn.SiLU(),
642
+ nn.Linear(512, 512),
643
+ nn.SiLU(),
644
+ nn.Linear(512, out_dim),
645
+ )
646
+ self.null_positive_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
647
+
648
+ elif feature_type == "text-image":
649
+ self.linears_text = nn.Sequential(
650
+ nn.Linear(self.positive_len + self.position_dim, 512),
651
+ nn.SiLU(),
652
+ nn.Linear(512, 512),
653
+ nn.SiLU(),
654
+ nn.Linear(512, out_dim),
655
+ )
656
+ self.linears_image = nn.Sequential(
657
+ nn.Linear(self.positive_len + self.position_dim, 512),
658
+ nn.SiLU(),
659
+ nn.Linear(512, 512),
660
+ nn.SiLU(),
661
+ nn.Linear(512, out_dim),
662
+ )
663
+ self.null_text_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
664
+ self.null_image_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
665
+
666
+ self.null_position_feature = torch.nn.Parameter(torch.zeros([self.position_dim]))
667
+
668
+ def forward(
669
+ self,
670
+ boxes,
671
+ masks,
672
+ positive_embeddings=None,
673
+ phrases_masks=None,
674
+ image_masks=None,
675
+ phrases_embeddings=None,
676
+ image_embeddings=None,
677
+ ):
678
+ masks = masks.unsqueeze(-1)
679
+
680
+ # embedding position (it may includes padding as placeholder)
681
+ xyxy_embedding = self.fourier_embedder(boxes) # B*N*4 -> B*N*C
682
+
683
+ # learnable null embedding
684
+ xyxy_null = self.null_position_feature.view(1, 1, -1)
685
+
686
+ # replace padding with learnable null embedding
687
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
688
+
689
+ # positionet with text only information
690
+ if positive_embeddings is not None:
691
+ # learnable null embedding
692
+ positive_null = self.null_positive_feature.view(1, 1, -1)
693
+
694
+ # replace padding with learnable null embedding
695
+ positive_embeddings = positive_embeddings * masks + (1 - masks) * positive_null
696
+
697
+ objs = self.linears(torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
698
+
699
+ # positionet with text and image infomation
700
+ else:
701
+ phrases_masks = phrases_masks.unsqueeze(-1)
702
+ image_masks = image_masks.unsqueeze(-1)
703
+
704
+ # learnable null embedding
705
+ text_null = self.null_text_feature.view(1, 1, -1)
706
+ image_null = self.null_image_feature.view(1, 1, -1)
707
+
708
+ # replace padding with learnable null embedding
709
+ phrases_embeddings = phrases_embeddings * phrases_masks + (1 - phrases_masks) * text_null
710
+ image_embeddings = image_embeddings * image_masks + (1 - image_masks) * image_null
711
+
712
+ objs_text = self.linears_text(torch.cat([phrases_embeddings, xyxy_embedding], dim=-1))
713
+ objs_image = self.linears_image(torch.cat([image_embeddings, xyxy_embedding], dim=-1))
714
+ objs = torch.cat([objs_text, objs_image], dim=1)
715
+
716
+ return objs
717
+
718
+
719
+ class CombinedTimestepSizeEmbeddings(nn.Module):
720
+ """
721
+ For PixArt-Alpha.
722
+
723
+ Reference:
724
+ https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
725
+ """
726
+
727
+ def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
728
+ super().__init__()
729
+
730
+ self.outdim = size_emb_dim
731
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
732
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
733
+
734
+ self.use_additional_conditions = use_additional_conditions
735
+ if use_additional_conditions:
736
+ self.use_additional_conditions = True
737
+ self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
738
+ self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
739
+ self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
740
+
741
+ def apply_condition(self, size: torch.Tensor, batch_size: int, embedder: nn.Module):
742
+ if size.ndim == 1:
743
+ size = size[:, None]
744
+
745
+ if size.shape[0] != batch_size:
746
+ size = size.repeat(batch_size // size.shape[0], 1)
747
+ if size.shape[0] != batch_size:
748
+ raise ValueError(f"`batch_size` should be {size.shape[0]} but found {batch_size}.")
749
+
750
+ current_batch_size, dims = size.shape[0], size.shape[1]
751
+ size = size.reshape(-1)
752
+ size_freq = self.additional_condition_proj(size).to(size.dtype)
753
+
754
+ size_emb = embedder(size_freq)
755
+ size_emb = size_emb.reshape(current_batch_size, dims * self.outdim)
756
+ return size_emb
757
+
758
+ def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
759
+ timesteps_proj = self.time_proj(timestep)
760
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
761
+
762
+ if self.use_additional_conditions:
763
+ resolution = self.apply_condition(resolution, batch_size=batch_size, embedder=self.resolution_embedder)
764
+ aspect_ratio = self.apply_condition(
765
+ aspect_ratio, batch_size=batch_size, embedder=self.aspect_ratio_embedder
766
+ )
767
+ conditioning = timesteps_emb + torch.cat([resolution, aspect_ratio], dim=1)
768
+ else:
769
+ conditioning = timesteps_emb
770
+
771
+ return conditioning
772
+
773
+
774
+ class CaptionProjection(nn.Module):
775
+ """
776
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
777
+
778
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
779
+ """
780
+
781
+ def __init__(self, in_features, hidden_size, num_tokens=120):
782
+ super().__init__()
783
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
784
+ self.act_1 = nn.GELU(approximate="tanh")
785
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size, bias=True)
786
+ self.register_buffer("y_embedding", nn.Parameter(torch.randn(num_tokens, in_features) / in_features**0.5))
787
+
788
+ def forward(self, caption, force_drop_ids=None):
789
+ hidden_states = self.linear_1(caption)
790
+ hidden_states = self.act_1(hidden_states)
791
+ hidden_states = self.linear_2(hidden_states)
792
+ return hidden_states
diffusers/models/embeddings_flax.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 math
15
+
16
+ import flax.linen as nn
17
+ import jax.numpy as jnp
18
+
19
+
20
+ def get_sinusoidal_embeddings(
21
+ timesteps: jnp.ndarray,
22
+ embedding_dim: int,
23
+ freq_shift: float = 1,
24
+ min_timescale: float = 1,
25
+ max_timescale: float = 1.0e4,
26
+ flip_sin_to_cos: bool = False,
27
+ scale: float = 1.0,
28
+ ) -> jnp.ndarray:
29
+ """Returns the positional encoding (same as Tensor2Tensor).
30
+
31
+ Args:
32
+ timesteps: a 1-D Tensor of N indices, one per batch element.
33
+ These may be fractional.
34
+ embedding_dim: The number of output channels.
35
+ min_timescale: The smallest time unit (should probably be 0.0).
36
+ max_timescale: The largest time unit.
37
+ Returns:
38
+ a Tensor of timing signals [N, num_channels]
39
+ """
40
+ assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
41
+ assert embedding_dim % 2 == 0, f"Embedding dimension {embedding_dim} should be even"
42
+ num_timescales = float(embedding_dim // 2)
43
+ log_timescale_increment = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift)
44
+ inv_timescales = min_timescale * jnp.exp(jnp.arange(num_timescales, dtype=jnp.float32) * -log_timescale_increment)
45
+ emb = jnp.expand_dims(timesteps, 1) * jnp.expand_dims(inv_timescales, 0)
46
+
47
+ # scale embeddings
48
+ scaled_time = scale * emb
49
+
50
+ if flip_sin_to_cos:
51
+ signal = jnp.concatenate([jnp.cos(scaled_time), jnp.sin(scaled_time)], axis=1)
52
+ else:
53
+ signal = jnp.concatenate([jnp.sin(scaled_time), jnp.cos(scaled_time)], axis=1)
54
+ signal = jnp.reshape(signal, [jnp.shape(timesteps)[0], embedding_dim])
55
+ return signal
56
+
57
+
58
+ class FlaxTimestepEmbedding(nn.Module):
59
+ r"""
60
+ Time step Embedding Module. Learns embeddings for input time steps.
61
+
62
+ Args:
63
+ time_embed_dim (`int`, *optional*, defaults to `32`):
64
+ Time step embedding dimension
65
+ dtype (:obj:`jnp.dtype`, *optional*, defaults to jnp.float32):
66
+ Parameters `dtype`
67
+ """
68
+
69
+ time_embed_dim: int = 32
70
+ dtype: jnp.dtype = jnp.float32
71
+
72
+ @nn.compact
73
+ def __call__(self, temb):
74
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_1")(temb)
75
+ temb = nn.silu(temb)
76
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_2")(temb)
77
+ return temb
78
+
79
+
80
+ class FlaxTimesteps(nn.Module):
81
+ r"""
82
+ Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239
83
+
84
+ Args:
85
+ dim (`int`, *optional*, defaults to `32`):
86
+ Time step embedding dimension
87
+ """
88
+
89
+ dim: int = 32
90
+ flip_sin_to_cos: bool = False
91
+ freq_shift: float = 1
92
+
93
+ @nn.compact
94
+ def __call__(self, timesteps):
95
+ return get_sinusoidal_embeddings(
96
+ timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift
97
+ )
diffusers/models/lora.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ # IMPORTANT: #
17
+ ###################################################################
18
+ # ----------------------------------------------------------------#
19
+ # This file is deprecated and will be removed soon #
20
+ # (as soon as PEFT will become a required dependency for LoRA) #
21
+ # ----------------------------------------------------------------#
22
+ ###################################################################
23
+
24
+ from typing import Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+
30
+ from ..utils import logging
31
+ from ..utils.import_utils import is_transformers_available
32
+
33
+
34
+ if is_transformers_available():
35
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ def text_encoder_attn_modules(text_encoder):
42
+ attn_modules = []
43
+
44
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
45
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
46
+ name = f"text_model.encoder.layers.{i}.self_attn"
47
+ mod = layer.self_attn
48
+ attn_modules.append((name, mod))
49
+ else:
50
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
51
+
52
+ return attn_modules
53
+
54
+
55
+ def text_encoder_mlp_modules(text_encoder):
56
+ mlp_modules = []
57
+
58
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
59
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
60
+ mlp_mod = layer.mlp
61
+ name = f"text_model.encoder.layers.{i}.mlp"
62
+ mlp_modules.append((name, mlp_mod))
63
+ else:
64
+ raise ValueError(f"do not know how to get mlp modules for: {text_encoder.__class__.__name__}")
65
+
66
+ return mlp_modules
67
+
68
+
69
+ def adjust_lora_scale_text_encoder(text_encoder, lora_scale: float = 1.0):
70
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
71
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
72
+ attn_module.q_proj.lora_scale = lora_scale
73
+ attn_module.k_proj.lora_scale = lora_scale
74
+ attn_module.v_proj.lora_scale = lora_scale
75
+ attn_module.out_proj.lora_scale = lora_scale
76
+
77
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
78
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
79
+ mlp_module.fc1.lora_scale = lora_scale
80
+ mlp_module.fc2.lora_scale = lora_scale
81
+
82
+
83
+ class PatchedLoraProjection(torch.nn.Module):
84
+ def __init__(self, regular_linear_layer, lora_scale=1, network_alpha=None, rank=4, dtype=None):
85
+ super().__init__()
86
+ from ..models.lora import LoRALinearLayer
87
+
88
+ self.regular_linear_layer = regular_linear_layer
89
+
90
+ device = self.regular_linear_layer.weight.device
91
+
92
+ if dtype is None:
93
+ dtype = self.regular_linear_layer.weight.dtype
94
+
95
+ self.lora_linear_layer = LoRALinearLayer(
96
+ self.regular_linear_layer.in_features,
97
+ self.regular_linear_layer.out_features,
98
+ network_alpha=network_alpha,
99
+ device=device,
100
+ dtype=dtype,
101
+ rank=rank,
102
+ )
103
+
104
+ self.lora_scale = lora_scale
105
+
106
+ # overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved
107
+ # when saving the whole text encoder model and when LoRA is unloaded or fused
108
+ def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
109
+ if self.lora_linear_layer is None:
110
+ return self.regular_linear_layer.state_dict(
111
+ *args, destination=destination, prefix=prefix, keep_vars=keep_vars
112
+ )
113
+
114
+ return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
115
+
116
+ def _fuse_lora(self, lora_scale=1.0, safe_fusing=False):
117
+ if self.lora_linear_layer is None:
118
+ return
119
+
120
+ dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device
121
+
122
+ w_orig = self.regular_linear_layer.weight.data.float()
123
+ w_up = self.lora_linear_layer.up.weight.data.float()
124
+ w_down = self.lora_linear_layer.down.weight.data.float()
125
+
126
+ if self.lora_linear_layer.network_alpha is not None:
127
+ w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank
128
+
129
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
130
+
131
+ if safe_fusing and torch.isnan(fused_weight).any().item():
132
+ raise ValueError(
133
+ "This LoRA weight seems to be broken. "
134
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
135
+ "LoRA weights will not be fused."
136
+ )
137
+
138
+ self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype)
139
+
140
+ # we can drop the lora layer now
141
+ self.lora_linear_layer = None
142
+
143
+ # offload the up and down matrices to CPU to not blow the memory
144
+ self.w_up = w_up.cpu()
145
+ self.w_down = w_down.cpu()
146
+ self.lora_scale = lora_scale
147
+
148
+ def _unfuse_lora(self):
149
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
150
+ return
151
+
152
+ fused_weight = self.regular_linear_layer.weight.data
153
+ dtype, device = fused_weight.dtype, fused_weight.device
154
+
155
+ w_up = self.w_up.to(device=device).float()
156
+ w_down = self.w_down.to(device).float()
157
+
158
+ unfused_weight = fused_weight.float() - (self.lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
159
+ self.regular_linear_layer.weight.data = unfused_weight.to(device=device, dtype=dtype)
160
+
161
+ self.w_up = None
162
+ self.w_down = None
163
+
164
+ def forward(self, input):
165
+ if self.lora_scale is None:
166
+ self.lora_scale = 1.0
167
+ if self.lora_linear_layer is None:
168
+ return self.regular_linear_layer(input)
169
+ return self.regular_linear_layer(input) + (self.lora_scale * self.lora_linear_layer(input))
170
+
171
+
172
+ class LoRALinearLayer(nn.Module):
173
+ r"""
174
+ A linear layer that is used with LoRA.
175
+
176
+ Parameters:
177
+ in_features (`int`):
178
+ Number of input features.
179
+ out_features (`int`):
180
+ Number of output features.
181
+ rank (`int`, `optional`, defaults to 4):
182
+ The rank of the LoRA layer.
183
+ network_alpha (`float`, `optional`, defaults to `None`):
184
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
185
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
186
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
187
+ device (`torch.device`, `optional`, defaults to `None`):
188
+ The device to use for the layer's weights.
189
+ dtype (`torch.dtype`, `optional`, defaults to `None`):
190
+ The dtype to use for the layer's weights.
191
+ """
192
+
193
+ def __init__(
194
+ self,
195
+ in_features: int,
196
+ out_features: int,
197
+ rank: int = 4,
198
+ network_alpha: Optional[float] = None,
199
+ device: Optional[Union[torch.device, str]] = None,
200
+ dtype: Optional[torch.dtype] = None,
201
+ ):
202
+ super().__init__()
203
+
204
+ self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
205
+ self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
206
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
207
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
208
+ self.network_alpha = network_alpha
209
+ self.rank = rank
210
+ self.out_features = out_features
211
+ self.in_features = in_features
212
+
213
+ nn.init.normal_(self.down.weight, std=1 / rank)
214
+ nn.init.zeros_(self.up.weight)
215
+
216
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
217
+ orig_dtype = hidden_states.dtype
218
+ dtype = self.down.weight.dtype
219
+
220
+ down_hidden_states = self.down(hidden_states.to(dtype))
221
+ up_hidden_states = self.up(down_hidden_states)
222
+
223
+ if self.network_alpha is not None:
224
+ up_hidden_states *= self.network_alpha / self.rank
225
+
226
+ return up_hidden_states.to(orig_dtype)
227
+
228
+
229
+ class LoRAConv2dLayer(nn.Module):
230
+ r"""
231
+ A convolutional layer that is used with LoRA.
232
+
233
+ Parameters:
234
+ in_features (`int`):
235
+ Number of input features.
236
+ out_features (`int`):
237
+ Number of output features.
238
+ rank (`int`, `optional`, defaults to 4):
239
+ The rank of the LoRA layer.
240
+ kernel_size (`int` or `tuple` of two `int`, `optional`, defaults to 1):
241
+ The kernel size of the convolution.
242
+ stride (`int` or `tuple` of two `int`, `optional`, defaults to 1):
243
+ The stride of the convolution.
244
+ padding (`int` or `tuple` of two `int` or `str`, `optional`, defaults to 0):
245
+ The padding of the convolution.
246
+ network_alpha (`float`, `optional`, defaults to `None`):
247
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
248
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
249
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
250
+ """
251
+
252
+ def __init__(
253
+ self,
254
+ in_features: int,
255
+ out_features: int,
256
+ rank: int = 4,
257
+ kernel_size: Union[int, Tuple[int, int]] = (1, 1),
258
+ stride: Union[int, Tuple[int, int]] = (1, 1),
259
+ padding: Union[int, Tuple[int, int], str] = 0,
260
+ network_alpha: Optional[float] = None,
261
+ ):
262
+ super().__init__()
263
+
264
+ self.down = nn.Conv2d(in_features, rank, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
265
+ # according to the official kohya_ss trainer kernel_size are always fixed for the up layer
266
+ # # see: https://github.com/bmaltais/kohya_ss/blob/2accb1305979ba62f5077a23aabac23b4c37e935/networks/lora_diffusers.py#L129
267
+ self.up = nn.Conv2d(rank, out_features, kernel_size=(1, 1), stride=(1, 1), bias=False)
268
+
269
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
270
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
271
+ self.network_alpha = network_alpha
272
+ self.rank = rank
273
+
274
+ nn.init.normal_(self.down.weight, std=1 / rank)
275
+ nn.init.zeros_(self.up.weight)
276
+
277
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
278
+ orig_dtype = hidden_states.dtype
279
+ dtype = self.down.weight.dtype
280
+
281
+ down_hidden_states = self.down(hidden_states.to(dtype))
282
+ up_hidden_states = self.up(down_hidden_states)
283
+
284
+ if self.network_alpha is not None:
285
+ up_hidden_states *= self.network_alpha / self.rank
286
+
287
+ return up_hidden_states.to(orig_dtype)
288
+
289
+
290
+ class LoRACompatibleConv(nn.Conv2d):
291
+ """
292
+ A convolutional layer that can be used with LoRA.
293
+ """
294
+
295
+ def __init__(self, *args, lora_layer: Optional[LoRAConv2dLayer] = None, **kwargs):
296
+ super().__init__(*args, **kwargs)
297
+ self.lora_layer = lora_layer
298
+
299
+ def set_lora_layer(self, lora_layer: Optional[LoRAConv2dLayer]):
300
+ self.lora_layer = lora_layer
301
+
302
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
303
+ if self.lora_layer is None:
304
+ return
305
+
306
+ dtype, device = self.weight.data.dtype, self.weight.data.device
307
+
308
+ w_orig = self.weight.data.float()
309
+ w_up = self.lora_layer.up.weight.data.float()
310
+ w_down = self.lora_layer.down.weight.data.float()
311
+
312
+ if self.lora_layer.network_alpha is not None:
313
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
314
+
315
+ fusion = torch.mm(w_up.flatten(start_dim=1), w_down.flatten(start_dim=1))
316
+ fusion = fusion.reshape((w_orig.shape))
317
+ fused_weight = w_orig + (lora_scale * fusion)
318
+
319
+ if safe_fusing and torch.isnan(fused_weight).any().item():
320
+ raise ValueError(
321
+ "This LoRA weight seems to be broken. "
322
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
323
+ "LoRA weights will not be fused."
324
+ )
325
+
326
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
327
+
328
+ # we can drop the lora layer now
329
+ self.lora_layer = None
330
+
331
+ # offload the up and down matrices to CPU to not blow the memory
332
+ self.w_up = w_up.cpu()
333
+ self.w_down = w_down.cpu()
334
+ self._lora_scale = lora_scale
335
+
336
+ def _unfuse_lora(self):
337
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
338
+ return
339
+
340
+ fused_weight = self.weight.data
341
+ dtype, device = fused_weight.data.dtype, fused_weight.data.device
342
+
343
+ self.w_up = self.w_up.to(device=device).float()
344
+ self.w_down = self.w_down.to(device).float()
345
+
346
+ fusion = torch.mm(self.w_up.flatten(start_dim=1), self.w_down.flatten(start_dim=1))
347
+ fusion = fusion.reshape((fused_weight.shape))
348
+ unfused_weight = fused_weight.float() - (self._lora_scale * fusion)
349
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
350
+
351
+ self.w_up = None
352
+ self.w_down = None
353
+
354
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
355
+ if self.lora_layer is None:
356
+ # make sure to the functional Conv2D function as otherwise torch.compile's graph will break
357
+ # see: https://github.com/huggingface/diffusers/pull/4315
358
+ return F.conv2d(
359
+ hidden_states, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups
360
+ )
361
+ else:
362
+ original_outputs = F.conv2d(
363
+ hidden_states, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups
364
+ )
365
+ return original_outputs + (scale * self.lora_layer(hidden_states))
366
+
367
+
368
+ class LoRACompatibleLinear(nn.Linear):
369
+ """
370
+ A Linear layer that can be used with LoRA.
371
+ """
372
+
373
+ def __init__(self, *args, lora_layer: Optional[LoRALinearLayer] = None, **kwargs):
374
+ super().__init__(*args, **kwargs)
375
+ self.lora_layer = lora_layer
376
+
377
+ def set_lora_layer(self, lora_layer: Optional[LoRALinearLayer]):
378
+ self.lora_layer = lora_layer
379
+
380
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
381
+ if self.lora_layer is None:
382
+ return
383
+
384
+ dtype, device = self.weight.data.dtype, self.weight.data.device
385
+
386
+ w_orig = self.weight.data.float()
387
+ w_up = self.lora_layer.up.weight.data.float()
388
+ w_down = self.lora_layer.down.weight.data.float()
389
+
390
+ if self.lora_layer.network_alpha is not None:
391
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
392
+
393
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
394
+
395
+ if safe_fusing and torch.isnan(fused_weight).any().item():
396
+ raise ValueError(
397
+ "This LoRA weight seems to be broken. "
398
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
399
+ "LoRA weights will not be fused."
400
+ )
401
+
402
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
403
+
404
+ # we can drop the lora layer now
405
+ self.lora_layer = None
406
+
407
+ # offload the up and down matrices to CPU to not blow the memory
408
+ self.w_up = w_up.cpu()
409
+ self.w_down = w_down.cpu()
410
+ self._lora_scale = lora_scale
411
+
412
+ def _unfuse_lora(self):
413
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
414
+ return
415
+
416
+ fused_weight = self.weight.data
417
+ dtype, device = fused_weight.dtype, fused_weight.device
418
+
419
+ w_up = self.w_up.to(device=device).float()
420
+ w_down = self.w_down.to(device).float()
421
+
422
+ unfused_weight = fused_weight.float() - (self._lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
423
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
424
+
425
+ self.w_up = None
426
+ self.w_down = None
427
+
428
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
429
+ if self.lora_layer is None:
430
+ out = super().forward(hidden_states)
431
+ return out
432
+ else:
433
+ out = super().forward(hidden_states) + (scale * self.lora_layer(hidden_states))
434
+ return out
diffusers/models/modeling_flax_pytorch_utils.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """ PyTorch - Flax general utilities."""
16
+ import re
17
+
18
+ import jax.numpy as jnp
19
+ from flax.traverse_util import flatten_dict, unflatten_dict
20
+ from jax.random import PRNGKey
21
+
22
+ from ..utils import logging
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+
28
+ def rename_key(key):
29
+ regex = r"\w+[.]\d+"
30
+ pats = re.findall(regex, key)
31
+ for pat in pats:
32
+ key = key.replace(pat, "_".join(pat.split(".")))
33
+ return key
34
+
35
+
36
+ #####################
37
+ # PyTorch => Flax #
38
+ #####################
39
+
40
+
41
+ # Adapted from https://github.com/huggingface/transformers/blob/c603c80f46881ae18b2ca50770ef65fa4033eacd/src/transformers/modeling_flax_pytorch_utils.py#L69
42
+ # and https://github.com/patil-suraj/stable-diffusion-jax/blob/main/stable_diffusion_jax/convert_diffusers_to_jax.py
43
+ def rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict):
44
+ """Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
45
+ # conv norm or layer norm
46
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
47
+
48
+ # rename attention layers
49
+ if len(pt_tuple_key) > 1:
50
+ for rename_from, rename_to in (
51
+ ("to_out_0", "proj_attn"),
52
+ ("to_k", "key"),
53
+ ("to_v", "value"),
54
+ ("to_q", "query"),
55
+ ):
56
+ if pt_tuple_key[-2] == rename_from:
57
+ weight_name = pt_tuple_key[-1]
58
+ weight_name = "kernel" if weight_name == "weight" else weight_name
59
+ renamed_pt_tuple_key = pt_tuple_key[:-2] + (rename_to, weight_name)
60
+ if renamed_pt_tuple_key in random_flax_state_dict:
61
+ assert random_flax_state_dict[renamed_pt_tuple_key].shape == pt_tensor.T.shape
62
+ return renamed_pt_tuple_key, pt_tensor.T
63
+
64
+ if (
65
+ any("norm" in str_ for str_ in pt_tuple_key)
66
+ and (pt_tuple_key[-1] == "bias")
67
+ and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
68
+ and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
69
+ ):
70
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
71
+ return renamed_pt_tuple_key, pt_tensor
72
+ elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
73
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
74
+ return renamed_pt_tuple_key, pt_tensor
75
+
76
+ # embedding
77
+ if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
78
+ pt_tuple_key = pt_tuple_key[:-1] + ("embedding",)
79
+ return renamed_pt_tuple_key, pt_tensor
80
+
81
+ # conv layer
82
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
83
+ if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
84
+ pt_tensor = pt_tensor.transpose(2, 3, 1, 0)
85
+ return renamed_pt_tuple_key, pt_tensor
86
+
87
+ # linear layer
88
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
89
+ if pt_tuple_key[-1] == "weight":
90
+ pt_tensor = pt_tensor.T
91
+ return renamed_pt_tuple_key, pt_tensor
92
+
93
+ # old PyTorch layer norm weight
94
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",)
95
+ if pt_tuple_key[-1] == "gamma":
96
+ return renamed_pt_tuple_key, pt_tensor
97
+
98
+ # old PyTorch layer norm bias
99
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",)
100
+ if pt_tuple_key[-1] == "beta":
101
+ return renamed_pt_tuple_key, pt_tensor
102
+
103
+ return pt_tuple_key, pt_tensor
104
+
105
+
106
+ def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model, init_key=42):
107
+ # Step 1: Convert pytorch tensor to numpy
108
+ pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
109
+
110
+ # Step 2: Since the model is stateless, get random Flax params
111
+ random_flax_params = flax_model.init_weights(PRNGKey(init_key))
112
+
113
+ random_flax_state_dict = flatten_dict(random_flax_params)
114
+ flax_state_dict = {}
115
+
116
+ # Need to change some parameters name to match Flax names
117
+ for pt_key, pt_tensor in pt_state_dict.items():
118
+ renamed_pt_key = rename_key(pt_key)
119
+ pt_tuple_key = tuple(renamed_pt_key.split("."))
120
+
121
+ # Correctly rename weight parameters
122
+ flax_key, flax_tensor = rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict)
123
+
124
+ if flax_key in random_flax_state_dict:
125
+ if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
126
+ raise ValueError(
127
+ f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
128
+ f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
129
+ )
130
+
131
+ # also add unexpected weight so that warning is thrown
132
+ flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
133
+
134
+ return unflatten_dict(flax_state_dict)
diffusers/models/modeling_flax_utils.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+
16
+ import os
17
+ from pickle import UnpicklingError
18
+ from typing import Any, Dict, Union
19
+
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import msgpack.exceptions
23
+ from flax.core.frozen_dict import FrozenDict, unfreeze
24
+ from flax.serialization import from_bytes, to_bytes
25
+ from flax.traverse_util import flatten_dict, unflatten_dict
26
+ from huggingface_hub import create_repo, hf_hub_download
27
+ from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
28
+ from requests import HTTPError
29
+
30
+ from .. import __version__, is_torch_available
31
+ from ..utils import (
32
+ CONFIG_NAME,
33
+ DIFFUSERS_CACHE,
34
+ FLAX_WEIGHTS_NAME,
35
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
36
+ WEIGHTS_NAME,
37
+ PushToHubMixin,
38
+ logging,
39
+ )
40
+ from .modeling_flax_pytorch_utils import convert_pytorch_state_dict_to_flax
41
+
42
+
43
+ logger = logging.get_logger(__name__)
44
+
45
+
46
+ class FlaxModelMixin(PushToHubMixin):
47
+ r"""
48
+ Base class for all Flax models.
49
+
50
+ [`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
51
+ saving models.
52
+
53
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin.save_pretrained`].
54
+ """
55
+
56
+ config_name = CONFIG_NAME
57
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
58
+ _flax_internal_args = ["name", "parent", "dtype"]
59
+
60
+ @classmethod
61
+ def _from_config(cls, config, **kwargs):
62
+ """
63
+ All context managers that the model should be initialized under go here.
64
+ """
65
+ return cls(config, **kwargs)
66
+
67
+ def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
68
+ """
69
+ Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
70
+ """
71
+
72
+ # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
73
+ def conditional_cast(param):
74
+ if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
75
+ param = param.astype(dtype)
76
+ return param
77
+
78
+ if mask is None:
79
+ return jax.tree_map(conditional_cast, params)
80
+
81
+ flat_params = flatten_dict(params)
82
+ flat_mask, _ = jax.tree_flatten(mask)
83
+
84
+ for masked, key in zip(flat_mask, flat_params.keys()):
85
+ if masked:
86
+ param = flat_params[key]
87
+ flat_params[key] = conditional_cast(param)
88
+
89
+ return unflatten_dict(flat_params)
90
+
91
+ def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
92
+ r"""
93
+ Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
94
+ the `params` in place.
95
+
96
+ This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full
97
+ half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
98
+
99
+ Arguments:
100
+ params (`Union[Dict, FrozenDict]`):
101
+ A `PyTree` of model parameters.
102
+ mask (`Union[Dict, FrozenDict]`):
103
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
104
+ for params you want to cast, and `False` for those you want to skip.
105
+
106
+ Examples:
107
+
108
+ ```python
109
+ >>> from diffusers import FlaxUNet2DConditionModel
110
+
111
+ >>> # load model
112
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
113
+ >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
114
+ >>> params = model.to_bf16(params)
115
+ >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)
116
+ >>> # then pass the mask as follows
117
+ >>> from flax import traverse_util
118
+
119
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
120
+ >>> flat_params = traverse_util.flatten_dict(params)
121
+ >>> mask = {
122
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
123
+ ... for path in flat_params
124
+ ... }
125
+ >>> mask = traverse_util.unflatten_dict(mask)
126
+ >>> params = model.to_bf16(params, mask)
127
+ ```"""
128
+ return self._cast_floating_to(params, jnp.bfloat16, mask)
129
+
130
+ def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
131
+ r"""
132
+ Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
133
+ model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
134
+
135
+ Arguments:
136
+ params (`Union[Dict, FrozenDict]`):
137
+ A `PyTree` of model parameters.
138
+ mask (`Union[Dict, FrozenDict]`):
139
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
140
+ for params you want to cast, and `False` for those you want to skip.
141
+
142
+ Examples:
143
+
144
+ ```python
145
+ >>> from diffusers import FlaxUNet2DConditionModel
146
+
147
+ >>> # Download model and configuration from huggingface.co
148
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
149
+ >>> # By default, the model params will be in fp32, to illustrate the use of this method,
150
+ >>> # we'll first cast to fp16 and back to fp32
151
+ >>> params = model.to_f16(params)
152
+ >>> # now cast back to fp32
153
+ >>> params = model.to_fp32(params)
154
+ ```"""
155
+ return self._cast_floating_to(params, jnp.float32, mask)
156
+
157
+ def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
158
+ r"""
159
+ Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
160
+ `params` in place.
161
+
162
+ This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full
163
+ half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
164
+
165
+ Arguments:
166
+ params (`Union[Dict, FrozenDict]`):
167
+ A `PyTree` of model parameters.
168
+ mask (`Union[Dict, FrozenDict]`):
169
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
170
+ for params you want to cast, and `False` for those you want to skip.
171
+
172
+ Examples:
173
+
174
+ ```python
175
+ >>> from diffusers import FlaxUNet2DConditionModel
176
+
177
+ >>> # load model
178
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
179
+ >>> # By default, the model params will be in fp32, to cast these to float16
180
+ >>> params = model.to_fp16(params)
181
+ >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
182
+ >>> # then pass the mask as follows
183
+ >>> from flax import traverse_util
184
+
185
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
186
+ >>> flat_params = traverse_util.flatten_dict(params)
187
+ >>> mask = {
188
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
189
+ ... for path in flat_params
190
+ ... }
191
+ >>> mask = traverse_util.unflatten_dict(mask)
192
+ >>> params = model.to_fp16(params, mask)
193
+ ```"""
194
+ return self._cast_floating_to(params, jnp.float16, mask)
195
+
196
+ def init_weights(self, rng: jax.Array) -> Dict:
197
+ raise NotImplementedError(f"init_weights method has to be implemented for {self}")
198
+
199
+ @classmethod
200
+ def from_pretrained(
201
+ cls,
202
+ pretrained_model_name_or_path: Union[str, os.PathLike],
203
+ dtype: jnp.dtype = jnp.float32,
204
+ *model_args,
205
+ **kwargs,
206
+ ):
207
+ r"""
208
+ Instantiate a pretrained Flax model from a pretrained model configuration.
209
+
210
+ Parameters:
211
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
212
+ Can be either:
213
+
214
+ - A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model
215
+ hosted on the Hub.
216
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
217
+ using [`~FlaxModelMixin.save_pretrained`].
218
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
219
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
220
+ `jax.numpy.bfloat16` (on TPUs).
221
+
222
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
223
+ specified, all the computation will be performed with the given `dtype`.
224
+
225
+ <Tip>
226
+
227
+ This only specifies the dtype of the *computation* and does not influence the dtype of model
228
+ parameters.
229
+
230
+ If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and
231
+ [`~FlaxModelMixin.to_bf16`].
232
+
233
+ </Tip>
234
+
235
+ model_args (sequence of positional arguments, *optional*):
236
+ All remaining positional arguments are passed to the underlying model's `__init__` method.
237
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
238
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
239
+ is not used.
240
+ force_download (`bool`, *optional*, defaults to `False`):
241
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
242
+ cached versions if they exist.
243
+ resume_download (`bool`, *optional*, defaults to `False`):
244
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
245
+ incompletely downloaded files are deleted.
246
+ proxies (`Dict[str, str]`, *optional*):
247
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
248
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
249
+ local_files_only(`bool`, *optional*, defaults to `False`):
250
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
251
+ won't be downloaded from the Hub.
252
+ revision (`str`, *optional*, defaults to `"main"`):
253
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
254
+ allowed by Git.
255
+ from_pt (`bool`, *optional*, defaults to `False`):
256
+ Load the model weights from a PyTorch checkpoint save file.
257
+ kwargs (remaining dictionary of keyword arguments, *optional*):
258
+ Can be used to update the configuration object (after it is loaded) and initiate the model (for
259
+ example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
260
+ automatically loaded:
261
+
262
+ - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying
263
+ model's `__init__` method (we assume all relevant updates to the configuration have already been
264
+ done).
265
+ - If a configuration is not provided, `kwargs` are first passed to the configuration class
266
+ initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds
267
+ to a configuration attribute is used to override said attribute with the supplied `kwargs` value.
268
+ Remaining keys that do not correspond to any configuration attribute are passed to the underlying
269
+ model's `__init__` function.
270
+
271
+ Examples:
272
+
273
+ ```python
274
+ >>> from diffusers import FlaxUNet2DConditionModel
275
+
276
+ >>> # Download model and configuration from huggingface.co and cache.
277
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
278
+ >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
279
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")
280
+ ```
281
+
282
+ If you get the error message below, you need to finetune the weights for your downstream task:
283
+
284
+ ```bash
285
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
286
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
287
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
288
+ ```
289
+ """
290
+ config = kwargs.pop("config", None)
291
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
292
+ force_download = kwargs.pop("force_download", False)
293
+ from_pt = kwargs.pop("from_pt", False)
294
+ resume_download = kwargs.pop("resume_download", False)
295
+ proxies = kwargs.pop("proxies", None)
296
+ local_files_only = kwargs.pop("local_files_only", False)
297
+ use_auth_token = kwargs.pop("use_auth_token", None)
298
+ revision = kwargs.pop("revision", None)
299
+ subfolder = kwargs.pop("subfolder", None)
300
+
301
+ user_agent = {
302
+ "diffusers": __version__,
303
+ "file_type": "model",
304
+ "framework": "flax",
305
+ }
306
+
307
+ # Load config if we don't provide one
308
+ if config is None:
309
+ config, unused_kwargs = cls.load_config(
310
+ pretrained_model_name_or_path,
311
+ cache_dir=cache_dir,
312
+ return_unused_kwargs=True,
313
+ force_download=force_download,
314
+ resume_download=resume_download,
315
+ proxies=proxies,
316
+ local_files_only=local_files_only,
317
+ use_auth_token=use_auth_token,
318
+ revision=revision,
319
+ subfolder=subfolder,
320
+ **kwargs,
321
+ )
322
+
323
+ model, model_kwargs = cls.from_config(config, dtype=dtype, return_unused_kwargs=True, **unused_kwargs)
324
+
325
+ # Load model
326
+ pretrained_path_with_subfolder = (
327
+ pretrained_model_name_or_path
328
+ if subfolder is None
329
+ else os.path.join(pretrained_model_name_or_path, subfolder)
330
+ )
331
+ if os.path.isdir(pretrained_path_with_subfolder):
332
+ if from_pt:
333
+ if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
334
+ raise EnvironmentError(
335
+ f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} "
336
+ )
337
+ model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)
338
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):
339
+ # Load from a Flax checkpoint
340
+ model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)
341
+ # Check if pytorch weights exist instead
342
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
343
+ raise EnvironmentError(
344
+ f"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model"
345
+ " using `from_pt=True`."
346
+ )
347
+ else:
348
+ raise EnvironmentError(
349
+ f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
350
+ f"{pretrained_path_with_subfolder}."
351
+ )
352
+ else:
353
+ try:
354
+ model_file = hf_hub_download(
355
+ pretrained_model_name_or_path,
356
+ filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,
357
+ cache_dir=cache_dir,
358
+ force_download=force_download,
359
+ proxies=proxies,
360
+ resume_download=resume_download,
361
+ local_files_only=local_files_only,
362
+ use_auth_token=use_auth_token,
363
+ user_agent=user_agent,
364
+ subfolder=subfolder,
365
+ revision=revision,
366
+ )
367
+
368
+ except RepositoryNotFoundError:
369
+ raise EnvironmentError(
370
+ f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
371
+ "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
372
+ "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
373
+ "login`."
374
+ )
375
+ except RevisionNotFoundError:
376
+ raise EnvironmentError(
377
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
378
+ "this model name. Check the model page at "
379
+ f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
380
+ )
381
+ except EntryNotFoundError:
382
+ raise EnvironmentError(
383
+ f"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}."
384
+ )
385
+ except HTTPError as err:
386
+ raise EnvironmentError(
387
+ f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
388
+ f"{err}"
389
+ )
390
+ except ValueError:
391
+ raise EnvironmentError(
392
+ f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
393
+ f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
394
+ f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your"
395
+ " internet connection or see how to run the library in offline mode at"
396
+ " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
397
+ )
398
+ except EnvironmentError:
399
+ raise EnvironmentError(
400
+ f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
401
+ "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
402
+ f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
403
+ f"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
404
+ )
405
+
406
+ if from_pt:
407
+ if is_torch_available():
408
+ from .modeling_utils import load_state_dict
409
+ else:
410
+ raise EnvironmentError(
411
+ "Can't load the model in PyTorch format because PyTorch is not installed. "
412
+ "Please, install PyTorch or use native Flax weights."
413
+ )
414
+
415
+ # Step 1: Get the pytorch file
416
+ pytorch_model_file = load_state_dict(model_file)
417
+
418
+ # Step 2: Convert the weights
419
+ state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)
420
+ else:
421
+ try:
422
+ with open(model_file, "rb") as state_f:
423
+ state = from_bytes(cls, state_f.read())
424
+ except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
425
+ try:
426
+ with open(model_file) as f:
427
+ if f.read().startswith("version"):
428
+ raise OSError(
429
+ "You seem to have cloned a repository without having git-lfs installed. Please"
430
+ " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
431
+ " folder you cloned."
432
+ )
433
+ else:
434
+ raise ValueError from e
435
+ except (UnicodeDecodeError, ValueError):
436
+ raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
437
+ # make sure all arrays are stored as jnp.ndarray
438
+ # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
439
+ # https://github.com/google/flax/issues/1261
440
+ state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.local_devices(backend="cpu")[0]), state)
441
+
442
+ # flatten dicts
443
+ state = flatten_dict(state)
444
+
445
+ params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))
446
+ required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
447
+
448
+ shape_state = flatten_dict(unfreeze(params_shape_tree))
449
+
450
+ missing_keys = required_params - set(state.keys())
451
+ unexpected_keys = set(state.keys()) - required_params
452
+
453
+ if missing_keys:
454
+ logger.warning(
455
+ f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
456
+ "Make sure to call model.init_weights to initialize the missing weights."
457
+ )
458
+ cls._missing_keys = missing_keys
459
+
460
+ for key in state.keys():
461
+ if key in shape_state and state[key].shape != shape_state[key].shape:
462
+ raise ValueError(
463
+ f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
464
+ f"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. "
465
+ )
466
+
467
+ # remove unexpected keys to not be saved again
468
+ for unexpected_key in unexpected_keys:
469
+ del state[unexpected_key]
470
+
471
+ if len(unexpected_keys) > 0:
472
+ logger.warning(
473
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
474
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
475
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
476
+ " with another architecture."
477
+ )
478
+ else:
479
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
480
+
481
+ if len(missing_keys) > 0:
482
+ logger.warning(
483
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
484
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
485
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
486
+ )
487
+ else:
488
+ logger.info(
489
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
490
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
491
+ f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
492
+ " training."
493
+ )
494
+
495
+ return model, unflatten_dict(state)
496
+
497
+ def save_pretrained(
498
+ self,
499
+ save_directory: Union[str, os.PathLike],
500
+ params: Union[Dict, FrozenDict],
501
+ is_main_process: bool = True,
502
+ push_to_hub: bool = False,
503
+ **kwargs,
504
+ ):
505
+ """
506
+ Save a model and its configuration file to a directory so that it can be reloaded using the
507
+ [`~FlaxModelMixin.from_pretrained`] class method.
508
+
509
+ Arguments:
510
+ save_directory (`str` or `os.PathLike`):
511
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
512
+ params (`Union[Dict, FrozenDict]`):
513
+ A `PyTree` of model parameters.
514
+ is_main_process (`bool`, *optional*, defaults to `True`):
515
+ Whether the process calling this is the main process or not. Useful during distributed training and you
516
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
517
+ process to avoid race conditions.
518
+ push_to_hub (`bool`, *optional*, defaults to `False`):
519
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
520
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
521
+ namespace).
522
+ kwargs (`Dict[str, Any]`, *optional*):
523
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
524
+ """
525
+ if os.path.isfile(save_directory):
526
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
527
+ return
528
+
529
+ os.makedirs(save_directory, exist_ok=True)
530
+
531
+ if push_to_hub:
532
+ commit_message = kwargs.pop("commit_message", None)
533
+ private = kwargs.pop("private", False)
534
+ create_pr = kwargs.pop("create_pr", False)
535
+ token = kwargs.pop("token", None)
536
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
537
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
538
+
539
+ model_to_save = self
540
+
541
+ # Attach architecture to the config
542
+ # Save the config
543
+ if is_main_process:
544
+ model_to_save.save_config(save_directory)
545
+
546
+ # save model
547
+ output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)
548
+ with open(output_model_file, "wb") as f:
549
+ model_bytes = to_bytes(params)
550
+ f.write(model_bytes)
551
+
552
+ logger.info(f"Model weights saved in {output_model_file}")
553
+
554
+ if push_to_hub:
555
+ self._upload_folder(
556
+ save_directory,
557
+ repo_id,
558
+ token=token,
559
+ commit_message=commit_message,
560
+ create_pr=create_pr,
561
+ )
diffusers/models/modeling_outputs.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from ..utils import BaseOutput
4
+
5
+
6
+ @dataclass
7
+ class AutoencoderKLOutput(BaseOutput):
8
+ """
9
+ Output of AutoencoderKL encoding method.
10
+
11
+ Args:
12
+ latent_dist (`DiagonalGaussianDistribution`):
13
+ Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
14
+ `DiagonalGaussianDistribution` allows for sampling latents from the distribution.
15
+ """
16
+
17
+ latent_dist: "DiagonalGaussianDistribution" # noqa: F821
diffusers/models/modeling_pytorch_flax_utils.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """ PyTorch - Flax general utilities."""
16
+
17
+ from pickle import UnpicklingError
18
+
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+ from flax.serialization import from_bytes
23
+ from flax.traverse_util import flatten_dict
24
+
25
+ from ..utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ #####################
32
+ # Flax => PyTorch #
33
+ #####################
34
+
35
+
36
+ # from https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_flax_pytorch_utils.py#L224-L352
37
+ def load_flax_checkpoint_in_pytorch_model(pt_model, model_file):
38
+ try:
39
+ with open(model_file, "rb") as flax_state_f:
40
+ flax_state = from_bytes(None, flax_state_f.read())
41
+ except UnpicklingError as e:
42
+ try:
43
+ with open(model_file) as f:
44
+ if f.read().startswith("version"):
45
+ raise OSError(
46
+ "You seem to have cloned a repository without having git-lfs installed. Please"
47
+ " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
48
+ " folder you cloned."
49
+ )
50
+ else:
51
+ raise ValueError from e
52
+ except (UnicodeDecodeError, ValueError):
53
+ raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
54
+
55
+ return load_flax_weights_in_pytorch_model(pt_model, flax_state)
56
+
57
+
58
+ def load_flax_weights_in_pytorch_model(pt_model, flax_state):
59
+ """Load flax checkpoints in a PyTorch model"""
60
+
61
+ try:
62
+ import torch # noqa: F401
63
+ except ImportError:
64
+ logger.error(
65
+ "Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see"
66
+ " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation"
67
+ " instructions."
68
+ )
69
+ raise
70
+
71
+ # check if we have bf16 weights
72
+ is_type_bf16 = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype == jnp.bfloat16, flax_state)).values()
73
+ if any(is_type_bf16):
74
+ # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16
75
+
76
+ # and bf16 is not fully supported in PT yet.
77
+ logger.warning(
78
+ "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` "
79
+ "before loading those in PyTorch model."
80
+ )
81
+ flax_state = jax.tree_util.tree_map(
82
+ lambda params: params.astype(np.float32) if params.dtype == jnp.bfloat16 else params, flax_state
83
+ )
84
+
85
+ pt_model.base_model_prefix = ""
86
+
87
+ flax_state_dict = flatten_dict(flax_state, sep=".")
88
+ pt_model_dict = pt_model.state_dict()
89
+
90
+ # keep track of unexpected & missing keys
91
+ unexpected_keys = []
92
+ missing_keys = set(pt_model_dict.keys())
93
+
94
+ for flax_key_tuple, flax_tensor in flax_state_dict.items():
95
+ flax_key_tuple_array = flax_key_tuple.split(".")
96
+
97
+ if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
98
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
99
+ flax_tensor = jnp.transpose(flax_tensor, (3, 2, 0, 1))
100
+ elif flax_key_tuple_array[-1] == "kernel":
101
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
102
+ flax_tensor = flax_tensor.T
103
+ elif flax_key_tuple_array[-1] == "scale":
104
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
105
+
106
+ if "time_embedding" not in flax_key_tuple_array:
107
+ for i, flax_key_tuple_string in enumerate(flax_key_tuple_array):
108
+ flax_key_tuple_array[i] = (
109
+ flax_key_tuple_string.replace("_0", ".0")
110
+ .replace("_1", ".1")
111
+ .replace("_2", ".2")
112
+ .replace("_3", ".3")
113
+ .replace("_4", ".4")
114
+ .replace("_5", ".5")
115
+ .replace("_6", ".6")
116
+ .replace("_7", ".7")
117
+ .replace("_8", ".8")
118
+ .replace("_9", ".9")
119
+ )
120
+
121
+ flax_key = ".".join(flax_key_tuple_array)
122
+
123
+ if flax_key in pt_model_dict:
124
+ if flax_tensor.shape != pt_model_dict[flax_key].shape:
125
+ raise ValueError(
126
+ f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected "
127
+ f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."
128
+ )
129
+ else:
130
+ # add weight to pytorch dict
131
+ flax_tensor = np.asarray(flax_tensor) if not isinstance(flax_tensor, np.ndarray) else flax_tensor
132
+ pt_model_dict[flax_key] = torch.from_numpy(flax_tensor)
133
+ # remove from missing keys
134
+ missing_keys.remove(flax_key)
135
+ else:
136
+ # weight is not expected by PyTorch model
137
+ unexpected_keys.append(flax_key)
138
+
139
+ pt_model.load_state_dict(pt_model_dict)
140
+
141
+ # re-transform missing_keys to list
142
+ missing_keys = list(missing_keys)
143
+
144
+ if len(unexpected_keys) > 0:
145
+ logger.warning(
146
+ "Some weights of the Flax model were not used when initializing the PyTorch model"
147
+ f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
148
+ f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"
149
+ " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This"
150
+ f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"
151
+ " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a"
152
+ " FlaxBertForSequenceClassification model)."
153
+ )
154
+ if len(missing_keys) > 0:
155
+ logger.warning(
156
+ f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"
157
+ f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"
158
+ " use it for predictions and inference."
159
+ )
160
+
161
+ return pt_model
diffusers/models/modeling_utils.py ADDED
@@ -0,0 +1,1166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+
17
+ import inspect
18
+ import itertools
19
+ import os
20
+ import re
21
+ from collections import OrderedDict
22
+ from functools import partial
23
+ from typing import Any, Callable, List, Optional, Tuple, Union
24
+
25
+ import safetensors
26
+ import torch
27
+ from huggingface_hub import create_repo
28
+ from torch import Tensor, nn
29
+
30
+ from .. import __version__
31
+ from ..utils import (
32
+ CONFIG_NAME,
33
+ DIFFUSERS_CACHE,
34
+ FLAX_WEIGHTS_NAME,
35
+ HF_HUB_OFFLINE,
36
+ MIN_PEFT_VERSION,
37
+ SAFETENSORS_WEIGHTS_NAME,
38
+ WEIGHTS_NAME,
39
+ _add_variant,
40
+ _get_model_file,
41
+ check_peft_version,
42
+ deprecate,
43
+ is_accelerate_available,
44
+ is_torch_version,
45
+ logging,
46
+ )
47
+ from ..utils.hub_utils import PushToHubMixin
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+
53
+ if is_torch_version(">=", "1.9.0"):
54
+ _LOW_CPU_MEM_USAGE_DEFAULT = True
55
+ else:
56
+ _LOW_CPU_MEM_USAGE_DEFAULT = False
57
+
58
+
59
+ if is_accelerate_available():
60
+ import accelerate
61
+ from accelerate.utils import set_module_tensor_to_device
62
+ from accelerate.utils.versions import is_torch_version
63
+
64
+
65
+ def get_parameter_device(parameter: torch.nn.Module) -> torch.device:
66
+ try:
67
+ parameters_and_buffers = itertools.chain(parameter.parameters(), parameter.buffers())
68
+ return next(parameters_and_buffers).device
69
+ except StopIteration:
70
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
71
+
72
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
73
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
74
+ return tuples
75
+
76
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
77
+ first_tuple = next(gen)
78
+ return first_tuple[1].device
79
+
80
+
81
+ def get_parameter_dtype(parameter: torch.nn.Module) -> torch.dtype:
82
+ try:
83
+ params = tuple(parameter.parameters())
84
+ if len(params) > 0:
85
+ return params[0].dtype
86
+
87
+ buffers = tuple(parameter.buffers())
88
+ if len(buffers) > 0:
89
+ return buffers[0].dtype
90
+
91
+ except StopIteration:
92
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
93
+
94
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
95
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
96
+ return tuples
97
+
98
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
99
+ first_tuple = next(gen)
100
+ return first_tuple[1].dtype
101
+
102
+
103
+ def load_state_dict(checkpoint_file: Union[str, os.PathLike], variant: Optional[str] = None):
104
+ """
105
+ Reads a checkpoint file, returning properly formatted errors if they arise.
106
+ """
107
+ try:
108
+ if os.path.basename(checkpoint_file) == _add_variant(WEIGHTS_NAME, variant):
109
+ return torch.load(checkpoint_file, map_location="cpu")
110
+ else:
111
+ return safetensors.torch.load_file(checkpoint_file, device="cpu")
112
+ except Exception as e:
113
+ try:
114
+ with open(checkpoint_file) as f:
115
+ if f.read().startswith("version"):
116
+ raise OSError(
117
+ "You seem to have cloned a repository without having git-lfs installed. Please install "
118
+ "git-lfs and run `git lfs install` followed by `git lfs pull` in the folder "
119
+ "you cloned."
120
+ )
121
+ else:
122
+ raise ValueError(
123
+ f"Unable to locate the file {checkpoint_file} which is necessary to load this pretrained "
124
+ "model. Make sure you have saved the model properly."
125
+ ) from e
126
+ except (UnicodeDecodeError, ValueError):
127
+ raise OSError(
128
+ f"Unable to load weights from checkpoint file for '{checkpoint_file}' "
129
+ f"at '{checkpoint_file}'. "
130
+ "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True."
131
+ )
132
+
133
+
134
+ def load_model_dict_into_meta(
135
+ model,
136
+ state_dict: OrderedDict,
137
+ device: Optional[Union[str, torch.device]] = None,
138
+ dtype: Optional[Union[str, torch.dtype]] = None,
139
+ model_name_or_path: Optional[str] = None,
140
+ ) -> List[str]:
141
+ device = device or torch.device("cpu")
142
+ dtype = dtype or torch.float32
143
+
144
+ accepts_dtype = "dtype" in set(inspect.signature(set_module_tensor_to_device).parameters.keys())
145
+
146
+ unexpected_keys = []
147
+ empty_state_dict = model.state_dict()
148
+ for param_name, param in state_dict.items():
149
+ if param_name not in empty_state_dict:
150
+ unexpected_keys.append(param_name)
151
+ continue
152
+
153
+ if empty_state_dict[param_name].shape != param.shape:
154
+ model_name_or_path_str = f"{model_name_or_path} " if model_name_or_path is not None else ""
155
+ raise ValueError(
156
+ f"Cannot load {model_name_or_path_str}because {param_name} expected shape {empty_state_dict[param_name]}, but got {param.shape}. If you want to instead overwrite randomly initialized weights, please make sure to pass both `low_cpu_mem_usage=False` and `ignore_mismatched_sizes=True`. For more information, see also: https://github.com/huggingface/diffusers/issues/1619#issuecomment-1345604389 as an example."
157
+ )
158
+
159
+ if accepts_dtype:
160
+ set_module_tensor_to_device(model, param_name, device, value=param, dtype=dtype)
161
+ else:
162
+ set_module_tensor_to_device(model, param_name, device, value=param)
163
+ return unexpected_keys
164
+
165
+
166
+ def _load_state_dict_into_model(model_to_load, state_dict: OrderedDict) -> List[str]:
167
+ # Convert old format to new format if needed from a PyTorch state_dict
168
+ # copy state_dict so _load_from_state_dict can modify it
169
+ state_dict = state_dict.copy()
170
+ error_msgs = []
171
+
172
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
173
+ # so we need to apply the function recursively.
174
+ def load(module: torch.nn.Module, prefix: str = ""):
175
+ args = (state_dict, prefix, {}, True, [], [], error_msgs)
176
+ module._load_from_state_dict(*args)
177
+
178
+ for name, child in module._modules.items():
179
+ if child is not None:
180
+ load(child, prefix + name + ".")
181
+
182
+ load(model_to_load)
183
+
184
+ return error_msgs
185
+
186
+
187
+ class ModelMixin(torch.nn.Module, PushToHubMixin):
188
+ r"""
189
+ Base class for all models.
190
+
191
+ [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
192
+ saving models.
193
+
194
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].
195
+ """
196
+
197
+ config_name = CONFIG_NAME
198
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
199
+ _supports_gradient_checkpointing = False
200
+ _keys_to_ignore_on_load_unexpected = None
201
+ _hf_peft_config_loaded = False
202
+
203
+ def __init__(self):
204
+ super().__init__()
205
+
206
+ def __getattr__(self, name: str) -> Any:
207
+ """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
208
+ config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite
209
+ __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':
210
+ https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
211
+ """
212
+
213
+ is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
214
+ is_attribute = name in self.__dict__
215
+
216
+ if is_in_config and not is_attribute:
217
+ 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. 'unet.config.{name}'."
218
+ deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False, stacklevel=3)
219
+ return self._internal_dict[name]
220
+
221
+ # call PyTorch's https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
222
+ return super().__getattr__(name)
223
+
224
+ @property
225
+ def is_gradient_checkpointing(self) -> bool:
226
+ """
227
+ Whether gradient checkpointing is activated for this model or not.
228
+ """
229
+ return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())
230
+
231
+ def enable_gradient_checkpointing(self) -> None:
232
+ """
233
+ Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
234
+ *checkpoint activations* in other frameworks).
235
+ """
236
+ if not self._supports_gradient_checkpointing:
237
+ raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.")
238
+ self.apply(partial(self._set_gradient_checkpointing, value=True))
239
+
240
+ def disable_gradient_checkpointing(self) -> None:
241
+ """
242
+ Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
243
+ *checkpoint activations* in other frameworks).
244
+ """
245
+ if self._supports_gradient_checkpointing:
246
+ self.apply(partial(self._set_gradient_checkpointing, value=False))
247
+
248
+ def set_use_memory_efficient_attention_xformers(
249
+ self, valid: bool, attention_op: Optional[Callable] = None
250
+ ) -> None:
251
+ # Recursively walk through all the children.
252
+ # Any children which exposes the set_use_memory_efficient_attention_xformers method
253
+ # gets the message
254
+ def fn_recursive_set_mem_eff(module: torch.nn.Module):
255
+ if hasattr(module, "set_use_memory_efficient_attention_xformers"):
256
+ module.set_use_memory_efficient_attention_xformers(valid, attention_op)
257
+
258
+ for child in module.children():
259
+ fn_recursive_set_mem_eff(child)
260
+
261
+ for module in self.children():
262
+ if isinstance(module, torch.nn.Module):
263
+ fn_recursive_set_mem_eff(module)
264
+
265
+ def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None) -> None:
266
+ r"""
267
+ Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
268
+
269
+ When this option is enabled, you should observe lower GPU memory usage and a potential speed up during
270
+ inference. Speed up during training is not guaranteed.
271
+
272
+ <Tip warning={true}>
273
+
274
+ ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
275
+ precedent.
276
+
277
+ </Tip>
278
+
279
+ Parameters:
280
+ attention_op (`Callable`, *optional*):
281
+ Override the default `None` operator for use as `op` argument to the
282
+ [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
283
+ function of xFormers.
284
+
285
+ Examples:
286
+
287
+ ```py
288
+ >>> import torch
289
+ >>> from diffusers import UNet2DConditionModel
290
+ >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
291
+
292
+ >>> model = UNet2DConditionModel.from_pretrained(
293
+ ... "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
294
+ ... )
295
+ >>> model = model.to("cuda")
296
+ >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
297
+ ```
298
+ """
299
+ self.set_use_memory_efficient_attention_xformers(True, attention_op)
300
+
301
+ def disable_xformers_memory_efficient_attention(self) -> None:
302
+ r"""
303
+ Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
304
+ """
305
+ self.set_use_memory_efficient_attention_xformers(False)
306
+
307
+ def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
308
+ r"""
309
+ Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
310
+ to the adapter to follow the convention of the PEFT library.
311
+
312
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
313
+ [documentation](https://huggingface.co/docs/peft).
314
+
315
+ Args:
316
+ adapter_config (`[~peft.PeftConfig]`):
317
+ The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
318
+ methods.
319
+ adapter_name (`str`, *optional*, defaults to `"default"`):
320
+ The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
321
+ """
322
+ check_peft_version(min_version=MIN_PEFT_VERSION)
323
+
324
+ from peft import PeftConfig, inject_adapter_in_model
325
+
326
+ if not self._hf_peft_config_loaded:
327
+ self._hf_peft_config_loaded = True
328
+ elif adapter_name in self.peft_config:
329
+ raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
330
+
331
+ if not isinstance(adapter_config, PeftConfig):
332
+ raise ValueError(
333
+ f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
334
+ )
335
+
336
+ # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
337
+ # handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.
338
+ adapter_config.base_model_name_or_path = None
339
+ inject_adapter_in_model(adapter_config, self, adapter_name)
340
+ self.set_adapter(adapter_name)
341
+
342
+ def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
343
+ """
344
+ Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
345
+
346
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
347
+ official documentation: https://huggingface.co/docs/peft
348
+
349
+ Args:
350
+ adapter_name (Union[str, List[str]])):
351
+ The list of adapters to set or the adapter name in case of single adapter.
352
+ """
353
+ check_peft_version(min_version=MIN_PEFT_VERSION)
354
+
355
+ if not self._hf_peft_config_loaded:
356
+ raise ValueError("No adapter loaded. Please load an adapter first.")
357
+
358
+ if isinstance(adapter_name, str):
359
+ adapter_name = [adapter_name]
360
+
361
+ missing = set(adapter_name) - set(self.peft_config)
362
+ if len(missing) > 0:
363
+ raise ValueError(
364
+ f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
365
+ f" current loaded adapters are: {list(self.peft_config.keys())}"
366
+ )
367
+
368
+ from peft.tuners.tuners_utils import BaseTunerLayer
369
+
370
+ _adapters_has_been_set = False
371
+
372
+ for _, module in self.named_modules():
373
+ if isinstance(module, BaseTunerLayer):
374
+ if hasattr(module, "set_adapter"):
375
+ module.set_adapter(adapter_name)
376
+ # Previous versions of PEFT does not support multi-adapter inference
377
+ elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
378
+ raise ValueError(
379
+ "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."
380
+ " `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
381
+ )
382
+ else:
383
+ module.active_adapter = adapter_name
384
+ _adapters_has_been_set = True
385
+
386
+ if not _adapters_has_been_set:
387
+ raise ValueError(
388
+ "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
389
+ )
390
+
391
+ def disable_adapters(self) -> None:
392
+ r"""
393
+ Disable all adapters attached to the model and fallback to inference with the base model only.
394
+
395
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
396
+ official documentation: https://huggingface.co/docs/peft
397
+ """
398
+ check_peft_version(min_version=MIN_PEFT_VERSION)
399
+
400
+ if not self._hf_peft_config_loaded:
401
+ raise ValueError("No adapter loaded. Please load an adapter first.")
402
+
403
+ from peft.tuners.tuners_utils import BaseTunerLayer
404
+
405
+ for _, module in self.named_modules():
406
+ if isinstance(module, BaseTunerLayer):
407
+ if hasattr(module, "enable_adapters"):
408
+ module.enable_adapters(enabled=False)
409
+ else:
410
+ # support for older PEFT versions
411
+ module.disable_adapters = True
412
+
413
+ def enable_adapters(self) -> None:
414
+ """
415
+ Enable adapters that are attached to the model. The model will use `self.active_adapters()` to retrieve the
416
+ list of adapters to enable.
417
+
418
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
419
+ official documentation: https://huggingface.co/docs/peft
420
+ """
421
+ check_peft_version(min_version=MIN_PEFT_VERSION)
422
+
423
+ if not self._hf_peft_config_loaded:
424
+ raise ValueError("No adapter loaded. Please load an adapter first.")
425
+
426
+ from peft.tuners.tuners_utils import BaseTunerLayer
427
+
428
+ for _, module in self.named_modules():
429
+ if isinstance(module, BaseTunerLayer):
430
+ if hasattr(module, "enable_adapters"):
431
+ module.enable_adapters(enabled=True)
432
+ else:
433
+ # support for older PEFT versions
434
+ module.disable_adapters = False
435
+
436
+ def active_adapters(self) -> List[str]:
437
+ """
438
+ Gets the current list of active adapters of the model.
439
+
440
+ If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
441
+ official documentation: https://huggingface.co/docs/peft
442
+ """
443
+ check_peft_version(min_version=MIN_PEFT_VERSION)
444
+
445
+ if not self._hf_peft_config_loaded:
446
+ raise ValueError("No adapter loaded. Please load an adapter first.")
447
+
448
+ from peft.tuners.tuners_utils import BaseTunerLayer
449
+
450
+ for _, module in self.named_modules():
451
+ if isinstance(module, BaseTunerLayer):
452
+ return module.active_adapter
453
+
454
+ def save_pretrained(
455
+ self,
456
+ save_directory: Union[str, os.PathLike],
457
+ is_main_process: bool = True,
458
+ save_function: Optional[Callable] = None,
459
+ safe_serialization: bool = True,
460
+ variant: Optional[str] = None,
461
+ push_to_hub: bool = False,
462
+ **kwargs,
463
+ ):
464
+ """
465
+ Save a model and its configuration file to a directory so that it can be reloaded using the
466
+ [`~models.ModelMixin.from_pretrained`] class method.
467
+
468
+ Arguments:
469
+ save_directory (`str` or `os.PathLike`):
470
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
471
+ is_main_process (`bool`, *optional*, defaults to `True`):
472
+ Whether the process calling this is the main process or not. Useful during distributed training and you
473
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
474
+ process to avoid race conditions.
475
+ save_function (`Callable`):
476
+ The function to use to save the state dictionary. Useful during distributed training when you need to
477
+ replace `torch.save` with another method. Can be configured with the environment variable
478
+ `DIFFUSERS_SAVE_MODE`.
479
+ safe_serialization (`bool`, *optional*, defaults to `True`):
480
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
481
+ variant (`str`, *optional*):
482
+ If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
483
+ push_to_hub (`bool`, *optional*, defaults to `False`):
484
+ Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
485
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
486
+ namespace).
487
+ kwargs (`Dict[str, Any]`, *optional*):
488
+ Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
489
+ """
490
+ if os.path.isfile(save_directory):
491
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
492
+ return
493
+
494
+ os.makedirs(save_directory, exist_ok=True)
495
+
496
+ if push_to_hub:
497
+ commit_message = kwargs.pop("commit_message", None)
498
+ private = kwargs.pop("private", False)
499
+ create_pr = kwargs.pop("create_pr", False)
500
+ token = kwargs.pop("token", None)
501
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
502
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
503
+
504
+ # Only save the model itself if we are using distributed training
505
+ model_to_save = self
506
+
507
+ # Attach architecture to the config
508
+ # Save the config
509
+ if is_main_process:
510
+ model_to_save.save_config(save_directory)
511
+
512
+ # Save the model
513
+ state_dict = model_to_save.state_dict()
514
+
515
+ weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
516
+ weights_name = _add_variant(weights_name, variant)
517
+
518
+ # Save the model
519
+ if safe_serialization:
520
+ safetensors.torch.save_file(
521
+ state_dict, os.path.join(save_directory, weights_name), metadata={"format": "pt"}
522
+ )
523
+ else:
524
+ torch.save(state_dict, os.path.join(save_directory, weights_name))
525
+
526
+ logger.info(f"Model weights saved in {os.path.join(save_directory, weights_name)}")
527
+
528
+ if push_to_hub:
529
+ self._upload_folder(
530
+ save_directory,
531
+ repo_id,
532
+ token=token,
533
+ commit_message=commit_message,
534
+ create_pr=create_pr,
535
+ )
536
+
537
+ @classmethod
538
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
539
+ r"""
540
+ Instantiate a pretrained PyTorch model from a pretrained model configuration.
541
+
542
+ The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To
543
+ train the model, set it back in training mode with `model.train()`.
544
+
545
+ Parameters:
546
+ pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
547
+ Can be either:
548
+
549
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
550
+ the Hub.
551
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
552
+ with [`~ModelMixin.save_pretrained`].
553
+
554
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
555
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
556
+ is not used.
557
+ torch_dtype (`str` or `torch.dtype`, *optional*):
558
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
559
+ dtype is automatically derived from the model's weights.
560
+ force_download (`bool`, *optional*, defaults to `False`):
561
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
562
+ cached versions if they exist.
563
+ resume_download (`bool`, *optional*, defaults to `False`):
564
+ Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
565
+ incompletely downloaded files are deleted.
566
+ proxies (`Dict[str, str]`, *optional*):
567
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
568
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
569
+ output_loading_info (`bool`, *optional*, defaults to `False`):
570
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
571
+ local_files_only(`bool`, *optional*, defaults to `False`):
572
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
573
+ won't be downloaded from the Hub.
574
+ use_auth_token (`str` or *bool*, *optional*):
575
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
576
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
577
+ revision (`str`, *optional*, defaults to `"main"`):
578
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
579
+ allowed by Git.
580
+ from_flax (`bool`, *optional*, defaults to `False`):
581
+ Load the model weights from a Flax checkpoint save file.
582
+ subfolder (`str`, *optional*, defaults to `""`):
583
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
584
+ mirror (`str`, *optional*):
585
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
586
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
587
+ information.
588
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
589
+ A map that specifies where each submodule should go. It doesn't need to be defined for each
590
+ parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
591
+ same device.
592
+
593
+ Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
594
+ more information about each option see [designing a device
595
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
596
+ max_memory (`Dict`, *optional*):
597
+ A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
598
+ each GPU and the available CPU RAM if unset.
599
+ offload_folder (`str` or `os.PathLike`, *optional*):
600
+ The path to offload weights if `device_map` contains the value `"disk"`.
601
+ offload_state_dict (`bool`, *optional*):
602
+ If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
603
+ the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
604
+ when there is some disk offload.
605
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
606
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
607
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
608
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
609
+ argument to `True` will raise an error.
610
+ variant (`str`, *optional*):
611
+ Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when
612
+ loading `from_flax`.
613
+ use_safetensors (`bool`, *optional*, defaults to `None`):
614
+ If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the
615
+ `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`
616
+ weights. If set to `False`, `safetensors` weights are not loaded.
617
+
618
+ <Tip>
619
+
620
+ To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
621
+ `huggingface-cli login`. You can also activate the special
622
+ ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
623
+ firewalled environment.
624
+
625
+ </Tip>
626
+
627
+ Example:
628
+
629
+ ```py
630
+ from diffusers import UNet2DConditionModel
631
+
632
+ unet = UNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet")
633
+ ```
634
+
635
+ If you get the error message below, you need to finetune the weights for your downstream task:
636
+
637
+ ```bash
638
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
639
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
640
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
641
+ ```
642
+ """
643
+ cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE)
644
+ ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
645
+ force_download = kwargs.pop("force_download", False)
646
+ from_flax = kwargs.pop("from_flax", False)
647
+ resume_download = kwargs.pop("resume_download", False)
648
+ proxies = kwargs.pop("proxies", None)
649
+ output_loading_info = kwargs.pop("output_loading_info", False)
650
+ local_files_only = kwargs.pop("local_files_only", HF_HUB_OFFLINE)
651
+ use_auth_token = kwargs.pop("use_auth_token", None)
652
+ revision = kwargs.pop("revision", None)
653
+ torch_dtype = kwargs.pop("torch_dtype", None)
654
+ subfolder = kwargs.pop("subfolder", None)
655
+ device_map = kwargs.pop("device_map", None)
656
+ max_memory = kwargs.pop("max_memory", None)
657
+ offload_folder = kwargs.pop("offload_folder", None)
658
+ offload_state_dict = kwargs.pop("offload_state_dict", False)
659
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
660
+ variant = kwargs.pop("variant", None)
661
+ use_safetensors = kwargs.pop("use_safetensors", None)
662
+
663
+ allow_pickle = False
664
+ if use_safetensors is None:
665
+ use_safetensors = True
666
+ allow_pickle = True
667
+
668
+ if low_cpu_mem_usage and not is_accelerate_available():
669
+ low_cpu_mem_usage = False
670
+ logger.warning(
671
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
672
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
673
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
674
+ " install accelerate\n```\n."
675
+ )
676
+
677
+ if device_map is not None and not is_accelerate_available():
678
+ raise NotImplementedError(
679
+ "Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set"
680
+ " `device_map=None`. You can install accelerate with `pip install accelerate`."
681
+ )
682
+
683
+ # Check if we can handle device_map and dispatching the weights
684
+ if device_map is not None and not is_torch_version(">=", "1.9.0"):
685
+ raise NotImplementedError(
686
+ "Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
687
+ " `device_map=None`."
688
+ )
689
+
690
+ if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
691
+ raise NotImplementedError(
692
+ "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
693
+ " `low_cpu_mem_usage=False`."
694
+ )
695
+
696
+ if low_cpu_mem_usage is False and device_map is not None:
697
+ raise ValueError(
698
+ f"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and"
699
+ " dispatching. Please make sure to set `low_cpu_mem_usage=True`."
700
+ )
701
+
702
+ # Load config if we don't provide a configuration
703
+ config_path = pretrained_model_name_or_path
704
+
705
+ user_agent = {
706
+ "diffusers": __version__,
707
+ "file_type": "model",
708
+ "framework": "pytorch",
709
+ }
710
+
711
+ # load config
712
+ config, unused_kwargs, commit_hash = cls.load_config(
713
+ config_path,
714
+ cache_dir=cache_dir,
715
+ return_unused_kwargs=True,
716
+ return_commit_hash=True,
717
+ force_download=force_download,
718
+ resume_download=resume_download,
719
+ proxies=proxies,
720
+ local_files_only=local_files_only,
721
+ use_auth_token=use_auth_token,
722
+ revision=revision,
723
+ subfolder=subfolder,
724
+ device_map=device_map,
725
+ max_memory=max_memory,
726
+ offload_folder=offload_folder,
727
+ offload_state_dict=offload_state_dict,
728
+ user_agent=user_agent,
729
+ **kwargs,
730
+ )
731
+
732
+ # load model
733
+ model_file = None
734
+ if from_flax:
735
+ model_file = _get_model_file(
736
+ pretrained_model_name_or_path,
737
+ weights_name=FLAX_WEIGHTS_NAME,
738
+ cache_dir=cache_dir,
739
+ force_download=force_download,
740
+ resume_download=resume_download,
741
+ proxies=proxies,
742
+ local_files_only=local_files_only,
743
+ use_auth_token=use_auth_token,
744
+ revision=revision,
745
+ subfolder=subfolder,
746
+ user_agent=user_agent,
747
+ commit_hash=commit_hash,
748
+ )
749
+ model = cls.from_config(config, **unused_kwargs)
750
+
751
+ # Convert the weights
752
+ from .modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model
753
+
754
+ model = load_flax_checkpoint_in_pytorch_model(model, model_file)
755
+ else:
756
+ if use_safetensors:
757
+ try:
758
+ model_file = _get_model_file(
759
+ pretrained_model_name_or_path,
760
+ weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),
761
+ cache_dir=cache_dir,
762
+ force_download=force_download,
763
+ resume_download=resume_download,
764
+ proxies=proxies,
765
+ local_files_only=local_files_only,
766
+ use_auth_token=use_auth_token,
767
+ revision=revision,
768
+ subfolder=subfolder,
769
+ user_agent=user_agent,
770
+ commit_hash=commit_hash,
771
+ )
772
+ except IOError as e:
773
+ if not allow_pickle:
774
+ raise e
775
+ pass
776
+ if model_file is None:
777
+ model_file = _get_model_file(
778
+ pretrained_model_name_or_path,
779
+ weights_name=_add_variant(WEIGHTS_NAME, variant),
780
+ cache_dir=cache_dir,
781
+ force_download=force_download,
782
+ resume_download=resume_download,
783
+ proxies=proxies,
784
+ local_files_only=local_files_only,
785
+ use_auth_token=use_auth_token,
786
+ revision=revision,
787
+ subfolder=subfolder,
788
+ user_agent=user_agent,
789
+ commit_hash=commit_hash,
790
+ )
791
+
792
+ if low_cpu_mem_usage:
793
+ # Instantiate model with empty weights
794
+ with accelerate.init_empty_weights():
795
+ model = cls.from_config(config, **unused_kwargs)
796
+
797
+ # if device_map is None, load the state dict and move the params from meta device to the cpu
798
+ if device_map is None:
799
+ param_device = "cpu"
800
+ state_dict = load_state_dict(model_file, variant=variant)
801
+ model._convert_deprecated_attention_blocks(state_dict)
802
+ # move the params from meta device to cpu
803
+ missing_keys = set(model.state_dict().keys()) - set(state_dict.keys())
804
+ if len(missing_keys) > 0:
805
+ raise ValueError(
806
+ f"Cannot load {cls} from {pretrained_model_name_or_path} because the following keys are"
807
+ f" missing: \n {', '.join(missing_keys)}. \n Please make sure to pass"
808
+ " `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize"
809
+ " those weights or else make sure your checkpoint file is correct."
810
+ )
811
+
812
+ unexpected_keys = load_model_dict_into_meta(
813
+ model,
814
+ state_dict,
815
+ device=param_device,
816
+ dtype=torch_dtype,
817
+ model_name_or_path=pretrained_model_name_or_path,
818
+ )
819
+
820
+ if cls._keys_to_ignore_on_load_unexpected is not None:
821
+ for pat in cls._keys_to_ignore_on_load_unexpected:
822
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
823
+
824
+ if len(unexpected_keys) > 0:
825
+ logger.warn(
826
+ f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
827
+ )
828
+
829
+ else: # else let accelerate handle loading and dispatching.
830
+ # Load weights and dispatch according to the device_map
831
+ # by default the device_map is None and the weights are loaded on the CPU
832
+ try:
833
+ accelerate.load_checkpoint_and_dispatch(
834
+ model,
835
+ model_file,
836
+ device_map,
837
+ max_memory=max_memory,
838
+ offload_folder=offload_folder,
839
+ offload_state_dict=offload_state_dict,
840
+ dtype=torch_dtype,
841
+ )
842
+ except AttributeError as e:
843
+ # When using accelerate loading, we do not have the ability to load the state
844
+ # dict and rename the weight names manually. Additionally, accelerate skips
845
+ # torch loading conventions and directly writes into `module.{_buffers, _parameters}`
846
+ # (which look like they should be private variables?), so we can't use the standard hooks
847
+ # to rename parameters on load. We need to mimic the original weight names so the correct
848
+ # attributes are available. After we have loaded the weights, we convert the deprecated
849
+ # names to the new non-deprecated names. Then we _greatly encourage_ the user to convert
850
+ # the weights so we don't have to do this again.
851
+
852
+ if "'Attention' object has no attribute" in str(e):
853
+ logger.warn(
854
+ f"Taking `{str(e)}` while using `accelerate.load_checkpoint_and_dispatch` to mean {pretrained_model_name_or_path}"
855
+ " was saved with deprecated attention block weight names. We will load it with the deprecated attention block"
856
+ " names and convert them on the fly to the new attention block format. Please re-save the model after this conversion,"
857
+ " so we don't have to do the on the fly renaming in the future. If the model is from a hub checkpoint,"
858
+ " please also re-upload it or open a PR on the original repository."
859
+ )
860
+ model._temp_convert_self_to_deprecated_attention_blocks()
861
+ accelerate.load_checkpoint_and_dispatch(
862
+ model,
863
+ model_file,
864
+ device_map,
865
+ max_memory=max_memory,
866
+ offload_folder=offload_folder,
867
+ offload_state_dict=offload_state_dict,
868
+ dtype=torch_dtype,
869
+ )
870
+ model._undo_temp_convert_self_to_deprecated_attention_blocks()
871
+ else:
872
+ raise e
873
+
874
+ loading_info = {
875
+ "missing_keys": [],
876
+ "unexpected_keys": [],
877
+ "mismatched_keys": [],
878
+ "error_msgs": [],
879
+ }
880
+ else:
881
+ model = cls.from_config(config, **unused_kwargs)
882
+
883
+ state_dict = load_state_dict(model_file, variant=variant)
884
+ model._convert_deprecated_attention_blocks(state_dict)
885
+
886
+ model, missing_keys, unexpected_keys, mismatched_keys, error_msgs = cls._load_pretrained_model(
887
+ model,
888
+ state_dict,
889
+ model_file,
890
+ pretrained_model_name_or_path,
891
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
892
+ )
893
+
894
+ loading_info = {
895
+ "missing_keys": missing_keys,
896
+ "unexpected_keys": unexpected_keys,
897
+ "mismatched_keys": mismatched_keys,
898
+ "error_msgs": error_msgs,
899
+ }
900
+
901
+ if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):
902
+ raise ValueError(
903
+ f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."
904
+ )
905
+ elif torch_dtype is not None:
906
+ model = model.to(torch_dtype)
907
+
908
+ model.register_to_config(_name_or_path=pretrained_model_name_or_path)
909
+
910
+ # Set model in evaluation mode to deactivate DropOut modules by default
911
+ model.eval()
912
+ if output_loading_info:
913
+ return model, loading_info
914
+
915
+ return model
916
+
917
+ @classmethod
918
+ def _load_pretrained_model(
919
+ cls,
920
+ model,
921
+ state_dict: OrderedDict,
922
+ resolved_archive_file,
923
+ pretrained_model_name_or_path: Union[str, os.PathLike],
924
+ ignore_mismatched_sizes: bool = False,
925
+ ):
926
+ # Retrieve missing & unexpected_keys
927
+ model_state_dict = model.state_dict()
928
+ loaded_keys = list(state_dict.keys())
929
+
930
+ expected_keys = list(model_state_dict.keys())
931
+
932
+ original_loaded_keys = loaded_keys
933
+
934
+ missing_keys = list(set(expected_keys) - set(loaded_keys))
935
+ unexpected_keys = list(set(loaded_keys) - set(expected_keys))
936
+
937
+ # Make sure we are able to load base models as well as derived models (with heads)
938
+ model_to_load = model
939
+
940
+ def _find_mismatched_keys(
941
+ state_dict,
942
+ model_state_dict,
943
+ loaded_keys,
944
+ ignore_mismatched_sizes,
945
+ ):
946
+ mismatched_keys = []
947
+ if ignore_mismatched_sizes:
948
+ for checkpoint_key in loaded_keys:
949
+ model_key = checkpoint_key
950
+
951
+ if (
952
+ model_key in model_state_dict
953
+ and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape
954
+ ):
955
+ mismatched_keys.append(
956
+ (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)
957
+ )
958
+ del state_dict[checkpoint_key]
959
+ return mismatched_keys
960
+
961
+ if state_dict is not None:
962
+ # Whole checkpoint
963
+ mismatched_keys = _find_mismatched_keys(
964
+ state_dict,
965
+ model_state_dict,
966
+ original_loaded_keys,
967
+ ignore_mismatched_sizes,
968
+ )
969
+ error_msgs = _load_state_dict_into_model(model_to_load, state_dict)
970
+
971
+ if len(error_msgs) > 0:
972
+ error_msg = "\n\t".join(error_msgs)
973
+ if "size mismatch" in error_msg:
974
+ error_msg += (
975
+ "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
976
+ )
977
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
978
+
979
+ if len(unexpected_keys) > 0:
980
+ logger.warning(
981
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
982
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
983
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task"
984
+ " or with another architecture (e.g. initializing a BertForSequenceClassification model from a"
985
+ " BertForPreTraining model).\n- This IS NOT expected if you are initializing"
986
+ f" {model.__class__.__name__} from the checkpoint of a model that you expect to be exactly"
987
+ " identical (initializing a BertForSequenceClassification model from a"
988
+ " BertForSequenceClassification model)."
989
+ )
990
+ else:
991
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
992
+ if len(missing_keys) > 0:
993
+ logger.warning(
994
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
995
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
996
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
997
+ )
998
+ elif len(mismatched_keys) == 0:
999
+ logger.info(
1000
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
1001
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the"
1002
+ f" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions"
1003
+ " without further training."
1004
+ )
1005
+ if len(mismatched_keys) > 0:
1006
+ mismatched_warning = "\n".join(
1007
+ [
1008
+ f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
1009
+ for key, shape1, shape2 in mismatched_keys
1010
+ ]
1011
+ )
1012
+ logger.warning(
1013
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
1014
+ f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
1015
+ f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be"
1016
+ " able to use it for predictions and inference."
1017
+ )
1018
+
1019
+ return model, missing_keys, unexpected_keys, mismatched_keys, error_msgs
1020
+
1021
+ @property
1022
+ def device(self) -> torch.device:
1023
+ """
1024
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
1025
+ device).
1026
+ """
1027
+ return get_parameter_device(self)
1028
+
1029
+ @property
1030
+ def dtype(self) -> torch.dtype:
1031
+ """
1032
+ `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
1033
+ """
1034
+ return get_parameter_dtype(self)
1035
+
1036
+ def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:
1037
+ """
1038
+ Get number of (trainable or non-embedding) parameters in the module.
1039
+
1040
+ Args:
1041
+ only_trainable (`bool`, *optional*, defaults to `False`):
1042
+ Whether or not to return only the number of trainable parameters.
1043
+ exclude_embeddings (`bool`, *optional*, defaults to `False`):
1044
+ Whether or not to return only the number of non-embedding parameters.
1045
+
1046
+ Returns:
1047
+ `int`: The number of parameters.
1048
+
1049
+ Example:
1050
+
1051
+ ```py
1052
+ from diffusers import UNet2DConditionModel
1053
+
1054
+ model_id = "runwayml/stable-diffusion-v1-5"
1055
+ unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
1056
+ unet.num_parameters(only_trainable=True)
1057
+ 859520964
1058
+ ```
1059
+ """
1060
+
1061
+ if exclude_embeddings:
1062
+ embedding_param_names = [
1063
+ f"{name}.weight"
1064
+ for name, module_type in self.named_modules()
1065
+ if isinstance(module_type, torch.nn.Embedding)
1066
+ ]
1067
+ non_embedding_parameters = [
1068
+ parameter for name, parameter in self.named_parameters() if name not in embedding_param_names
1069
+ ]
1070
+ return sum(p.numel() for p in non_embedding_parameters if p.requires_grad or not only_trainable)
1071
+ else:
1072
+ return sum(p.numel() for p in self.parameters() if p.requires_grad or not only_trainable)
1073
+
1074
+ def _convert_deprecated_attention_blocks(self, state_dict: OrderedDict) -> None:
1075
+ deprecated_attention_block_paths = []
1076
+
1077
+ def recursive_find_attn_block(name, module):
1078
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
1079
+ deprecated_attention_block_paths.append(name)
1080
+
1081
+ for sub_name, sub_module in module.named_children():
1082
+ sub_name = sub_name if name == "" else f"{name}.{sub_name}"
1083
+ recursive_find_attn_block(sub_name, sub_module)
1084
+
1085
+ recursive_find_attn_block("", self)
1086
+
1087
+ # NOTE: we have to check if the deprecated parameters are in the state dict
1088
+ # because it is possible we are loading from a state dict that was already
1089
+ # converted
1090
+
1091
+ for path in deprecated_attention_block_paths:
1092
+ # group_norm path stays the same
1093
+
1094
+ # query -> to_q
1095
+ if f"{path}.query.weight" in state_dict:
1096
+ state_dict[f"{path}.to_q.weight"] = state_dict.pop(f"{path}.query.weight")
1097
+ if f"{path}.query.bias" in state_dict:
1098
+ state_dict[f"{path}.to_q.bias"] = state_dict.pop(f"{path}.query.bias")
1099
+
1100
+ # key -> to_k
1101
+ if f"{path}.key.weight" in state_dict:
1102
+ state_dict[f"{path}.to_k.weight"] = state_dict.pop(f"{path}.key.weight")
1103
+ if f"{path}.key.bias" in state_dict:
1104
+ state_dict[f"{path}.to_k.bias"] = state_dict.pop(f"{path}.key.bias")
1105
+
1106
+ # value -> to_v
1107
+ if f"{path}.value.weight" in state_dict:
1108
+ state_dict[f"{path}.to_v.weight"] = state_dict.pop(f"{path}.value.weight")
1109
+ if f"{path}.value.bias" in state_dict:
1110
+ state_dict[f"{path}.to_v.bias"] = state_dict.pop(f"{path}.value.bias")
1111
+
1112
+ # proj_attn -> to_out.0
1113
+ if f"{path}.proj_attn.weight" in state_dict:
1114
+ state_dict[f"{path}.to_out.0.weight"] = state_dict.pop(f"{path}.proj_attn.weight")
1115
+ if f"{path}.proj_attn.bias" in state_dict:
1116
+ state_dict[f"{path}.to_out.0.bias"] = state_dict.pop(f"{path}.proj_attn.bias")
1117
+
1118
+ def _temp_convert_self_to_deprecated_attention_blocks(self) -> None:
1119
+ deprecated_attention_block_modules = []
1120
+
1121
+ def recursive_find_attn_block(module):
1122
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
1123
+ deprecated_attention_block_modules.append(module)
1124
+
1125
+ for sub_module in module.children():
1126
+ recursive_find_attn_block(sub_module)
1127
+
1128
+ recursive_find_attn_block(self)
1129
+
1130
+ for module in deprecated_attention_block_modules:
1131
+ module.query = module.to_q
1132
+ module.key = module.to_k
1133
+ module.value = module.to_v
1134
+ module.proj_attn = module.to_out[0]
1135
+
1136
+ # We don't _have_ to delete the old attributes, but it's helpful to ensure
1137
+ # that _all_ the weights are loaded into the new attributes and we're not
1138
+ # making an incorrect assumption that this model should be converted when
1139
+ # it really shouldn't be.
1140
+ del module.to_q
1141
+ del module.to_k
1142
+ del module.to_v
1143
+ del module.to_out
1144
+
1145
+ def _undo_temp_convert_self_to_deprecated_attention_blocks(self) -> None:
1146
+ deprecated_attention_block_modules = []
1147
+
1148
+ def recursive_find_attn_block(module) -> None:
1149
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
1150
+ deprecated_attention_block_modules.append(module)
1151
+
1152
+ for sub_module in module.children():
1153
+ recursive_find_attn_block(sub_module)
1154
+
1155
+ recursive_find_attn_block(self)
1156
+
1157
+ for module in deprecated_attention_block_modules:
1158
+ module.to_q = module.query
1159
+ module.to_k = module.key
1160
+ module.to_v = module.value
1161
+ module.to_out = nn.ModuleList([module.proj_attn, nn.Dropout(module.dropout)])
1162
+
1163
+ del module.query
1164
+ del module.key
1165
+ del module.value
1166
+ del module.proj_attn
diffusers/models/normalization.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 HuggingFace Inc.
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 typing import Dict, Optional, Tuple
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from .activations import get_activation
23
+ from .embeddings import CombinedTimestepLabelEmbeddings, CombinedTimestepSizeEmbeddings
24
+
25
+
26
+ class AdaLayerNorm(nn.Module):
27
+ r"""
28
+ Norm layer modified to incorporate timestep embeddings.
29
+
30
+ Parameters:
31
+ embedding_dim (`int`): The size of each embedding vector.
32
+ num_embeddings (`int`): The size of the embeddings dictionary.
33
+ """
34
+
35
+ def __init__(self, embedding_dim: int, num_embeddings: int):
36
+ super().__init__()
37
+ self.emb = nn.Embedding(num_embeddings, embedding_dim)
38
+ self.silu = nn.SiLU()
39
+ self.linear = nn.Linear(embedding_dim, embedding_dim * 2)
40
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False)
41
+
42
+ def forward(self, x: torch.Tensor, timestep: torch.Tensor) -> torch.Tensor:
43
+ emb = self.linear(self.silu(self.emb(timestep)))
44
+ scale, shift = torch.chunk(emb, 2)
45
+ x = self.norm(x) * (1 + scale) + shift
46
+ return x
47
+
48
+
49
+ class AdaLayerNormZero(nn.Module):
50
+ r"""
51
+ Norm layer adaptive layer norm zero (adaLN-Zero).
52
+
53
+ Parameters:
54
+ embedding_dim (`int`): The size of each embedding vector.
55
+ num_embeddings (`int`): The size of the embeddings dictionary.
56
+ """
57
+
58
+ def __init__(self, embedding_dim: int, num_embeddings: int):
59
+ super().__init__()
60
+
61
+ self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
62
+
63
+ self.silu = nn.SiLU()
64
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
65
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
66
+
67
+ def forward(
68
+ self,
69
+ x: torch.Tensor,
70
+ timestep: torch.Tensor,
71
+ class_labels: torch.LongTensor,
72
+ hidden_dtype: Optional[torch.dtype] = None,
73
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
74
+ emb = self.linear(self.silu(self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)))
75
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
76
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
77
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
78
+
79
+
80
+ class AdaLayerNormSingle(nn.Module):
81
+ r"""
82
+ Norm layer adaptive layer norm single (adaLN-single).
83
+
84
+ As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
85
+
86
+ Parameters:
87
+ embedding_dim (`int`): The size of each embedding vector.
88
+ use_additional_conditions (`bool`): To use additional conditions for normalization or not.
89
+ """
90
+
91
+ def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
92
+ super().__init__()
93
+
94
+ self.emb = CombinedTimestepSizeEmbeddings(
95
+ embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
96
+ )
97
+
98
+ self.silu = nn.SiLU()
99
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
100
+
101
+ def forward(
102
+ self,
103
+ timestep: torch.Tensor,
104
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
105
+ batch_size: Optional[int] = None,
106
+ hidden_dtype: Optional[torch.dtype] = None,
107
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
108
+ # No modulation happening here.
109
+ embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype)
110
+ return self.linear(self.silu(embedded_timestep)), embedded_timestep
111
+
112
+
113
+ class AdaGroupNorm(nn.Module):
114
+ r"""
115
+ GroupNorm layer modified to incorporate timestep embeddings.
116
+
117
+ Parameters:
118
+ embedding_dim (`int`): The size of each embedding vector.
119
+ num_embeddings (`int`): The size of the embeddings dictionary.
120
+ num_groups (`int`): The number of groups to separate the channels into.
121
+ act_fn (`str`, *optional*, defaults to `None`): The activation function to use.
122
+ eps (`float`, *optional*, defaults to `1e-5`): The epsilon value to use for numerical stability.
123
+ """
124
+
125
+ def __init__(
126
+ self, embedding_dim: int, out_dim: int, num_groups: int, act_fn: Optional[str] = None, eps: float = 1e-5
127
+ ):
128
+ super().__init__()
129
+ self.num_groups = num_groups
130
+ self.eps = eps
131
+
132
+ if act_fn is None:
133
+ self.act = None
134
+ else:
135
+ self.act = get_activation(act_fn)
136
+
137
+ self.linear = nn.Linear(embedding_dim, out_dim * 2)
138
+
139
+ def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
140
+ if self.act:
141
+ emb = self.act(emb)
142
+ emb = self.linear(emb)
143
+ emb = emb[:, :, None, None]
144
+ scale, shift = emb.chunk(2, dim=1)
145
+
146
+ x = F.group_norm(x, self.num_groups, eps=self.eps)
147
+ x = x * (1 + scale) + shift
148
+ return x
diffusers/models/prior_transformer.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, Optional, Union
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from torch import nn
7
+
8
+ from ..configuration_utils import ConfigMixin, register_to_config
9
+ from ..loaders import UNet2DConditionLoadersMixin
10
+ from ..utils import BaseOutput
11
+ from .attention import BasicTransformerBlock
12
+ from .attention_processor import (
13
+ ADDED_KV_ATTENTION_PROCESSORS,
14
+ CROSS_ATTENTION_PROCESSORS,
15
+ AttentionProcessor,
16
+ AttnAddedKVProcessor,
17
+ AttnProcessor,
18
+ )
19
+ from .embeddings import TimestepEmbedding, Timesteps
20
+ from .modeling_utils import ModelMixin
21
+
22
+
23
+ @dataclass
24
+ class PriorTransformerOutput(BaseOutput):
25
+ """
26
+ The output of [`PriorTransformer`].
27
+
28
+ Args:
29
+ predicted_image_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
30
+ The predicted CLIP image embedding conditioned on the CLIP text embedding input.
31
+ """
32
+
33
+ predicted_image_embedding: torch.FloatTensor
34
+
35
+
36
+ class PriorTransformer(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
37
+ """
38
+ A Prior Transformer model.
39
+
40
+ Parameters:
41
+ num_attention_heads (`int`, *optional*, defaults to 32): The number of heads to use for multi-head attention.
42
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
43
+ num_layers (`int`, *optional*, defaults to 20): The number of layers of Transformer blocks to use.
44
+ embedding_dim (`int`, *optional*, defaults to 768): The dimension of the model input `hidden_states`
45
+ num_embeddings (`int`, *optional*, defaults to 77):
46
+ The number of embeddings of the model input `hidden_states`
47
+ additional_embeddings (`int`, *optional*, defaults to 4): The number of additional tokens appended to the
48
+ projected `hidden_states`. The actual length of the used `hidden_states` is `num_embeddings +
49
+ additional_embeddings`.
50
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
51
+ time_embed_act_fn (`str`, *optional*, defaults to 'silu'):
52
+ The activation function to use to create timestep embeddings.
53
+ norm_in_type (`str`, *optional*, defaults to None): The normalization layer to apply on hidden states before
54
+ passing to Transformer blocks. Set it to `None` if normalization is not needed.
55
+ embedding_proj_norm_type (`str`, *optional*, defaults to None):
56
+ The normalization layer to apply on the input `proj_embedding`. Set it to `None` if normalization is not
57
+ needed.
58
+ encoder_hid_proj_type (`str`, *optional*, defaults to `linear`):
59
+ The projection layer to apply on the input `encoder_hidden_states`. Set it to `None` if
60
+ `encoder_hidden_states` is `None`.
61
+ added_emb_type (`str`, *optional*, defaults to `prd`): Additional embeddings to condition the model.
62
+ Choose from `prd` or `None`. if choose `prd`, it will prepend a token indicating the (quantized) dot
63
+ product between the text embedding and image embedding as proposed in the unclip paper
64
+ https://arxiv.org/abs/2204.06125 If it is `None`, no additional embeddings will be prepended.
65
+ time_embed_dim (`int, *optional*, defaults to None): The dimension of timestep embeddings.
66
+ If None, will be set to `num_attention_heads * attention_head_dim`
67
+ embedding_proj_dim (`int`, *optional*, default to None):
68
+ The dimension of `proj_embedding`. If None, will be set to `embedding_dim`.
69
+ clip_embed_dim (`int`, *optional*, default to None):
70
+ The dimension of the output. If None, will be set to `embedding_dim`.
71
+ """
72
+
73
+ @register_to_config
74
+ def __init__(
75
+ self,
76
+ num_attention_heads: int = 32,
77
+ attention_head_dim: int = 64,
78
+ num_layers: int = 20,
79
+ embedding_dim: int = 768,
80
+ num_embeddings=77,
81
+ additional_embeddings=4,
82
+ dropout: float = 0.0,
83
+ time_embed_act_fn: str = "silu",
84
+ norm_in_type: Optional[str] = None, # layer
85
+ embedding_proj_norm_type: Optional[str] = None, # layer
86
+ encoder_hid_proj_type: Optional[str] = "linear", # linear
87
+ added_emb_type: Optional[str] = "prd", # prd
88
+ time_embed_dim: Optional[int] = None,
89
+ embedding_proj_dim: Optional[int] = None,
90
+ clip_embed_dim: Optional[int] = None,
91
+ ):
92
+ super().__init__()
93
+ self.num_attention_heads = num_attention_heads
94
+ self.attention_head_dim = attention_head_dim
95
+ inner_dim = num_attention_heads * attention_head_dim
96
+ self.additional_embeddings = additional_embeddings
97
+
98
+ time_embed_dim = time_embed_dim or inner_dim
99
+ embedding_proj_dim = embedding_proj_dim or embedding_dim
100
+ clip_embed_dim = clip_embed_dim or embedding_dim
101
+
102
+ self.time_proj = Timesteps(inner_dim, True, 0)
103
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, out_dim=inner_dim, act_fn=time_embed_act_fn)
104
+
105
+ self.proj_in = nn.Linear(embedding_dim, inner_dim)
106
+
107
+ if embedding_proj_norm_type is None:
108
+ self.embedding_proj_norm = None
109
+ elif embedding_proj_norm_type == "layer":
110
+ self.embedding_proj_norm = nn.LayerNorm(embedding_proj_dim)
111
+ else:
112
+ raise ValueError(f"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}")
113
+
114
+ self.embedding_proj = nn.Linear(embedding_proj_dim, inner_dim)
115
+
116
+ if encoder_hid_proj_type is None:
117
+ self.encoder_hidden_states_proj = None
118
+ elif encoder_hid_proj_type == "linear":
119
+ self.encoder_hidden_states_proj = nn.Linear(embedding_dim, inner_dim)
120
+ else:
121
+ raise ValueError(f"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}")
122
+
123
+ self.positional_embedding = nn.Parameter(torch.zeros(1, num_embeddings + additional_embeddings, inner_dim))
124
+
125
+ if added_emb_type == "prd":
126
+ self.prd_embedding = nn.Parameter(torch.zeros(1, 1, inner_dim))
127
+ elif added_emb_type is None:
128
+ self.prd_embedding = None
129
+ else:
130
+ raise ValueError(
131
+ f"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`."
132
+ )
133
+
134
+ self.transformer_blocks = nn.ModuleList(
135
+ [
136
+ BasicTransformerBlock(
137
+ inner_dim,
138
+ num_attention_heads,
139
+ attention_head_dim,
140
+ dropout=dropout,
141
+ activation_fn="gelu",
142
+ attention_bias=True,
143
+ )
144
+ for d in range(num_layers)
145
+ ]
146
+ )
147
+
148
+ if norm_in_type == "layer":
149
+ self.norm_in = nn.LayerNorm(inner_dim)
150
+ elif norm_in_type is None:
151
+ self.norm_in = None
152
+ else:
153
+ raise ValueError(f"Unsupported norm_in_type: {norm_in_type}.")
154
+
155
+ self.norm_out = nn.LayerNorm(inner_dim)
156
+
157
+ self.proj_to_clip_embeddings = nn.Linear(inner_dim, clip_embed_dim)
158
+
159
+ causal_attention_mask = torch.full(
160
+ [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings], -10000.0
161
+ )
162
+ causal_attention_mask.triu_(1)
163
+ causal_attention_mask = causal_attention_mask[None, ...]
164
+ self.register_buffer("causal_attention_mask", causal_attention_mask, persistent=False)
165
+
166
+ self.clip_mean = nn.Parameter(torch.zeros(1, clip_embed_dim))
167
+ self.clip_std = nn.Parameter(torch.zeros(1, clip_embed_dim))
168
+
169
+ @property
170
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
171
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
172
+ r"""
173
+ Returns:
174
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
175
+ indexed by its weight name.
176
+ """
177
+ # set recursively
178
+ processors = {}
179
+
180
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
181
+ if hasattr(module, "get_processor"):
182
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
183
+
184
+ for sub_name, child in module.named_children():
185
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
186
+
187
+ return processors
188
+
189
+ for name, module in self.named_children():
190
+ fn_recursive_add_processors(name, module, processors)
191
+
192
+ return processors
193
+
194
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
195
+ def set_attn_processor(
196
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False
197
+ ):
198
+ r"""
199
+ Sets the attention processor to use to compute attention.
200
+
201
+ Parameters:
202
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
203
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
204
+ for **all** `Attention` layers.
205
+
206
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
207
+ processor. This is strongly recommended when setting trainable attention processors.
208
+
209
+ """
210
+ count = len(self.attn_processors.keys())
211
+
212
+ if isinstance(processor, dict) and len(processor) != count:
213
+ raise ValueError(
214
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
215
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
216
+ )
217
+
218
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
219
+ if hasattr(module, "set_processor"):
220
+ if not isinstance(processor, dict):
221
+ module.set_processor(processor, _remove_lora=_remove_lora)
222
+ else:
223
+ module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora)
224
+
225
+ for sub_name, child in module.named_children():
226
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
227
+
228
+ for name, module in self.named_children():
229
+ fn_recursive_attn_processor(name, module, processor)
230
+
231
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
232
+ def set_default_attn_processor(self):
233
+ """
234
+ Disables custom attention processors and sets the default attention implementation.
235
+ """
236
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
237
+ processor = AttnAddedKVProcessor()
238
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
239
+ processor = AttnProcessor()
240
+ else:
241
+ raise ValueError(
242
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
243
+ )
244
+
245
+ self.set_attn_processor(processor, _remove_lora=True)
246
+
247
+ def forward(
248
+ self,
249
+ hidden_states,
250
+ timestep: Union[torch.Tensor, float, int],
251
+ proj_embedding: torch.FloatTensor,
252
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
253
+ attention_mask: Optional[torch.BoolTensor] = None,
254
+ return_dict: bool = True,
255
+ ):
256
+ """
257
+ The [`PriorTransformer`] forward method.
258
+
259
+ Args:
260
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
261
+ The currently predicted image embeddings.
262
+ timestep (`torch.LongTensor`):
263
+ Current denoising step.
264
+ proj_embedding (`torch.FloatTensor` of shape `(batch_size, embedding_dim)`):
265
+ Projected embedding vector the denoising process is conditioned on.
266
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, num_embeddings, embedding_dim)`):
267
+ Hidden states of the text embeddings the denoising process is conditioned on.
268
+ attention_mask (`torch.BoolTensor` of shape `(batch_size, num_embeddings)`):
269
+ Text mask for the text embeddings.
270
+ return_dict (`bool`, *optional*, defaults to `True`):
271
+ Whether or not to return a [`~models.prior_transformer.PriorTransformerOutput`] instead of a plain
272
+ tuple.
273
+
274
+ Returns:
275
+ [`~models.prior_transformer.PriorTransformerOutput`] or `tuple`:
276
+ If return_dict is True, a [`~models.prior_transformer.PriorTransformerOutput`] is returned, otherwise a
277
+ tuple is returned where the first element is the sample tensor.
278
+ """
279
+ batch_size = hidden_states.shape[0]
280
+
281
+ timesteps = timestep
282
+ if not torch.is_tensor(timesteps):
283
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=hidden_states.device)
284
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
285
+ timesteps = timesteps[None].to(hidden_states.device)
286
+
287
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
288
+ timesteps = timesteps * torch.ones(batch_size, dtype=timesteps.dtype, device=timesteps.device)
289
+
290
+ timesteps_projected = self.time_proj(timesteps)
291
+
292
+ # timesteps does not contain any weights and will always return f32 tensors
293
+ # but time_embedding might be fp16, so we need to cast here.
294
+ timesteps_projected = timesteps_projected.to(dtype=self.dtype)
295
+ time_embeddings = self.time_embedding(timesteps_projected)
296
+
297
+ if self.embedding_proj_norm is not None:
298
+ proj_embedding = self.embedding_proj_norm(proj_embedding)
299
+
300
+ proj_embeddings = self.embedding_proj(proj_embedding)
301
+ if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
302
+ encoder_hidden_states = self.encoder_hidden_states_proj(encoder_hidden_states)
303
+ elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
304
+ raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set")
305
+
306
+ hidden_states = self.proj_in(hidden_states)
307
+
308
+ positional_embeddings = self.positional_embedding.to(hidden_states.dtype)
309
+
310
+ additional_embeds = []
311
+ additional_embeddings_len = 0
312
+
313
+ if encoder_hidden_states is not None:
314
+ additional_embeds.append(encoder_hidden_states)
315
+ additional_embeddings_len += encoder_hidden_states.shape[1]
316
+
317
+ if len(proj_embeddings.shape) == 2:
318
+ proj_embeddings = proj_embeddings[:, None, :]
319
+
320
+ if len(hidden_states.shape) == 2:
321
+ hidden_states = hidden_states[:, None, :]
322
+
323
+ additional_embeds = additional_embeds + [
324
+ proj_embeddings,
325
+ time_embeddings[:, None, :],
326
+ hidden_states,
327
+ ]
328
+
329
+ if self.prd_embedding is not None:
330
+ prd_embedding = self.prd_embedding.to(hidden_states.dtype).expand(batch_size, -1, -1)
331
+ additional_embeds.append(prd_embedding)
332
+
333
+ hidden_states = torch.cat(
334
+ additional_embeds,
335
+ dim=1,
336
+ )
337
+
338
+ # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
339
+ additional_embeddings_len = additional_embeddings_len + proj_embeddings.shape[1] + 1
340
+ if positional_embeddings.shape[1] < hidden_states.shape[1]:
341
+ positional_embeddings = F.pad(
342
+ positional_embeddings,
343
+ (
344
+ 0,
345
+ 0,
346
+ additional_embeddings_len,
347
+ self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
348
+ ),
349
+ value=0.0,
350
+ )
351
+
352
+ hidden_states = hidden_states + positional_embeddings
353
+
354
+ if attention_mask is not None:
355
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
356
+ attention_mask = F.pad(attention_mask, (0, self.additional_embeddings), value=0.0)
357
+ attention_mask = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype)
358
+ attention_mask = attention_mask.repeat_interleave(self.config.num_attention_heads, dim=0)
359
+
360
+ if self.norm_in is not None:
361
+ hidden_states = self.norm_in(hidden_states)
362
+
363
+ for block in self.transformer_blocks:
364
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
365
+
366
+ hidden_states = self.norm_out(hidden_states)
367
+
368
+ if self.prd_embedding is not None:
369
+ hidden_states = hidden_states[:, -1]
370
+ else:
371
+ hidden_states = hidden_states[:, additional_embeddings_len:]
372
+
373
+ predicted_image_embedding = self.proj_to_clip_embeddings(hidden_states)
374
+
375
+ if not return_dict:
376
+ return (predicted_image_embedding,)
377
+
378
+ return PriorTransformerOutput(predicted_image_embedding=predicted_image_embedding)
379
+
380
+ def post_process_latents(self, prior_latents):
381
+ prior_latents = (prior_latents * self.clip_std) + self.clip_mean
382
+ return prior_latents
diffusers/models/resnet.py ADDED
@@ -0,0 +1,1368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ # `TemporalConvLayer` Copyright 2023 Alibaba DAMO-VILAB, The ModelScope Team and 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 functools import partial
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from ..utils import USE_PEFT_BACKEND
24
+ from .activations import get_activation
25
+ from .attention_processor import SpatialNorm
26
+ from .lora import LoRACompatibleConv, LoRACompatibleLinear
27
+ from .normalization import AdaGroupNorm
28
+
29
+
30
+ class Upsample1D(nn.Module):
31
+ """A 1D upsampling layer with an optional convolution.
32
+
33
+ Parameters:
34
+ channels (`int`):
35
+ number of channels in the inputs and outputs.
36
+ use_conv (`bool`, default `False`):
37
+ option to use a convolution.
38
+ use_conv_transpose (`bool`, default `False`):
39
+ option to use a convolution transpose.
40
+ out_channels (`int`, optional):
41
+ number of output channels. Defaults to `channels`.
42
+ name (`str`, default `conv`):
43
+ name of the upsampling 1D layer.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ channels: int,
49
+ use_conv: bool = False,
50
+ use_conv_transpose: bool = False,
51
+ out_channels: Optional[int] = None,
52
+ name: str = "conv",
53
+ ):
54
+ super().__init__()
55
+ self.channels = channels
56
+ self.out_channels = out_channels or channels
57
+ self.use_conv = use_conv
58
+ self.use_conv_transpose = use_conv_transpose
59
+ self.name = name
60
+
61
+ self.conv = None
62
+ if use_conv_transpose:
63
+ self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
64
+ elif use_conv:
65
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
66
+
67
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
68
+ assert inputs.shape[1] == self.channels
69
+ if self.use_conv_transpose:
70
+ return self.conv(inputs)
71
+
72
+ outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
73
+
74
+ if self.use_conv:
75
+ outputs = self.conv(outputs)
76
+
77
+ return outputs
78
+
79
+
80
+ class Downsample1D(nn.Module):
81
+ """A 1D downsampling layer with an optional convolution.
82
+
83
+ Parameters:
84
+ channels (`int`):
85
+ number of channels in the inputs and outputs.
86
+ use_conv (`bool`, default `False`):
87
+ option to use a convolution.
88
+ out_channels (`int`, optional):
89
+ number of output channels. Defaults to `channels`.
90
+ padding (`int`, default `1`):
91
+ padding for the convolution.
92
+ name (`str`, default `conv`):
93
+ name of the downsampling 1D layer.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ channels: int,
99
+ use_conv: bool = False,
100
+ out_channels: Optional[int] = None,
101
+ padding: int = 1,
102
+ name: str = "conv",
103
+ ):
104
+ super().__init__()
105
+ self.channels = channels
106
+ self.out_channels = out_channels or channels
107
+ self.use_conv = use_conv
108
+ self.padding = padding
109
+ stride = 2
110
+ self.name = name
111
+
112
+ if use_conv:
113
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
114
+ else:
115
+ assert self.channels == self.out_channels
116
+ self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
117
+
118
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
119
+ assert inputs.shape[1] == self.channels
120
+ return self.conv(inputs)
121
+
122
+
123
+ class Upsample2D(nn.Module):
124
+ """A 2D upsampling layer with an optional convolution.
125
+
126
+ Parameters:
127
+ channels (`int`):
128
+ number of channels in the inputs and outputs.
129
+ use_conv (`bool`, default `False`):
130
+ option to use a convolution.
131
+ use_conv_transpose (`bool`, default `False`):
132
+ option to use a convolution transpose.
133
+ out_channels (`int`, optional):
134
+ number of output channels. Defaults to `channels`.
135
+ name (`str`, default `conv`):
136
+ name of the upsampling 2D layer.
137
+ """
138
+
139
+ def __init__(
140
+ self,
141
+ channels: int,
142
+ use_conv: bool = False,
143
+ use_conv_transpose: bool = False,
144
+ out_channels: Optional[int] = None,
145
+ name: str = "conv",
146
+ ):
147
+ super().__init__()
148
+ self.channels = channels
149
+ self.out_channels = out_channels or channels
150
+ self.use_conv = use_conv
151
+ self.use_conv_transpose = use_conv_transpose
152
+ self.name = name
153
+ conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
154
+
155
+ conv = None
156
+ if use_conv_transpose:
157
+ conv = nn.ConvTranspose2d(channels, self.out_channels, 4, 2, 1)
158
+ elif use_conv:
159
+ conv = conv_cls(self.channels, self.out_channels, 3, padding=1)
160
+
161
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
162
+ if name == "conv":
163
+ self.conv = conv
164
+ else:
165
+ self.Conv2d_0 = conv
166
+
167
+ def forward(
168
+ self,
169
+ hidden_states: torch.FloatTensor,
170
+ output_size: Optional[int] = None,
171
+ scale: float = 1.0,
172
+ ) -> torch.FloatTensor:
173
+ assert hidden_states.shape[1] == self.channels
174
+
175
+ if self.use_conv_transpose:
176
+ return self.conv(hidden_states)
177
+
178
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
179
+ # TODO(Suraj): Remove this cast once the issue is fixed in PyTorch
180
+ # https://github.com/pytorch/pytorch/issues/86679
181
+ dtype = hidden_states.dtype
182
+ if dtype == torch.bfloat16:
183
+ hidden_states = hidden_states.to(torch.float32)
184
+
185
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
186
+ if hidden_states.shape[0] >= 64:
187
+ hidden_states = hidden_states.contiguous()
188
+
189
+ # if `output_size` is passed we force the interpolation output
190
+ # size and do not make use of `scale_factor=2`
191
+ if output_size is None:
192
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
193
+ else:
194
+ hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
195
+
196
+ # If the input is bfloat16, we cast back to bfloat16
197
+ if dtype == torch.bfloat16:
198
+ hidden_states = hidden_states.to(dtype)
199
+
200
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
201
+ if self.use_conv:
202
+ if self.name == "conv":
203
+ if isinstance(self.conv, LoRACompatibleConv) and not USE_PEFT_BACKEND:
204
+ hidden_states = self.conv(hidden_states, scale)
205
+ else:
206
+ hidden_states = self.conv(hidden_states)
207
+ else:
208
+ if isinstance(self.Conv2d_0, LoRACompatibleConv) and not USE_PEFT_BACKEND:
209
+ hidden_states = self.Conv2d_0(hidden_states, scale)
210
+ else:
211
+ hidden_states = self.Conv2d_0(hidden_states)
212
+
213
+ return hidden_states
214
+
215
+
216
+ class Downsample2D(nn.Module):
217
+ """A 2D downsampling layer with an optional convolution.
218
+
219
+ Parameters:
220
+ channels (`int`):
221
+ number of channels in the inputs and outputs.
222
+ use_conv (`bool`, default `False`):
223
+ option to use a convolution.
224
+ out_channels (`int`, optional):
225
+ number of output channels. Defaults to `channels`.
226
+ padding (`int`, default `1`):
227
+ padding for the convolution.
228
+ name (`str`, default `conv`):
229
+ name of the downsampling 2D layer.
230
+ """
231
+
232
+ def __init__(
233
+ self,
234
+ channels: int,
235
+ use_conv: bool = False,
236
+ out_channels: Optional[int] = None,
237
+ padding: int = 1,
238
+ name: str = "conv",
239
+ ):
240
+ super().__init__()
241
+ self.channels = channels
242
+ self.out_channels = out_channels or channels
243
+ self.use_conv = use_conv
244
+ self.padding = padding
245
+ stride = 2
246
+ self.name = name
247
+ conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
248
+
249
+ if use_conv:
250
+ conv = conv_cls(self.channels, self.out_channels, 3, stride=stride, padding=padding)
251
+ else:
252
+ assert self.channels == self.out_channels
253
+ conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
254
+
255
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
256
+ if name == "conv":
257
+ self.Conv2d_0 = conv
258
+ self.conv = conv
259
+ elif name == "Conv2d_0":
260
+ self.conv = conv
261
+ else:
262
+ self.conv = conv
263
+
264
+ def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
265
+ assert hidden_states.shape[1] == self.channels
266
+
267
+ if self.use_conv and self.padding == 0:
268
+ pad = (0, 1, 0, 1)
269
+ hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
270
+
271
+ assert hidden_states.shape[1] == self.channels
272
+
273
+ if not USE_PEFT_BACKEND:
274
+ if isinstance(self.conv, LoRACompatibleConv):
275
+ hidden_states = self.conv(hidden_states, scale)
276
+ else:
277
+ hidden_states = self.conv(hidden_states)
278
+ else:
279
+ hidden_states = self.conv(hidden_states)
280
+
281
+ return hidden_states
282
+
283
+
284
+ class FirUpsample2D(nn.Module):
285
+ """A 2D FIR upsampling layer with an optional convolution.
286
+
287
+ Parameters:
288
+ channels (`int`, optional):
289
+ number of channels in the inputs and outputs.
290
+ use_conv (`bool`, default `False`):
291
+ option to use a convolution.
292
+ out_channels (`int`, optional):
293
+ number of output channels. Defaults to `channels`.
294
+ fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
295
+ kernel for the FIR filter.
296
+ """
297
+
298
+ def __init__(
299
+ self,
300
+ channels: Optional[int] = None,
301
+ out_channels: Optional[int] = None,
302
+ use_conv: bool = False,
303
+ fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
304
+ ):
305
+ super().__init__()
306
+ out_channels = out_channels if out_channels else channels
307
+ if use_conv:
308
+ self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
309
+ self.use_conv = use_conv
310
+ self.fir_kernel = fir_kernel
311
+ self.out_channels = out_channels
312
+
313
+ def _upsample_2d(
314
+ self,
315
+ hidden_states: torch.FloatTensor,
316
+ weight: Optional[torch.FloatTensor] = None,
317
+ kernel: Optional[torch.FloatTensor] = None,
318
+ factor: int = 2,
319
+ gain: float = 1,
320
+ ) -> torch.FloatTensor:
321
+ """Fused `upsample_2d()` followed by `Conv2d()`.
322
+
323
+ Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
324
+ efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
325
+ arbitrary order.
326
+
327
+ Args:
328
+ hidden_states (`torch.FloatTensor`):
329
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
330
+ weight (`torch.FloatTensor`, *optional*):
331
+ Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
332
+ performed by `inChannels = x.shape[0] // numGroups`.
333
+ kernel (`torch.FloatTensor`, *optional*):
334
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
335
+ corresponds to nearest-neighbor upsampling.
336
+ factor (`int`, *optional*): Integer upsampling factor (default: 2).
337
+ gain (`float`, *optional*): Scaling factor for signal magnitude (default: 1.0).
338
+
339
+ Returns:
340
+ output (`torch.FloatTensor`):
341
+ Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same
342
+ datatype as `hidden_states`.
343
+ """
344
+
345
+ assert isinstance(factor, int) and factor >= 1
346
+
347
+ # Setup filter kernel.
348
+ if kernel is None:
349
+ kernel = [1] * factor
350
+
351
+ # setup kernel
352
+ kernel = torch.tensor(kernel, dtype=torch.float32)
353
+ if kernel.ndim == 1:
354
+ kernel = torch.outer(kernel, kernel)
355
+ kernel /= torch.sum(kernel)
356
+
357
+ kernel = kernel * (gain * (factor**2))
358
+
359
+ if self.use_conv:
360
+ convH = weight.shape[2]
361
+ convW = weight.shape[3]
362
+ inC = weight.shape[1]
363
+
364
+ pad_value = (kernel.shape[0] - factor) - (convW - 1)
365
+
366
+ stride = (factor, factor)
367
+ # Determine data dimensions.
368
+ output_shape = (
369
+ (hidden_states.shape[2] - 1) * factor + convH,
370
+ (hidden_states.shape[3] - 1) * factor + convW,
371
+ )
372
+ output_padding = (
373
+ output_shape[0] - (hidden_states.shape[2] - 1) * stride[0] - convH,
374
+ output_shape[1] - (hidden_states.shape[3] - 1) * stride[1] - convW,
375
+ )
376
+ assert output_padding[0] >= 0 and output_padding[1] >= 0
377
+ num_groups = hidden_states.shape[1] // inC
378
+
379
+ # Transpose weights.
380
+ weight = torch.reshape(weight, (num_groups, -1, inC, convH, convW))
381
+ weight = torch.flip(weight, dims=[3, 4]).permute(0, 2, 1, 3, 4)
382
+ weight = torch.reshape(weight, (num_groups * inC, -1, convH, convW))
383
+
384
+ inverse_conv = F.conv_transpose2d(
385
+ hidden_states,
386
+ weight,
387
+ stride=stride,
388
+ output_padding=output_padding,
389
+ padding=0,
390
+ )
391
+
392
+ output = upfirdn2d_native(
393
+ inverse_conv,
394
+ torch.tensor(kernel, device=inverse_conv.device),
395
+ pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2 + 1),
396
+ )
397
+ else:
398
+ pad_value = kernel.shape[0] - factor
399
+ output = upfirdn2d_native(
400
+ hidden_states,
401
+ torch.tensor(kernel, device=hidden_states.device),
402
+ up=factor,
403
+ pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2),
404
+ )
405
+
406
+ return output
407
+
408
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
409
+ if self.use_conv:
410
+ height = self._upsample_2d(hidden_states, self.Conv2d_0.weight, kernel=self.fir_kernel)
411
+ height = height + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
412
+ else:
413
+ height = self._upsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
414
+
415
+ return height
416
+
417
+
418
+ class FirDownsample2D(nn.Module):
419
+ """A 2D FIR downsampling layer with an optional convolution.
420
+
421
+ Parameters:
422
+ channels (`int`):
423
+ number of channels in the inputs and outputs.
424
+ use_conv (`bool`, default `False`):
425
+ option to use a convolution.
426
+ out_channels (`int`, optional):
427
+ number of output channels. Defaults to `channels`.
428
+ fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
429
+ kernel for the FIR filter.
430
+ """
431
+
432
+ def __init__(
433
+ self,
434
+ channels: Optional[int] = None,
435
+ out_channels: Optional[int] = None,
436
+ use_conv: bool = False,
437
+ fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
438
+ ):
439
+ super().__init__()
440
+ out_channels = out_channels if out_channels else channels
441
+ if use_conv:
442
+ self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
443
+ self.fir_kernel = fir_kernel
444
+ self.use_conv = use_conv
445
+ self.out_channels = out_channels
446
+
447
+ def _downsample_2d(
448
+ self,
449
+ hidden_states: torch.FloatTensor,
450
+ weight: Optional[torch.FloatTensor] = None,
451
+ kernel: Optional[torch.FloatTensor] = None,
452
+ factor: int = 2,
453
+ gain: float = 1,
454
+ ) -> torch.FloatTensor:
455
+ """Fused `Conv2d()` followed by `downsample_2d()`.
456
+ Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
457
+ efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
458
+ arbitrary order.
459
+
460
+ Args:
461
+ hidden_states (`torch.FloatTensor`):
462
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
463
+ weight (`torch.FloatTensor`, *optional*):
464
+ Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
465
+ performed by `inChannels = x.shape[0] // numGroups`.
466
+ kernel (`torch.FloatTensor`, *optional*):
467
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
468
+ corresponds to average pooling.
469
+ factor (`int`, *optional*, default to `2`):
470
+ Integer downsampling factor.
471
+ gain (`float`, *optional*, default to `1.0`):
472
+ Scaling factor for signal magnitude.
473
+
474
+ Returns:
475
+ output (`torch.FloatTensor`):
476
+ Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
477
+ datatype as `x`.
478
+ """
479
+
480
+ assert isinstance(factor, int) and factor >= 1
481
+ if kernel is None:
482
+ kernel = [1] * factor
483
+
484
+ # setup kernel
485
+ kernel = torch.tensor(kernel, dtype=torch.float32)
486
+ if kernel.ndim == 1:
487
+ kernel = torch.outer(kernel, kernel)
488
+ kernel /= torch.sum(kernel)
489
+
490
+ kernel = kernel * gain
491
+
492
+ if self.use_conv:
493
+ _, _, convH, convW = weight.shape
494
+ pad_value = (kernel.shape[0] - factor) + (convW - 1)
495
+ stride_value = [factor, factor]
496
+ upfirdn_input = upfirdn2d_native(
497
+ hidden_states,
498
+ torch.tensor(kernel, device=hidden_states.device),
499
+ pad=((pad_value + 1) // 2, pad_value // 2),
500
+ )
501
+ output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
502
+ else:
503
+ pad_value = kernel.shape[0] - factor
504
+ output = upfirdn2d_native(
505
+ hidden_states,
506
+ torch.tensor(kernel, device=hidden_states.device),
507
+ down=factor,
508
+ pad=((pad_value + 1) // 2, pad_value // 2),
509
+ )
510
+
511
+ return output
512
+
513
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
514
+ if self.use_conv:
515
+ downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
516
+ hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
517
+ else:
518
+ hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
519
+
520
+ return hidden_states
521
+
522
+
523
+ # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
524
+ class KDownsample2D(nn.Module):
525
+ r"""A 2D K-downsampling layer.
526
+
527
+ Parameters:
528
+ pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
529
+ """
530
+
531
+ def __init__(self, pad_mode: str = "reflect"):
532
+ super().__init__()
533
+ self.pad_mode = pad_mode
534
+ kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
535
+ self.pad = kernel_1d.shape[1] // 2 - 1
536
+ self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
537
+
538
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
539
+ inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
540
+ weight = inputs.new_zeros(
541
+ [
542
+ inputs.shape[1],
543
+ inputs.shape[1],
544
+ self.kernel.shape[0],
545
+ self.kernel.shape[1],
546
+ ]
547
+ )
548
+ indices = torch.arange(inputs.shape[1], device=inputs.device)
549
+ kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
550
+ weight[indices, indices] = kernel
551
+ return F.conv2d(inputs, weight, stride=2)
552
+
553
+
554
+ class KUpsample2D(nn.Module):
555
+ r"""A 2D K-upsampling layer.
556
+
557
+ Parameters:
558
+ pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
559
+ """
560
+
561
+ def __init__(self, pad_mode: str = "reflect"):
562
+ super().__init__()
563
+ self.pad_mode = pad_mode
564
+ kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]]) * 2
565
+ self.pad = kernel_1d.shape[1] // 2 - 1
566
+ self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
567
+
568
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
569
+ inputs = F.pad(inputs, ((self.pad + 1) // 2,) * 4, self.pad_mode)
570
+ weight = inputs.new_zeros(
571
+ [
572
+ inputs.shape[1],
573
+ inputs.shape[1],
574
+ self.kernel.shape[0],
575
+ self.kernel.shape[1],
576
+ ]
577
+ )
578
+ indices = torch.arange(inputs.shape[1], device=inputs.device)
579
+ kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
580
+ weight[indices, indices] = kernel
581
+ return F.conv_transpose2d(inputs, weight, stride=2, padding=self.pad * 2 + 1)
582
+
583
+
584
+ class ResnetBlock2D(nn.Module):
585
+ r"""
586
+ A Resnet block.
587
+
588
+ Parameters:
589
+ in_channels (`int`): The number of channels in the input.
590
+ out_channels (`int`, *optional*, default to be `None`):
591
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
592
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
593
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
594
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
595
+ groups_out (`int`, *optional*, default to None):
596
+ The number of groups to use for the second normalization layer. if set to None, same as `groups`.
597
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
598
+ non_linearity (`str`, *optional*, default to `"swish"`): the activation function to use.
599
+ time_embedding_norm (`str`, *optional*, default to `"default"` ): Time scale shift config.
600
+ By default, apply timestep embedding conditioning with a simple shift mechanism. Choose "scale_shift" or
601
+ "ada_group" for a stronger conditioning with scale and shift.
602
+ kernel (`torch.FloatTensor`, optional, default to None): FIR filter, see
603
+ [`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
604
+ output_scale_factor (`float`, *optional*, default to be `1.0`): the scale factor to use for the output.
605
+ use_in_shortcut (`bool`, *optional*, default to `True`):
606
+ If `True`, add a 1x1 nn.conv2d layer for skip-connection.
607
+ up (`bool`, *optional*, default to `False`): If `True`, add an upsample layer.
608
+ down (`bool`, *optional*, default to `False`): If `True`, add a downsample layer.
609
+ conv_shortcut_bias (`bool`, *optional*, default to `True`): If `True`, adds a learnable bias to the
610
+ `conv_shortcut` output.
611
+ conv_2d_out_channels (`int`, *optional*, default to `None`): the number of channels in the output.
612
+ If None, same as `out_channels`.
613
+ """
614
+
615
+ def __init__(
616
+ self,
617
+ *,
618
+ in_channels: int,
619
+ out_channels: Optional[int] = None,
620
+ conv_shortcut: bool = False,
621
+ dropout: float = 0.0,
622
+ temb_channels: int = 512,
623
+ groups: int = 32,
624
+ groups_out: Optional[int] = None,
625
+ pre_norm: bool = True,
626
+ eps: float = 1e-6,
627
+ non_linearity: str = "swish",
628
+ skip_time_act: bool = False,
629
+ time_embedding_norm: str = "default", # default, scale_shift, ada_group, spatial
630
+ kernel: Optional[torch.FloatTensor] = None,
631
+ output_scale_factor: float = 1.0,
632
+ use_in_shortcut: Optional[bool] = None,
633
+ up: bool = False,
634
+ down: bool = False,
635
+ conv_shortcut_bias: bool = True,
636
+ conv_2d_out_channels: Optional[int] = None,
637
+ ):
638
+ super().__init__()
639
+ self.pre_norm = pre_norm
640
+ self.pre_norm = True
641
+ self.in_channels = in_channels
642
+ out_channels = in_channels if out_channels is None else out_channels
643
+ self.out_channels = out_channels
644
+ self.use_conv_shortcut = conv_shortcut
645
+ self.up = up
646
+ self.down = down
647
+ self.output_scale_factor = output_scale_factor
648
+ self.time_embedding_norm = time_embedding_norm
649
+ self.skip_time_act = skip_time_act
650
+
651
+ linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
652
+ conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
653
+
654
+ if groups_out is None:
655
+ groups_out = groups
656
+
657
+ if self.time_embedding_norm == "ada_group":
658
+ self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps)
659
+ elif self.time_embedding_norm == "spatial":
660
+ self.norm1 = SpatialNorm(in_channels, temb_channels)
661
+ else:
662
+ self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
663
+
664
+ self.conv1 = conv_cls(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
665
+
666
+ if temb_channels is not None:
667
+ if self.time_embedding_norm == "default":
668
+ self.time_emb_proj = linear_cls(temb_channels, out_channels)
669
+ elif self.time_embedding_norm == "scale_shift":
670
+ self.time_emb_proj = linear_cls(temb_channels, 2 * out_channels)
671
+ elif self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
672
+ self.time_emb_proj = None
673
+ else:
674
+ raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
675
+ else:
676
+ self.time_emb_proj = None
677
+
678
+ if self.time_embedding_norm == "ada_group":
679
+ self.norm2 = AdaGroupNorm(temb_channels, out_channels, groups_out, eps=eps)
680
+ elif self.time_embedding_norm == "spatial":
681
+ self.norm2 = SpatialNorm(out_channels, temb_channels)
682
+ else:
683
+ self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
684
+
685
+ self.dropout = torch.nn.Dropout(dropout)
686
+ conv_2d_out_channels = conv_2d_out_channels or out_channels
687
+ self.conv2 = conv_cls(out_channels, conv_2d_out_channels, kernel_size=3, stride=1, padding=1)
688
+
689
+ self.nonlinearity = get_activation(non_linearity)
690
+
691
+ self.upsample = self.downsample = None
692
+ if self.up:
693
+ if kernel == "fir":
694
+ fir_kernel = (1, 3, 3, 1)
695
+ self.upsample = lambda x: upsample_2d(x, kernel=fir_kernel)
696
+ elif kernel == "sde_vp":
697
+ self.upsample = partial(F.interpolate, scale_factor=2.0, mode="nearest")
698
+ else:
699
+ self.upsample = Upsample2D(in_channels, use_conv=False)
700
+ elif self.down:
701
+ if kernel == "fir":
702
+ fir_kernel = (1, 3, 3, 1)
703
+ self.downsample = lambda x: downsample_2d(x, kernel=fir_kernel)
704
+ elif kernel == "sde_vp":
705
+ self.downsample = partial(F.avg_pool2d, kernel_size=2, stride=2)
706
+ else:
707
+ self.downsample = Downsample2D(in_channels, use_conv=False, padding=1, name="op")
708
+
709
+ self.use_in_shortcut = self.in_channels != conv_2d_out_channels if use_in_shortcut is None else use_in_shortcut
710
+
711
+ self.conv_shortcut = None
712
+ if self.use_in_shortcut:
713
+ self.conv_shortcut = conv_cls(
714
+ in_channels,
715
+ conv_2d_out_channels,
716
+ kernel_size=1,
717
+ stride=1,
718
+ padding=0,
719
+ bias=conv_shortcut_bias,
720
+ )
721
+
722
+ def forward(
723
+ self,
724
+ input_tensor: torch.FloatTensor,
725
+ temb: torch.FloatTensor,
726
+ scale: float = 1.0,
727
+ ) -> torch.FloatTensor:
728
+ hidden_states = input_tensor
729
+
730
+ if self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
731
+ hidden_states = self.norm1(hidden_states, temb)
732
+ else:
733
+ hidden_states = self.norm1(hidden_states)
734
+
735
+ hidden_states = self.nonlinearity(hidden_states)
736
+
737
+ if self.upsample is not None:
738
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
739
+ if hidden_states.shape[0] >= 64:
740
+ input_tensor = input_tensor.contiguous()
741
+ hidden_states = hidden_states.contiguous()
742
+ input_tensor = (
743
+ self.upsample(input_tensor, scale=scale)
744
+ if isinstance(self.upsample, Upsample2D)
745
+ else self.upsample(input_tensor)
746
+ )
747
+ hidden_states = (
748
+ self.upsample(hidden_states, scale=scale)
749
+ if isinstance(self.upsample, Upsample2D)
750
+ else self.upsample(hidden_states)
751
+ )
752
+ elif self.downsample is not None:
753
+ input_tensor = (
754
+ self.downsample(input_tensor, scale=scale)
755
+ if isinstance(self.downsample, Downsample2D)
756
+ else self.downsample(input_tensor)
757
+ )
758
+ hidden_states = (
759
+ self.downsample(hidden_states, scale=scale)
760
+ if isinstance(self.downsample, Downsample2D)
761
+ else self.downsample(hidden_states)
762
+ )
763
+
764
+ hidden_states = self.conv1(hidden_states, scale) if not USE_PEFT_BACKEND else self.conv1(hidden_states)
765
+
766
+ if self.time_emb_proj is not None:
767
+ if not self.skip_time_act:
768
+ temb = self.nonlinearity(temb)
769
+ temb = (
770
+ self.time_emb_proj(temb, scale)[:, :, None, None]
771
+ if not USE_PEFT_BACKEND
772
+ else self.time_emb_proj(temb)[:, :, None, None]
773
+ )
774
+
775
+ if temb is not None and self.time_embedding_norm == "default":
776
+ hidden_states = hidden_states + temb
777
+
778
+ if self.time_embedding_norm == "ada_group" or self.time_embedding_norm == "spatial":
779
+ hidden_states = self.norm2(hidden_states, temb)
780
+ else:
781
+ hidden_states = self.norm2(hidden_states)
782
+
783
+ if temb is not None and self.time_embedding_norm == "scale_shift":
784
+ scale, shift = torch.chunk(temb, 2, dim=1)
785
+ hidden_states = hidden_states * (1 + scale) + shift
786
+
787
+ hidden_states = self.nonlinearity(hidden_states)
788
+
789
+ hidden_states = self.dropout(hidden_states)
790
+ hidden_states = self.conv2(hidden_states, scale) if not USE_PEFT_BACKEND else self.conv2(hidden_states)
791
+
792
+ if self.conv_shortcut is not None:
793
+ input_tensor = (
794
+ self.conv_shortcut(input_tensor, scale) if not USE_PEFT_BACKEND else self.conv_shortcut(input_tensor)
795
+ )
796
+
797
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
798
+
799
+ return output_tensor
800
+
801
+
802
+ # unet_rl.py
803
+ def rearrange_dims(tensor: torch.Tensor) -> torch.Tensor:
804
+ if len(tensor.shape) == 2:
805
+ return tensor[:, :, None]
806
+ if len(tensor.shape) == 3:
807
+ return tensor[:, :, None, :]
808
+ elif len(tensor.shape) == 4:
809
+ return tensor[:, :, 0, :]
810
+ else:
811
+ raise ValueError(f"`len(tensor)`: {len(tensor)} has to be 2, 3 or 4.")
812
+
813
+
814
+ class Conv1dBlock(nn.Module):
815
+ """
816
+ Conv1d --> GroupNorm --> Mish
817
+
818
+ Parameters:
819
+ inp_channels (`int`): Number of input channels.
820
+ out_channels (`int`): Number of output channels.
821
+ kernel_size (`int` or `tuple`): Size of the convolving kernel.
822
+ n_groups (`int`, default `8`): Number of groups to separate the channels into.
823
+ activation (`str`, defaults to `mish`): Name of the activation function.
824
+ """
825
+
826
+ def __init__(
827
+ self,
828
+ inp_channels: int,
829
+ out_channels: int,
830
+ kernel_size: Union[int, Tuple[int, int]],
831
+ n_groups: int = 8,
832
+ activation: str = "mish",
833
+ ):
834
+ super().__init__()
835
+
836
+ self.conv1d = nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2)
837
+ self.group_norm = nn.GroupNorm(n_groups, out_channels)
838
+ self.mish = get_activation(activation)
839
+
840
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
841
+ intermediate_repr = self.conv1d(inputs)
842
+ intermediate_repr = rearrange_dims(intermediate_repr)
843
+ intermediate_repr = self.group_norm(intermediate_repr)
844
+ intermediate_repr = rearrange_dims(intermediate_repr)
845
+ output = self.mish(intermediate_repr)
846
+ return output
847
+
848
+
849
+ # unet_rl.py
850
+ class ResidualTemporalBlock1D(nn.Module):
851
+ """
852
+ Residual 1D block with temporal convolutions.
853
+
854
+ Parameters:
855
+ inp_channels (`int`): Number of input channels.
856
+ out_channels (`int`): Number of output channels.
857
+ embed_dim (`int`): Embedding dimension.
858
+ kernel_size (`int` or `tuple`): Size of the convolving kernel.
859
+ activation (`str`, defaults `mish`): It is possible to choose the right activation function.
860
+ """
861
+
862
+ def __init__(
863
+ self,
864
+ inp_channels: int,
865
+ out_channels: int,
866
+ embed_dim: int,
867
+ kernel_size: Union[int, Tuple[int, int]] = 5,
868
+ activation: str = "mish",
869
+ ):
870
+ super().__init__()
871
+ self.conv_in = Conv1dBlock(inp_channels, out_channels, kernel_size)
872
+ self.conv_out = Conv1dBlock(out_channels, out_channels, kernel_size)
873
+
874
+ self.time_emb_act = get_activation(activation)
875
+ self.time_emb = nn.Linear(embed_dim, out_channels)
876
+
877
+ self.residual_conv = (
878
+ nn.Conv1d(inp_channels, out_channels, 1) if inp_channels != out_channels else nn.Identity()
879
+ )
880
+
881
+ def forward(self, inputs: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
882
+ """
883
+ Args:
884
+ inputs : [ batch_size x inp_channels x horizon ]
885
+ t : [ batch_size x embed_dim ]
886
+
887
+ returns:
888
+ out : [ batch_size x out_channels x horizon ]
889
+ """
890
+ t = self.time_emb_act(t)
891
+ t = self.time_emb(t)
892
+ out = self.conv_in(inputs) + rearrange_dims(t)
893
+ out = self.conv_out(out)
894
+ return out + self.residual_conv(inputs)
895
+
896
+
897
+ def upsample_2d(
898
+ hidden_states: torch.FloatTensor,
899
+ kernel: Optional[torch.FloatTensor] = None,
900
+ factor: int = 2,
901
+ gain: float = 1,
902
+ ) -> torch.FloatTensor:
903
+ r"""Upsample2D a batch of 2D images with the given filter.
904
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and upsamples each image with the given
905
+ filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the specified
906
+ `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its shape is
907
+ a: multiple of the upsampling factor.
908
+
909
+ Args:
910
+ hidden_states (`torch.FloatTensor`):
911
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
912
+ kernel (`torch.FloatTensor`, *optional*):
913
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
914
+ corresponds to nearest-neighbor upsampling.
915
+ factor (`int`, *optional*, default to `2`):
916
+ Integer upsampling factor.
917
+ gain (`float`, *optional*, default to `1.0`):
918
+ Scaling factor for signal magnitude (default: 1.0).
919
+
920
+ Returns:
921
+ output (`torch.FloatTensor`):
922
+ Tensor of the shape `[N, C, H * factor, W * factor]`
923
+ """
924
+ assert isinstance(factor, int) and factor >= 1
925
+ if kernel is None:
926
+ kernel = [1] * factor
927
+
928
+ kernel = torch.tensor(kernel, dtype=torch.float32)
929
+ if kernel.ndim == 1:
930
+ kernel = torch.outer(kernel, kernel)
931
+ kernel /= torch.sum(kernel)
932
+
933
+ kernel = kernel * (gain * (factor**2))
934
+ pad_value = kernel.shape[0] - factor
935
+ output = upfirdn2d_native(
936
+ hidden_states,
937
+ kernel.to(device=hidden_states.device),
938
+ up=factor,
939
+ pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2),
940
+ )
941
+ return output
942
+
943
+
944
+ def downsample_2d(
945
+ hidden_states: torch.FloatTensor,
946
+ kernel: Optional[torch.FloatTensor] = None,
947
+ factor: int = 2,
948
+ gain: float = 1,
949
+ ) -> torch.FloatTensor:
950
+ r"""Downsample2D a batch of 2D images with the given filter.
951
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
952
+ given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
953
+ specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
954
+ shape is a multiple of the downsampling factor.
955
+
956
+ Args:
957
+ hidden_states (`torch.FloatTensor`)
958
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
959
+ kernel (`torch.FloatTensor`, *optional*):
960
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
961
+ corresponds to average pooling.
962
+ factor (`int`, *optional*, default to `2`):
963
+ Integer downsampling factor.
964
+ gain (`float`, *optional*, default to `1.0`):
965
+ Scaling factor for signal magnitude.
966
+
967
+ Returns:
968
+ output (`torch.FloatTensor`):
969
+ Tensor of the shape `[N, C, H // factor, W // factor]`
970
+ """
971
+
972
+ assert isinstance(factor, int) and factor >= 1
973
+ if kernel is None:
974
+ kernel = [1] * factor
975
+
976
+ kernel = torch.tensor(kernel, dtype=torch.float32)
977
+ if kernel.ndim == 1:
978
+ kernel = torch.outer(kernel, kernel)
979
+ kernel /= torch.sum(kernel)
980
+
981
+ kernel = kernel * gain
982
+ pad_value = kernel.shape[0] - factor
983
+ output = upfirdn2d_native(
984
+ hidden_states,
985
+ kernel.to(device=hidden_states.device),
986
+ down=factor,
987
+ pad=((pad_value + 1) // 2, pad_value // 2),
988
+ )
989
+ return output
990
+
991
+
992
+ def upfirdn2d_native(
993
+ tensor: torch.Tensor,
994
+ kernel: torch.Tensor,
995
+ up: int = 1,
996
+ down: int = 1,
997
+ pad: Tuple[int, int] = (0, 0),
998
+ ) -> torch.Tensor:
999
+ up_x = up_y = up
1000
+ down_x = down_y = down
1001
+ pad_x0 = pad_y0 = pad[0]
1002
+ pad_x1 = pad_y1 = pad[1]
1003
+
1004
+ _, channel, in_h, in_w = tensor.shape
1005
+ tensor = tensor.reshape(-1, in_h, in_w, 1)
1006
+
1007
+ _, in_h, in_w, minor = tensor.shape
1008
+ kernel_h, kernel_w = kernel.shape
1009
+
1010
+ out = tensor.view(-1, in_h, 1, in_w, 1, minor)
1011
+ out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
1012
+ out = out.view(-1, in_h * up_y, in_w * up_x, minor)
1013
+
1014
+ out = F.pad(out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)])
1015
+ out = out.to(tensor.device) # Move back to mps if necessary
1016
+ out = out[
1017
+ :,
1018
+ max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0),
1019
+ max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0),
1020
+ :,
1021
+ ]
1022
+
1023
+ out = out.permute(0, 3, 1, 2)
1024
+ out = out.reshape([-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1])
1025
+ w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
1026
+ out = F.conv2d(out, w)
1027
+ out = out.reshape(
1028
+ -1,
1029
+ minor,
1030
+ in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
1031
+ in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
1032
+ )
1033
+ out = out.permute(0, 2, 3, 1)
1034
+ out = out[:, ::down_y, ::down_x, :]
1035
+
1036
+ out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
1037
+ out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
1038
+
1039
+ return out.view(-1, channel, out_h, out_w)
1040
+
1041
+
1042
+ class TemporalConvLayer(nn.Module):
1043
+ """
1044
+ Temporal convolutional layer that can be used for video (sequence of images) input Code mostly copied from:
1045
+ https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/models/multi_modal/video_synthesis/unet_sd.py#L1016
1046
+
1047
+ Parameters:
1048
+ in_dim (`int`): Number of input channels.
1049
+ out_dim (`int`): Number of output channels.
1050
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
1051
+ """
1052
+
1053
+ def __init__(
1054
+ self,
1055
+ in_dim: int,
1056
+ out_dim: Optional[int] = None,
1057
+ dropout: float = 0.0,
1058
+ norm_num_groups: int = 32,
1059
+ ):
1060
+ super().__init__()
1061
+ out_dim = out_dim or in_dim
1062
+ self.in_dim = in_dim
1063
+ self.out_dim = out_dim
1064
+
1065
+ # conv layers
1066
+ self.conv1 = nn.Sequential(
1067
+ nn.GroupNorm(norm_num_groups, in_dim),
1068
+ nn.SiLU(),
1069
+ nn.Conv3d(in_dim, out_dim, (3, 1, 1), padding=(1, 0, 0)),
1070
+ )
1071
+ self.conv2 = nn.Sequential(
1072
+ nn.GroupNorm(norm_num_groups, out_dim),
1073
+ nn.SiLU(),
1074
+ nn.Dropout(dropout),
1075
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
1076
+ )
1077
+ self.conv3 = nn.Sequential(
1078
+ nn.GroupNorm(norm_num_groups, out_dim),
1079
+ nn.SiLU(),
1080
+ nn.Dropout(dropout),
1081
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
1082
+ )
1083
+ self.conv4 = nn.Sequential(
1084
+ nn.GroupNorm(norm_num_groups, out_dim),
1085
+ nn.SiLU(),
1086
+ nn.Dropout(dropout),
1087
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
1088
+ )
1089
+
1090
+ # zero out the last layer params,so the conv block is identity
1091
+ nn.init.zeros_(self.conv4[-1].weight)
1092
+ nn.init.zeros_(self.conv4[-1].bias)
1093
+
1094
+ def forward(self, hidden_states: torch.Tensor, num_frames: int = 1) -> torch.Tensor:
1095
+ hidden_states = (
1096
+ hidden_states[None, :].reshape((-1, num_frames) + hidden_states.shape[1:]).permute(0, 2, 1, 3, 4)
1097
+ )
1098
+
1099
+ identity = hidden_states
1100
+ hidden_states = self.conv1(hidden_states)
1101
+ hidden_states = self.conv2(hidden_states)
1102
+ hidden_states = self.conv3(hidden_states)
1103
+ hidden_states = self.conv4(hidden_states)
1104
+
1105
+ hidden_states = identity + hidden_states
1106
+
1107
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(
1108
+ (hidden_states.shape[0] * hidden_states.shape[2], -1) + hidden_states.shape[3:]
1109
+ )
1110
+ return hidden_states
1111
+
1112
+
1113
+ class TemporalResnetBlock(nn.Module):
1114
+ r"""
1115
+ A Resnet block.
1116
+
1117
+ Parameters:
1118
+ in_channels (`int`): The number of channels in the input.
1119
+ out_channels (`int`, *optional*, default to be `None`):
1120
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
1121
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
1122
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
1123
+ """
1124
+
1125
+ def __init__(
1126
+ self,
1127
+ in_channels: int,
1128
+ out_channels: Optional[int] = None,
1129
+ temb_channels: int = 512,
1130
+ eps: float = 1e-6,
1131
+ ):
1132
+ super().__init__()
1133
+ self.in_channels = in_channels
1134
+ out_channels = in_channels if out_channels is None else out_channels
1135
+ self.out_channels = out_channels
1136
+
1137
+ kernel_size = (3, 1, 1)
1138
+ padding = [k // 2 for k in kernel_size]
1139
+
1140
+ self.norm1 = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=eps, affine=True)
1141
+ self.conv1 = nn.Conv3d(
1142
+ in_channels,
1143
+ out_channels,
1144
+ kernel_size=kernel_size,
1145
+ stride=1,
1146
+ padding=padding,
1147
+ )
1148
+
1149
+ if temb_channels is not None:
1150
+ self.time_emb_proj = nn.Linear(temb_channels, out_channels)
1151
+ else:
1152
+ self.time_emb_proj = None
1153
+
1154
+ self.norm2 = torch.nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=eps, affine=True)
1155
+
1156
+ self.dropout = torch.nn.Dropout(0.0)
1157
+ self.conv2 = nn.Conv3d(
1158
+ out_channels,
1159
+ out_channels,
1160
+ kernel_size=kernel_size,
1161
+ stride=1,
1162
+ padding=padding,
1163
+ )
1164
+
1165
+ self.nonlinearity = get_activation("silu")
1166
+
1167
+ self.use_in_shortcut = self.in_channels != out_channels
1168
+
1169
+ self.conv_shortcut = None
1170
+ if self.use_in_shortcut:
1171
+ self.conv_shortcut = nn.Conv3d(
1172
+ in_channels,
1173
+ out_channels,
1174
+ kernel_size=1,
1175
+ stride=1,
1176
+ padding=0,
1177
+ )
1178
+
1179
+ def forward(self, input_tensor: torch.FloatTensor, temb: torch.FloatTensor) -> torch.FloatTensor:
1180
+ hidden_states = input_tensor
1181
+
1182
+ hidden_states = self.norm1(hidden_states)
1183
+ hidden_states = self.nonlinearity(hidden_states)
1184
+ hidden_states = self.conv1(hidden_states)
1185
+
1186
+ if self.time_emb_proj is not None:
1187
+ temb = self.nonlinearity(temb)
1188
+ temb = self.time_emb_proj(temb)[:, :, :, None, None]
1189
+ temb = temb.permute(0, 2, 1, 3, 4)
1190
+ hidden_states = hidden_states + temb
1191
+
1192
+ hidden_states = self.norm2(hidden_states)
1193
+ hidden_states = self.nonlinearity(hidden_states)
1194
+ hidden_states = self.dropout(hidden_states)
1195
+ hidden_states = self.conv2(hidden_states)
1196
+
1197
+ if self.conv_shortcut is not None:
1198
+ input_tensor = self.conv_shortcut(input_tensor)
1199
+
1200
+ output_tensor = input_tensor + hidden_states
1201
+
1202
+ return output_tensor
1203
+
1204
+
1205
+ # VideoResBlock
1206
+ class SpatioTemporalResBlock(nn.Module):
1207
+ r"""
1208
+ A SpatioTemporal Resnet block.
1209
+
1210
+ Parameters:
1211
+ in_channels (`int`): The number of channels in the input.
1212
+ out_channels (`int`, *optional*, default to be `None`):
1213
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
1214
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
1215
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the spatial resenet.
1216
+ temporal_eps (`float`, *optional*, defaults to `eps`): The epsilon to use for the temporal resnet.
1217
+ merge_factor (`float`, *optional*, defaults to `0.5`): The merge factor to use for the temporal mixing.
1218
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
1219
+ The merge strategy to use for the temporal mixing.
1220
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
1221
+ If `True`, switch the spatial and temporal mixing.
1222
+ """
1223
+
1224
+ def __init__(
1225
+ self,
1226
+ in_channels: int,
1227
+ out_channels: Optional[int] = None,
1228
+ temb_channels: int = 512,
1229
+ eps: float = 1e-6,
1230
+ temporal_eps: Optional[float] = None,
1231
+ merge_factor: float = 0.5,
1232
+ merge_strategy="learned_with_images",
1233
+ switch_spatial_to_temporal_mix: bool = False,
1234
+ ):
1235
+ super().__init__()
1236
+
1237
+ self.spatial_res_block = ResnetBlock2D(
1238
+ in_channels=in_channels,
1239
+ out_channels=out_channels,
1240
+ temb_channels=temb_channels,
1241
+ eps=eps,
1242
+ )
1243
+
1244
+ self.temporal_res_block = TemporalResnetBlock(
1245
+ in_channels=out_channels if out_channels is not None else in_channels,
1246
+ out_channels=out_channels if out_channels is not None else in_channels,
1247
+ temb_channels=temb_channels,
1248
+ eps=temporal_eps if temporal_eps is not None else eps,
1249
+ )
1250
+
1251
+ self.time_mixer = AlphaBlender(
1252
+ alpha=merge_factor,
1253
+ merge_strategy=merge_strategy,
1254
+ switch_spatial_to_temporal_mix=switch_spatial_to_temporal_mix,
1255
+ )
1256
+
1257
+ def forward(
1258
+ self,
1259
+ hidden_states: torch.FloatTensor,
1260
+ temb: Optional[torch.FloatTensor] = None,
1261
+ image_only_indicator: Optional[torch.Tensor] = None,
1262
+ ):
1263
+ num_frames = image_only_indicator.shape[-1]
1264
+ hidden_states = self.spatial_res_block(hidden_states, temb)
1265
+
1266
+ batch_frames, channels, height, width = hidden_states.shape
1267
+ batch_size = batch_frames // num_frames
1268
+
1269
+ hidden_states_mix = (
1270
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
1271
+ )
1272
+ hidden_states = (
1273
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
1274
+ )
1275
+
1276
+ if temb is not None:
1277
+ temb = temb.reshape(batch_size, num_frames, -1)
1278
+
1279
+ hidden_states = self.temporal_res_block(hidden_states, temb)
1280
+ hidden_states = self.time_mixer(
1281
+ x_spatial=hidden_states_mix,
1282
+ x_temporal=hidden_states,
1283
+ image_only_indicator=image_only_indicator,
1284
+ )
1285
+
1286
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
1287
+ return hidden_states
1288
+
1289
+
1290
+ class AlphaBlender(nn.Module):
1291
+ r"""
1292
+ A module to blend spatial and temporal features.
1293
+
1294
+ Parameters:
1295
+ alpha (`float`): The initial value of the blending factor.
1296
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
1297
+ The merge strategy to use for the temporal mixing.
1298
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
1299
+ If `True`, switch the spatial and temporal mixing.
1300
+ """
1301
+
1302
+ strategies = ["learned", "fixed", "learned_with_images"]
1303
+
1304
+ def __init__(
1305
+ self,
1306
+ alpha: float,
1307
+ merge_strategy: str = "learned_with_images",
1308
+ switch_spatial_to_temporal_mix: bool = False,
1309
+ ):
1310
+ super().__init__()
1311
+ self.merge_strategy = merge_strategy
1312
+ self.switch_spatial_to_temporal_mix = switch_spatial_to_temporal_mix # For TemporalVAE
1313
+
1314
+ if merge_strategy not in self.strategies:
1315
+ raise ValueError(f"merge_strategy needs to be in {self.strategies}")
1316
+
1317
+ if self.merge_strategy == "fixed":
1318
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
1319
+ elif self.merge_strategy == "learned" or self.merge_strategy == "learned_with_images":
1320
+ self.register_parameter("mix_factor", torch.nn.Parameter(torch.Tensor([alpha])))
1321
+ else:
1322
+ raise ValueError(f"Unknown merge strategy {self.merge_strategy}")
1323
+
1324
+ def get_alpha(self, image_only_indicator: torch.Tensor, ndims: int) -> torch.Tensor:
1325
+ if self.merge_strategy == "fixed":
1326
+ alpha = self.mix_factor
1327
+
1328
+ elif self.merge_strategy == "learned":
1329
+ alpha = torch.sigmoid(self.mix_factor)
1330
+
1331
+ elif self.merge_strategy == "learned_with_images":
1332
+ if image_only_indicator is None:
1333
+ raise ValueError("Please provide image_only_indicator to use learned_with_images merge strategy")
1334
+
1335
+ alpha = torch.where(
1336
+ image_only_indicator.bool(),
1337
+ torch.ones(1, 1, device=image_only_indicator.device),
1338
+ torch.sigmoid(self.mix_factor)[..., None],
1339
+ )
1340
+
1341
+ # (batch, channel, frames, height, width)
1342
+ if ndims == 5:
1343
+ alpha = alpha[:, None, :, None, None]
1344
+ # (batch*frames, height*width, channels)
1345
+ elif ndims == 3:
1346
+ alpha = alpha.reshape(-1)[:, None, None]
1347
+ else:
1348
+ raise ValueError(f"Unexpected ndims {ndims}. Dimensions should be 3 or 5")
1349
+
1350
+ else:
1351
+ raise NotImplementedError
1352
+
1353
+ return alpha
1354
+
1355
+ def forward(
1356
+ self,
1357
+ x_spatial: torch.Tensor,
1358
+ x_temporal: torch.Tensor,
1359
+ image_only_indicator: Optional[torch.Tensor] = None,
1360
+ ) -> torch.Tensor:
1361
+ alpha = self.get_alpha(image_only_indicator, x_spatial.ndim)
1362
+ alpha = alpha.to(x_spatial.dtype)
1363
+
1364
+ if self.switch_spatial_to_temporal_mix:
1365
+ alpha = 1.0 - alpha
1366
+
1367
+ x = alpha * x_spatial + (1.0 - alpha) * x_temporal
1368
+ return x
diffusers/models/resnet_flax.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 flax.linen as nn
15
+ import jax
16
+ import jax.numpy as jnp
17
+
18
+
19
+ class FlaxUpsample2D(nn.Module):
20
+ out_channels: int
21
+ dtype: jnp.dtype = jnp.float32
22
+
23
+ def setup(self):
24
+ self.conv = nn.Conv(
25
+ self.out_channels,
26
+ kernel_size=(3, 3),
27
+ strides=(1, 1),
28
+ padding=((1, 1), (1, 1)),
29
+ dtype=self.dtype,
30
+ )
31
+
32
+ def __call__(self, hidden_states):
33
+ batch, height, width, channels = hidden_states.shape
34
+ hidden_states = jax.image.resize(
35
+ hidden_states,
36
+ shape=(batch, height * 2, width * 2, channels),
37
+ method="nearest",
38
+ )
39
+ hidden_states = self.conv(hidden_states)
40
+ return hidden_states
41
+
42
+
43
+ class FlaxDownsample2D(nn.Module):
44
+ out_channels: int
45
+ dtype: jnp.dtype = jnp.float32
46
+
47
+ def setup(self):
48
+ self.conv = nn.Conv(
49
+ self.out_channels,
50
+ kernel_size=(3, 3),
51
+ strides=(2, 2),
52
+ padding=((1, 1), (1, 1)), # padding="VALID",
53
+ dtype=self.dtype,
54
+ )
55
+
56
+ def __call__(self, hidden_states):
57
+ # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
58
+ # hidden_states = jnp.pad(hidden_states, pad_width=pad)
59
+ hidden_states = self.conv(hidden_states)
60
+ return hidden_states
61
+
62
+
63
+ class FlaxResnetBlock2D(nn.Module):
64
+ in_channels: int
65
+ out_channels: int = None
66
+ dropout_prob: float = 0.0
67
+ use_nin_shortcut: bool = None
68
+ dtype: jnp.dtype = jnp.float32
69
+
70
+ def setup(self):
71
+ out_channels = self.in_channels if self.out_channels is None else self.out_channels
72
+
73
+ self.norm1 = nn.GroupNorm(num_groups=32, epsilon=1e-5)
74
+ self.conv1 = nn.Conv(
75
+ out_channels,
76
+ kernel_size=(3, 3),
77
+ strides=(1, 1),
78
+ padding=((1, 1), (1, 1)),
79
+ dtype=self.dtype,
80
+ )
81
+
82
+ self.time_emb_proj = nn.Dense(out_channels, dtype=self.dtype)
83
+
84
+ self.norm2 = nn.GroupNorm(num_groups=32, epsilon=1e-5)
85
+ self.dropout = nn.Dropout(self.dropout_prob)
86
+ self.conv2 = nn.Conv(
87
+ out_channels,
88
+ kernel_size=(3, 3),
89
+ strides=(1, 1),
90
+ padding=((1, 1), (1, 1)),
91
+ dtype=self.dtype,
92
+ )
93
+
94
+ use_nin_shortcut = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
95
+
96
+ self.conv_shortcut = None
97
+ if use_nin_shortcut:
98
+ self.conv_shortcut = nn.Conv(
99
+ out_channels,
100
+ kernel_size=(1, 1),
101
+ strides=(1, 1),
102
+ padding="VALID",
103
+ dtype=self.dtype,
104
+ )
105
+
106
+ def __call__(self, hidden_states, temb, deterministic=True):
107
+ residual = hidden_states
108
+ hidden_states = self.norm1(hidden_states)
109
+ hidden_states = nn.swish(hidden_states)
110
+ hidden_states = self.conv1(hidden_states)
111
+
112
+ temb = self.time_emb_proj(nn.swish(temb))
113
+ temb = jnp.expand_dims(jnp.expand_dims(temb, 1), 1)
114
+ hidden_states = hidden_states + temb
115
+
116
+ hidden_states = self.norm2(hidden_states)
117
+ hidden_states = nn.swish(hidden_states)
118
+ hidden_states = self.dropout(hidden_states, deterministic)
119
+ hidden_states = self.conv2(hidden_states)
120
+
121
+ if self.conv_shortcut is not None:
122
+ residual = self.conv_shortcut(residual)
123
+
124
+ return hidden_states + residual
diffusers/models/t5_film_transformer.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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 math
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from ..configuration_utils import ConfigMixin, register_to_config
21
+ from .attention_processor import Attention
22
+ from .embeddings import get_timestep_embedding
23
+ from .modeling_utils import ModelMixin
24
+
25
+
26
+ class T5FilmDecoder(ModelMixin, ConfigMixin):
27
+ r"""
28
+ T5 style decoder with FiLM conditioning.
29
+
30
+ Args:
31
+ input_dims (`int`, *optional*, defaults to `128`):
32
+ The number of input dimensions.
33
+ targets_length (`int`, *optional*, defaults to `256`):
34
+ The length of the targets.
35
+ d_model (`int`, *optional*, defaults to `768`):
36
+ Size of the input hidden states.
37
+ num_layers (`int`, *optional*, defaults to `12`):
38
+ The number of `DecoderLayer`'s to use.
39
+ num_heads (`int`, *optional*, defaults to `12`):
40
+ The number of attention heads to use.
41
+ d_kv (`int`, *optional*, defaults to `64`):
42
+ Size of the key-value projection vectors.
43
+ d_ff (`int`, *optional*, defaults to `2048`):
44
+ The number of dimensions in the intermediate feed-forward layer of `DecoderLayer`'s.
45
+ dropout_rate (`float`, *optional*, defaults to `0.1`):
46
+ Dropout probability.
47
+ """
48
+
49
+ @register_to_config
50
+ def __init__(
51
+ self,
52
+ input_dims: int = 128,
53
+ targets_length: int = 256,
54
+ max_decoder_noise_time: float = 2000.0,
55
+ d_model: int = 768,
56
+ num_layers: int = 12,
57
+ num_heads: int = 12,
58
+ d_kv: int = 64,
59
+ d_ff: int = 2048,
60
+ dropout_rate: float = 0.1,
61
+ ):
62
+ super().__init__()
63
+
64
+ self.conditioning_emb = nn.Sequential(
65
+ nn.Linear(d_model, d_model * 4, bias=False),
66
+ nn.SiLU(),
67
+ nn.Linear(d_model * 4, d_model * 4, bias=False),
68
+ nn.SiLU(),
69
+ )
70
+
71
+ self.position_encoding = nn.Embedding(targets_length, d_model)
72
+ self.position_encoding.weight.requires_grad = False
73
+
74
+ self.continuous_inputs_projection = nn.Linear(input_dims, d_model, bias=False)
75
+
76
+ self.dropout = nn.Dropout(p=dropout_rate)
77
+
78
+ self.decoders = nn.ModuleList()
79
+ for lyr_num in range(num_layers):
80
+ # FiLM conditional T5 decoder
81
+ lyr = DecoderLayer(d_model=d_model, d_kv=d_kv, num_heads=num_heads, d_ff=d_ff, dropout_rate=dropout_rate)
82
+ self.decoders.append(lyr)
83
+
84
+ self.decoder_norm = T5LayerNorm(d_model)
85
+
86
+ self.post_dropout = nn.Dropout(p=dropout_rate)
87
+ self.spec_out = nn.Linear(d_model, input_dims, bias=False)
88
+
89
+ def encoder_decoder_mask(self, query_input: torch.FloatTensor, key_input: torch.FloatTensor) -> torch.FloatTensor:
90
+ mask = torch.mul(query_input.unsqueeze(-1), key_input.unsqueeze(-2))
91
+ return mask.unsqueeze(-3)
92
+
93
+ def forward(self, encodings_and_masks, decoder_input_tokens, decoder_noise_time):
94
+ batch, _, _ = decoder_input_tokens.shape
95
+ assert decoder_noise_time.shape == (batch,)
96
+
97
+ # decoder_noise_time is in [0, 1), so rescale to expected timing range.
98
+ time_steps = get_timestep_embedding(
99
+ decoder_noise_time * self.config.max_decoder_noise_time,
100
+ embedding_dim=self.config.d_model,
101
+ max_period=self.config.max_decoder_noise_time,
102
+ ).to(dtype=self.dtype)
103
+
104
+ conditioning_emb = self.conditioning_emb(time_steps).unsqueeze(1)
105
+
106
+ assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)
107
+
108
+ seq_length = decoder_input_tokens.shape[1]
109
+
110
+ # If we want to use relative positions for audio context, we can just offset
111
+ # this sequence by the length of encodings_and_masks.
112
+ decoder_positions = torch.broadcast_to(
113
+ torch.arange(seq_length, device=decoder_input_tokens.device),
114
+ (batch, seq_length),
115
+ )
116
+
117
+ position_encodings = self.position_encoding(decoder_positions)
118
+
119
+ inputs = self.continuous_inputs_projection(decoder_input_tokens)
120
+ inputs += position_encodings
121
+ y = self.dropout(inputs)
122
+
123
+ # decoder: No padding present.
124
+ decoder_mask = torch.ones(
125
+ decoder_input_tokens.shape[:2], device=decoder_input_tokens.device, dtype=inputs.dtype
126
+ )
127
+
128
+ # Translate encoding masks to encoder-decoder masks.
129
+ encodings_and_encdec_masks = [(x, self.encoder_decoder_mask(decoder_mask, y)) for x, y in encodings_and_masks]
130
+
131
+ # cross attend style: concat encodings
132
+ encoded = torch.cat([x[0] for x in encodings_and_encdec_masks], dim=1)
133
+ encoder_decoder_mask = torch.cat([x[1] for x in encodings_and_encdec_masks], dim=-1)
134
+
135
+ for lyr in self.decoders:
136
+ y = lyr(
137
+ y,
138
+ conditioning_emb=conditioning_emb,
139
+ encoder_hidden_states=encoded,
140
+ encoder_attention_mask=encoder_decoder_mask,
141
+ )[0]
142
+
143
+ y = self.decoder_norm(y)
144
+ y = self.post_dropout(y)
145
+
146
+ spec_out = self.spec_out(y)
147
+ return spec_out
148
+
149
+
150
+ class DecoderLayer(nn.Module):
151
+ r"""
152
+ T5 decoder layer.
153
+
154
+ Args:
155
+ d_model (`int`):
156
+ Size of the input hidden states.
157
+ d_kv (`int`):
158
+ Size of the key-value projection vectors.
159
+ num_heads (`int`):
160
+ Number of attention heads.
161
+ d_ff (`int`):
162
+ Size of the intermediate feed-forward layer.
163
+ dropout_rate (`float`):
164
+ Dropout probability.
165
+ layer_norm_epsilon (`float`, *optional*, defaults to `1e-6`):
166
+ A small value used for numerical stability to avoid dividing by zero.
167
+ """
168
+
169
+ def __init__(
170
+ self, d_model: int, d_kv: int, num_heads: int, d_ff: int, dropout_rate: float, layer_norm_epsilon: float = 1e-6
171
+ ):
172
+ super().__init__()
173
+ self.layer = nn.ModuleList()
174
+
175
+ # cond self attention: layer 0
176
+ self.layer.append(
177
+ T5LayerSelfAttentionCond(d_model=d_model, d_kv=d_kv, num_heads=num_heads, dropout_rate=dropout_rate)
178
+ )
179
+
180
+ # cross attention: layer 1
181
+ self.layer.append(
182
+ T5LayerCrossAttention(
183
+ d_model=d_model,
184
+ d_kv=d_kv,
185
+ num_heads=num_heads,
186
+ dropout_rate=dropout_rate,
187
+ layer_norm_epsilon=layer_norm_epsilon,
188
+ )
189
+ )
190
+
191
+ # Film Cond MLP + dropout: last layer
192
+ self.layer.append(
193
+ T5LayerFFCond(d_model=d_model, d_ff=d_ff, dropout_rate=dropout_rate, layer_norm_epsilon=layer_norm_epsilon)
194
+ )
195
+
196
+ def forward(
197
+ self,
198
+ hidden_states: torch.FloatTensor,
199
+ conditioning_emb: Optional[torch.FloatTensor] = None,
200
+ attention_mask: Optional[torch.FloatTensor] = None,
201
+ encoder_hidden_states: Optional[torch.Tensor] = None,
202
+ encoder_attention_mask: Optional[torch.Tensor] = None,
203
+ encoder_decoder_position_bias=None,
204
+ ) -> Tuple[torch.FloatTensor]:
205
+ hidden_states = self.layer[0](
206
+ hidden_states,
207
+ conditioning_emb=conditioning_emb,
208
+ attention_mask=attention_mask,
209
+ )
210
+
211
+ if encoder_hidden_states is not None:
212
+ encoder_extended_attention_mask = torch.where(encoder_attention_mask > 0, 0, -1e10).to(
213
+ encoder_hidden_states.dtype
214
+ )
215
+
216
+ hidden_states = self.layer[1](
217
+ hidden_states,
218
+ key_value_states=encoder_hidden_states,
219
+ attention_mask=encoder_extended_attention_mask,
220
+ )
221
+
222
+ # Apply Film Conditional Feed Forward layer
223
+ hidden_states = self.layer[-1](hidden_states, conditioning_emb)
224
+
225
+ return (hidden_states,)
226
+
227
+
228
+ class T5LayerSelfAttentionCond(nn.Module):
229
+ r"""
230
+ T5 style self-attention layer with conditioning.
231
+
232
+ Args:
233
+ d_model (`int`):
234
+ Size of the input hidden states.
235
+ d_kv (`int`):
236
+ Size of the key-value projection vectors.
237
+ num_heads (`int`):
238
+ Number of attention heads.
239
+ dropout_rate (`float`):
240
+ Dropout probability.
241
+ """
242
+
243
+ def __init__(self, d_model: int, d_kv: int, num_heads: int, dropout_rate: float):
244
+ super().__init__()
245
+ self.layer_norm = T5LayerNorm(d_model)
246
+ self.FiLMLayer = T5FiLMLayer(in_features=d_model * 4, out_features=d_model)
247
+ self.attention = Attention(query_dim=d_model, heads=num_heads, dim_head=d_kv, out_bias=False, scale_qk=False)
248
+ self.dropout = nn.Dropout(dropout_rate)
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.FloatTensor,
253
+ conditioning_emb: Optional[torch.FloatTensor] = None,
254
+ attention_mask: Optional[torch.FloatTensor] = None,
255
+ ) -> torch.FloatTensor:
256
+ # pre_self_attention_layer_norm
257
+ normed_hidden_states = self.layer_norm(hidden_states)
258
+
259
+ if conditioning_emb is not None:
260
+ normed_hidden_states = self.FiLMLayer(normed_hidden_states, conditioning_emb)
261
+
262
+ # Self-attention block
263
+ attention_output = self.attention(normed_hidden_states)
264
+
265
+ hidden_states = hidden_states + self.dropout(attention_output)
266
+
267
+ return hidden_states
268
+
269
+
270
+ class T5LayerCrossAttention(nn.Module):
271
+ r"""
272
+ T5 style cross-attention layer.
273
+
274
+ Args:
275
+ d_model (`int`):
276
+ Size of the input hidden states.
277
+ d_kv (`int`):
278
+ Size of the key-value projection vectors.
279
+ num_heads (`int`):
280
+ Number of attention heads.
281
+ dropout_rate (`float`):
282
+ Dropout probability.
283
+ layer_norm_epsilon (`float`):
284
+ A small value used for numerical stability to avoid dividing by zero.
285
+ """
286
+
287
+ def __init__(self, d_model: int, d_kv: int, num_heads: int, dropout_rate: float, layer_norm_epsilon: float):
288
+ super().__init__()
289
+ self.attention = Attention(query_dim=d_model, heads=num_heads, dim_head=d_kv, out_bias=False, scale_qk=False)
290
+ self.layer_norm = T5LayerNorm(d_model, eps=layer_norm_epsilon)
291
+ self.dropout = nn.Dropout(dropout_rate)
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.FloatTensor,
296
+ key_value_states: Optional[torch.FloatTensor] = None,
297
+ attention_mask: Optional[torch.FloatTensor] = None,
298
+ ) -> torch.FloatTensor:
299
+ normed_hidden_states = self.layer_norm(hidden_states)
300
+ attention_output = self.attention(
301
+ normed_hidden_states,
302
+ encoder_hidden_states=key_value_states,
303
+ attention_mask=attention_mask.squeeze(1),
304
+ )
305
+ layer_output = hidden_states + self.dropout(attention_output)
306
+ return layer_output
307
+
308
+
309
+ class T5LayerFFCond(nn.Module):
310
+ r"""
311
+ T5 style feed-forward conditional layer.
312
+
313
+ Args:
314
+ d_model (`int`):
315
+ Size of the input hidden states.
316
+ d_ff (`int`):
317
+ Size of the intermediate feed-forward layer.
318
+ dropout_rate (`float`):
319
+ Dropout probability.
320
+ layer_norm_epsilon (`float`):
321
+ A small value used for numerical stability to avoid dividing by zero.
322
+ """
323
+
324
+ def __init__(self, d_model: int, d_ff: int, dropout_rate: float, layer_norm_epsilon: float):
325
+ super().__init__()
326
+ self.DenseReluDense = T5DenseGatedActDense(d_model=d_model, d_ff=d_ff, dropout_rate=dropout_rate)
327
+ self.film = T5FiLMLayer(in_features=d_model * 4, out_features=d_model)
328
+ self.layer_norm = T5LayerNorm(d_model, eps=layer_norm_epsilon)
329
+ self.dropout = nn.Dropout(dropout_rate)
330
+
331
+ def forward(
332
+ self, hidden_states: torch.FloatTensor, conditioning_emb: Optional[torch.FloatTensor] = None
333
+ ) -> torch.FloatTensor:
334
+ forwarded_states = self.layer_norm(hidden_states)
335
+ if conditioning_emb is not None:
336
+ forwarded_states = self.film(forwarded_states, conditioning_emb)
337
+
338
+ forwarded_states = self.DenseReluDense(forwarded_states)
339
+ hidden_states = hidden_states + self.dropout(forwarded_states)
340
+ return hidden_states
341
+
342
+
343
+ class T5DenseGatedActDense(nn.Module):
344
+ r"""
345
+ T5 style feed-forward layer with gated activations and dropout.
346
+
347
+ Args:
348
+ d_model (`int`):
349
+ Size of the input hidden states.
350
+ d_ff (`int`):
351
+ Size of the intermediate feed-forward layer.
352
+ dropout_rate (`float`):
353
+ Dropout probability.
354
+ """
355
+
356
+ def __init__(self, d_model: int, d_ff: int, dropout_rate: float):
357
+ super().__init__()
358
+ self.wi_0 = nn.Linear(d_model, d_ff, bias=False)
359
+ self.wi_1 = nn.Linear(d_model, d_ff, bias=False)
360
+ self.wo = nn.Linear(d_ff, d_model, bias=False)
361
+ self.dropout = nn.Dropout(dropout_rate)
362
+ self.act = NewGELUActivation()
363
+
364
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
365
+ hidden_gelu = self.act(self.wi_0(hidden_states))
366
+ hidden_linear = self.wi_1(hidden_states)
367
+ hidden_states = hidden_gelu * hidden_linear
368
+ hidden_states = self.dropout(hidden_states)
369
+
370
+ hidden_states = self.wo(hidden_states)
371
+ return hidden_states
372
+
373
+
374
+ class T5LayerNorm(nn.Module):
375
+ r"""
376
+ T5 style layer normalization module.
377
+
378
+ Args:
379
+ hidden_size (`int`):
380
+ Size of the input hidden states.
381
+ eps (`float`, `optional`, defaults to `1e-6`):
382
+ A small value used for numerical stability to avoid dividing by zero.
383
+ """
384
+
385
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
386
+ """
387
+ Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
388
+ """
389
+ super().__init__()
390
+ self.weight = nn.Parameter(torch.ones(hidden_size))
391
+ self.variance_epsilon = eps
392
+
393
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
394
+ # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
395
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated
396
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
397
+ # half-precision inputs is done in fp32
398
+
399
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
400
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
401
+
402
+ # convert into half-precision if necessary
403
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
404
+ hidden_states = hidden_states.to(self.weight.dtype)
405
+
406
+ return self.weight * hidden_states
407
+
408
+
409
+ class NewGELUActivation(nn.Module):
410
+ """
411
+ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
412
+ the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
413
+ """
414
+
415
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
416
+ return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
417
+
418
+
419
+ class T5FiLMLayer(nn.Module):
420
+ """
421
+ T5 style FiLM Layer.
422
+
423
+ Args:
424
+ in_features (`int`):
425
+ Number of input features.
426
+ out_features (`int`):
427
+ Number of output features.
428
+ """
429
+
430
+ def __init__(self, in_features: int, out_features: int):
431
+ super().__init__()
432
+ self.scale_bias = nn.Linear(in_features, out_features * 2, bias=False)
433
+
434
+ def forward(self, x: torch.FloatTensor, conditioning_emb: torch.FloatTensor) -> torch.FloatTensor:
435
+ emb = self.scale_bias(conditioning_emb)
436
+ scale, shift = torch.chunk(emb, 2, -1)
437
+ x = x * (1 + scale) + shift
438
+ return x