JOY-Huang commited on
Commit
025b1f9
1 Parent(s): 102bf04

remove local diffusers

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. app.py +75 -158
  2. diffusers/__init__.py +0 -797
  3. diffusers/commands/__init__.py +0 -27
  4. diffusers/commands/diffusers_cli.py +0 -43
  5. diffusers/commands/env.py +0 -84
  6. diffusers/commands/fp16_safetensors.py +0 -132
  7. diffusers/configuration_utils.py +0 -704
  8. diffusers/dependency_versions_check.py +0 -34
  9. diffusers/dependency_versions_table.py +0 -46
  10. diffusers/experimental/README.md +0 -5
  11. diffusers/experimental/__init__.py +0 -1
  12. diffusers/experimental/rl/__init__.py +0 -1
  13. diffusers/experimental/rl/value_guided_sampling.py +0 -153
  14. diffusers/image_processor.py +0 -1070
  15. diffusers/loaders/__init__.py +0 -88
  16. diffusers/loaders/autoencoder.py +0 -146
  17. diffusers/loaders/controlnet.py +0 -136
  18. diffusers/loaders/ip_adapter.py +0 -339
  19. diffusers/loaders/lora.py +0 -1458
  20. diffusers/loaders/lora_conversion_utils.py +0 -287
  21. diffusers/loaders/peft.py +0 -187
  22. diffusers/loaders/single_file.py +0 -323
  23. diffusers/loaders/single_file_utils.py +0 -1609
  24. diffusers/loaders/textual_inversion.py +0 -582
  25. diffusers/loaders/unet.py +0 -1161
  26. diffusers/loaders/unet_loader_utils.py +0 -163
  27. diffusers/loaders/utils.py +0 -59
  28. diffusers/models/README.md +0 -3
  29. diffusers/models/__init__.py +0 -105
  30. diffusers/models/activations.py +0 -131
  31. diffusers/models/adapter.py +0 -584
  32. diffusers/models/attention.py +0 -678
  33. diffusers/models/attention_flax.py +0 -494
  34. diffusers/models/attention_processor.py +0 -0
  35. diffusers/models/autoencoders/__init__.py +0 -5
  36. diffusers/models/autoencoders/autoencoder_asym_kl.py +0 -186
  37. diffusers/models/autoencoders/autoencoder_kl.py +0 -490
  38. diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +0 -399
  39. diffusers/models/autoencoders/autoencoder_tiny.py +0 -349
  40. diffusers/models/autoencoders/consistency_decoder_vae.py +0 -462
  41. diffusers/models/autoencoders/vae.py +0 -981
  42. diffusers/models/controlnet.py +0 -907
  43. diffusers/models/controlnet_flax.py +0 -395
  44. diffusers/models/controlnet_xs.py +0 -1915
  45. diffusers/models/downsampling.py +0 -333
  46. diffusers/models/dual_transformer_2d.py +0 -20
  47. diffusers/models/embeddings.py +0 -1037
  48. diffusers/models/embeddings_flax.py +0 -97
  49. diffusers/models/lora.py +0 -457
  50. diffusers/models/modeling_flax_pytorch_utils.py +0 -135
app.py CHANGED
@@ -1,45 +1,26 @@
1
  import os
2
  import torch
3
- import random
4
  import numpy as np
5
- import gradio as gr
6
  from PIL import Image
7
- from torchvision import transforms
8
 
9
- from diffusers import (
10
- DDPMScheduler,
11
- StableDiffusionXLPipeline
12
- )
13
  from schedulers.lcm_single_step_scheduler import LCMSingleStepScheduler
14
- from diffusers.utils import convert_unet_state_dict_to_peft
15
- from peft import LoraConfig, set_peft_model_state_dict
16
- from transformers import (
17
- AutoImageProcessor, AutoModel
18
- )
19
 
20
- from module.ip_adapter.utils import init_ip_adapter_in_unet
21
- from module.ip_adapter.resampler import Resampler
22
- from module.aggregator import Aggregator
23
- from pipelines.sdxl_instantir import InstantIRPipeline, LCM_LORA_MODULES, PREVIEWER_LORA_MODULES
24
 
25
  from huggingface_hub import hf_hub_download
26
 
27
- if not os.path.exists("checkpoints/adapter.pt"):
28
- hf_hub_download(repo_id="InstantX/InstantIR", filename="adapter.pt", local_dir="./checkpoints")
29
- if not os.path.exists("checkpoints/aggregator.pt"):
30
- hf_hub_download(repo_id="InstantX/InstantIR", filename="aggregator.pt", local_dir="./checkpoints")
31
- if not os.path.exists("checkpoints/previewer_lora_weights.bin"):
32
- hf_hub_download(repo_id="InstantX/InstantIR", filename="previewer_lora_weights.bin", local_dir="./checkpoints")
33
-
34
-
35
- transform = transforms.Compose([
36
- transforms.Resize(1024, interpolation=transforms.InterpolationMode.BILINEAR),
37
- transforms.CenterCrop(1024),
38
- ])
39
 
40
  device = "cuda" if torch.cuda.is_available() else "cpu"
41
  sdxl_repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
42
- instantir_repo_id = "InstantX/InstantIR"
43
  dinov2_repo_id = "facebook/dinov2-large"
44
 
45
  if torch.cuda.is_available():
@@ -47,105 +28,30 @@ if torch.cuda.is_available():
47
  else:
48
  torch_dtype = torch.float32
49
 
50
- print("Loading vision encoder...")
51
- image_encoder = AutoModel.from_pretrained(dinov2_repo_id, torch_dtype=torch_dtype)
52
- image_processor = AutoImageProcessor.from_pretrained(dinov2_repo_id)
53
-
54
  print("Loading SDXL...")
55
- pipe = StableDiffusionXLPipeline.from_pretrained(
56
  sdxl_repo_id,
57
- torch_dtype=torch.float16,
58
  )
59
- unet = pipe.unet
60
-
61
- print("Initializing Aggregator...")
62
- aggregator = Aggregator.from_unet(unet, load_weights_from_unet=False)
63
 
 
64
  print("Loading LQ-Adapter...")
65
- image_proj_model = Resampler(
66
- dim=1280,
67
- depth=4,
68
- dim_head=64,
69
- heads=20,
70
- num_queries=64,
71
- embedding_dim=image_encoder.config.hidden_size,
72
- output_dim=unet.config.cross_attention_dim,
73
- ff_mult=4
74
- )
75
- init_ip_adapter_in_unet(
76
- unet,
77
- image_proj_model,
78
- "checkpoints/adapter.pt",
79
- adapter_tokens=64,
80
  )
81
- print("Initializing InstantIR...")
82
- pipe = InstantIRPipeline(
83
- pipe.vae, pipe.text_encoder, pipe.text_encoder_2, pipe.tokenizer, pipe.tokenizer_2,
84
- unet, aggregator, pipe.scheduler, feature_extractor=image_processor, image_encoder=image_encoder,
85
- )
86
-
87
- # Add Previewer LoRA.
88
- lora_state_dict, alpha_dict = StableDiffusionXLPipeline.lora_state_dict(
89
- "checkpoints/previewer_lora_weights.bin",
90
- # weight_name="previewer_lora_weights.bin",
91
 
92
- )
93
- unet_state_dict = {
94
- f'{k.replace("unet.", "")}': v for k, v in lora_state_dict.items() if k.startswith("unet.")
95
- }
96
- unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
97
- lora_state_dict = dict()
98
- for k, v in unet_state_dict.items():
99
- if "ip" in k:
100
- k = k.replace("attn2", "attn2.processor")
101
- lora_state_dict[k] = v
102
- else:
103
- lora_state_dict[k] = v
104
- if alpha_dict:
105
- lora_alpha = next(iter(alpha_dict.values()))
106
- else:
107
- lora_alpha = 1
108
  print(f"use lora alpha {lora_alpha}")
109
- lora_config = LoraConfig(
110
- r=64,
111
- target_modules=PREVIEWER_LORA_MODULES,
112
- lora_alpha=lora_alpha,
113
- lora_dropout=0.0,
114
- )
115
-
116
- # Add LCM LoRA.
117
- lora_state_dict, alpha_dict = StableDiffusionXLPipeline.lora_state_dict(
118
- "latent-consistency/lcm-lora-sdxl"
119
- )
120
- unet_state_dict = {
121
- f'{k.replace("unet.", "")}': v for k, v in lora_state_dict.items() if k.startswith("unet.")
122
- }
123
- unet_state_dict = convert_unet_state_dict_to_peft(unet_state_dict)
124
- if alpha_dict:
125
- lora_alpha = next(iter(alpha_dict.values()))
126
- else:
127
- lora_alpha = 1
128
  print(f"use lora alpha {lora_alpha}")
129
- lora_config = LoraConfig(
130
- r=64,
131
- target_modules=LCM_LORA_MODULES,
132
- lora_alpha=lora_alpha,
133
- lora_dropout=0.0,
134
- )
135
-
136
- unet.add_adapter(lora_config, "lcm")
137
- incompatible_keys = set_peft_model_state_dict(unet, unet_state_dict, adapter_name="lcm")
138
- if incompatible_keys is not None:
139
- # check only for unexpected keys
140
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
141
- missing_keys = getattr(incompatible_keys, "missing_keys", None)
142
- if unexpected_keys:
143
- raise ValueError(
144
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
145
- f" {unexpected_keys}. "
146
- )
147
 
148
- unet.disable_adapters()
149
  pipe.scheduler = DDPMScheduler.from_pretrained(
150
  sdxl_repo_id,
151
  subfolder="scheduler"
@@ -154,17 +60,25 @@ lcm_scheduler = LCMSingleStepScheduler.from_config(pipe.scheduler.config)
154
  # Load weights.
155
  print("Loading checkpoint...")
156
  aggregator_state_dict = torch.load(
157
- "checkpoints/aggregator.pt",
158
  map_location="cpu"
159
  )
160
- aggregator.load_state_dict(aggregator_state_dict, strict=True)
161
- aggregator.to(dtype=torch.float16)
162
- unet.to(dtype=torch.float16)
163
- pipe=pipe.to(device)
164
 
165
  MAX_SEED = np.iinfo(np.int32).max
166
  MAX_IMAGE_SIZE = 1024
167
 
 
 
 
 
 
 
 
 
 
 
168
  def unpack_pipe_out(preview_row, index):
169
  return preview_row[index][0]
170
 
@@ -179,37 +93,45 @@ def show_final_preview(preview_row):
179
  return preview_row[-1][0]
180
 
181
  # @spaces.GPU #[uncomment to use ZeroGPU]
182
- def instantir_restore(lq, prompt="", steps=30, cfg_scale=7.0, guidance_end=1.0, creative_restoration=False, seed=3407):
 
 
 
183
  if creative_restoration:
184
  if "lcm" not in pipe.unet.active_adapters():
185
  pipe.unet.set_adapter('lcm')
186
  else:
187
- if "previewer" not in pipe.unet.active_adapters():
188
- pipe.unet.set_adapter('previewer')
189
 
190
  if isinstance(guidance_end, int):
191
  guidance_end = guidance_end / steps
192
- with torch.no_grad(): lq = [transform(lq)]
 
 
193
  generator = torch.Generator(device=device).manual_seed(seed)
 
 
 
 
 
 
 
 
194
 
195
  out = pipe(
196
  prompt=[prompt]*len(lq),
197
  image=lq,
198
- ip_adapter_image=[lq],
199
  num_inference_steps=steps,
200
  generator=generator,
201
- controlnet_conditioning_scale=1.0,
202
- # negative_original_size=(256,256),
203
- # negative_target_size=(1024,1024),
204
- negative_prompt=[""]*len(lq),
205
  guidance_scale=cfg_scale,
206
  control_guidance_end=guidance_end,
207
- # control_guidance_start=0.5,
208
  previewer_scheduler=lcm_scheduler,
209
  return_dict=False,
210
  save_preview_row=True,
211
- # reference_latent = reference_latents,
212
- # output_type='pt'
213
  )
214
  for i, preview_img in enumerate(out[1]):
215
  preview_img.append(f"preview_{i}")
@@ -228,7 +150,7 @@ css="""
228
  }
229
  """
230
 
231
- with gr.Blocks(css=css) as demo:
232
  gr.Markdown(
233
  """
234
  # InstantIR: Blind Image Restoration with Instant Generative Reference.
@@ -242,41 +164,36 @@ with gr.Blocks(css=css) as demo:
242
  """)
243
  with gr.Row():
244
  lq_img = gr.Image(label="Low-quality image", type="pil")
245
- with gr.Column(elem_id="col-container"):
246
  with gr.Row():
247
- steps = gr.Number(label="Steps", value=20, step=1)
248
  cfg_scale = gr.Number(label="CFG Scale", value=7.0, step=0.1)
 
 
 
249
  seed = gr.Number(label="Seed", value=42, step=1)
250
  # guidance_start = gr.Slider(label="Guidance Start", value=1.0, minimum=0.0, maximum=1.0, step=0.05)
251
- guidance_end = gr.Slider(label="Start Free Rendering", value=20, minimum=0, maximum=20, step=1)
252
- prompt = gr.Textbox(
253
- label="Restoration prompts (Optional)", show_label=False,
254
- placeholder="Restoration prompts (Optional)", value='',
255
- # container=False,
256
- )
257
  mode = gr.Checkbox(label="Creative Restoration", value=False)
258
- # with gr.Accordion("Advanced Settings", open=False):
259
  with gr.Row():
260
  with gr.Row():
261
  restore_btn = gr.Button("InstantIR magic!")
262
  clear_btn = gr.ClearButton()
263
- index = gr.Slider(label="Restoration Previews", value=19, minimum=0, maximum=19, step=1)
264
  with gr.Row():
265
  output = gr.Image(label="InstantIR restored", type="pil")
266
  preview = gr.Image(label="Preview", type="pil")
267
- # gr.Examples(
268
- # examples = examples,
269
- # inputs = [prompt]
270
- # )
271
- # gr.on(
272
- # triggers=[restore_btn.click, prompt.submit],
273
- # fn = infer,
274
- # inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
275
- # outputs = [result, seed]
276
- # )
277
  pipe_out = gr.Gallery(visible=False)
278
  clear_btn.add([lq_img, output, preview])
279
- restore_btn.click(instantir_restore, inputs=[lq_img, prompt, steps, cfg_scale, guidance_end, mode, seed], outputs=[output, pipe_out], api_name="InstantIR")
 
 
 
 
 
 
280
  steps.change(dynamic_guidance_slider, inputs=steps, outputs=guidance_end)
281
  output.change(dynamic_preview_slider, inputs=steps, outputs=index)
282
  index.release(unpack_pipe_out, inputs=[pipe_out, index], outputs=preview)
@@ -312,4 +229,4 @@ with gr.Blocks(css=css) as demo:
312
  ```
313
  """)
314
 
315
- demo.queue().launch(debug=True)
 
1
  import os
2
  import torch
 
3
  import numpy as np
4
+ import app as gr
5
  from PIL import Image
 
6
 
7
+ from diffusers import DDPMScheduler
 
 
 
8
  from schedulers.lcm_single_step_scheduler import LCMSingleStepScheduler
 
 
 
 
 
9
 
10
+ from module.ip_adapter.utils import load_adapter_to_pipe
11
+ from pipelines.sdxl_instantir import InstantIRPipeline
 
 
12
 
13
  from huggingface_hub import hf_hub_download
14
 
15
+ if not os.path.exists("models/adapter.pt"):
16
+ hf_hub_download(repo_id="InstantX/InstantIR", filename="models/adapter.pt", local_dir=".")
17
+ if not os.path.exists("models/aggregator.pt"):
18
+ hf_hub_download(repo_id="InstantX/InstantIR", filename="models/aggregator.pt", local_dir=".")
19
+ if not os.path.exists("models/previewer_lora_weights.bin"):
20
+ hf_hub_download(repo_id="InstantX/InstantIR", filename="models/previewer_lora_weights.bin", local_dir=".")
 
 
 
 
 
 
21
 
22
  device = "cuda" if torch.cuda.is_available() else "cpu"
23
  sdxl_repo_id = "stabilityai/stable-diffusion-xl-base-1.0"
 
24
  dinov2_repo_id = "facebook/dinov2-large"
25
 
26
  if torch.cuda.is_available():
 
28
  else:
29
  torch_dtype = torch.float32
30
 
31
+ # Load pretrained models.
 
 
 
32
  print("Loading SDXL...")
33
+ pipe = InstantIRPipeline.from_pretrained(
34
  sdxl_repo_id,
35
+ torch_dtype=torch_dtype,
36
  )
 
 
 
 
37
 
38
+ # Image prompt projector.
39
  print("Loading LQ-Adapter...")
40
+ load_adapter_to_pipe(
41
+ pipe,
42
+ "models/adapter.pt",
43
+ dinov2_repo_id,
 
 
 
 
 
 
 
 
 
 
 
44
  )
 
 
 
 
 
 
 
 
 
 
45
 
46
+ # Prepare previewer
47
+ lora_alpha = pipe.prepare_previewers("models")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  print(f"use lora alpha {lora_alpha}")
49
+ lora_alpha = pipe.prepare_previewers("latent-consistency/lcm-lora-sdxl", use_lcm=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  print(f"use lora alpha {lora_alpha}")
51
+ pipe.to(device=device, dtype=torch_dtype)
52
+ pipe.scheduler = DDPMScheduler.from_pretrained(sdxl_repo_id, subfolder="scheduler")
53
+ lcm_scheduler = LCMSingleStepScheduler.from_config(pipe.scheduler.config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
55
  pipe.scheduler = DDPMScheduler.from_pretrained(
56
  sdxl_repo_id,
57
  subfolder="scheduler"
 
60
  # Load weights.
61
  print("Loading checkpoint...")
62
  aggregator_state_dict = torch.load(
63
+ "models/aggregator.pt",
64
  map_location="cpu"
65
  )
66
+ pipe.aggregator.load_state_dict(aggregator_state_dict, strict=True)
67
+ pipe.aggregator.to(device=device, dtype=torch_dtype)
 
 
68
 
69
  MAX_SEED = np.iinfo(np.int32).max
70
  MAX_IMAGE_SIZE = 1024
71
 
72
+ PROMPT = "Photorealistic, highly detailed, hyper detailed photo - realistic maximum detail, 32k, \
73
+ ultra HD, extreme meticulous detailing, skin pore detailing, \
74
+ hyper sharpness, perfect without deformations, \
75
+ taken using a Canon EOS R camera, Cinematic, High Contrast, Color Grading. "
76
+
77
+ NEG_PROMPT = "blurry, out of focus, unclear, depth of field, over-smooth, \
78
+ sketch, oil painting, cartoon, CG Style, 3D render, unreal engine, \
79
+ dirty, messy, worst quality, low quality, frames, painting, illustration, drawing, art, \
80
+ watermark, signature, jpeg artifacts, deformed, lowres"
81
+
82
  def unpack_pipe_out(preview_row, index):
83
  return preview_row[index][0]
84
 
 
93
  return preview_row[-1][0]
94
 
95
  # @spaces.GPU #[uncomment to use ZeroGPU]
96
+ @torch.no_grad()
97
+ def instantir_restore(
98
+ lq, prompt="", steps=30, cfg_scale=7.0, guidance_end=1.0,
99
+ creative_restoration=False, seed=3407, height=1024, width=1024, preview_start=0.0):
100
  if creative_restoration:
101
  if "lcm" not in pipe.unet.active_adapters():
102
  pipe.unet.set_adapter('lcm')
103
  else:
104
+ if "default" not in pipe.unet.active_adapters():
105
+ pipe.unet.set_adapter('default')
106
 
107
  if isinstance(guidance_end, int):
108
  guidance_end = guidance_end / steps
109
+ if isinstance(preview_start, int):
110
+ preview_start = preview_start / steps
111
+ lq = [resize_img(lq.convert("RGB"), size=(width, height))]
112
  generator = torch.Generator(device=device).manual_seed(seed)
113
+ timesteps = [
114
+ i * (1000//steps) + pipe.scheduler.config.steps_offset for i in range(0, steps)
115
+ ]
116
+ timesteps = timesteps[::-1]
117
+ start_timestep = timesteps[0]
118
+
119
+ prompt = PROMPT if len(prompt)==0 else prompt
120
+ neg_prompt = NEG_PROMPT
121
 
122
  out = pipe(
123
  prompt=[prompt]*len(lq),
124
  image=lq,
 
125
  num_inference_steps=steps,
126
  generator=generator,
127
+ timesteps=timesteps,
128
+ negative_prompt=[neg_prompt]*len(lq),
 
 
129
  guidance_scale=cfg_scale,
130
  control_guidance_end=guidance_end,
131
+ preview_start=preview_start,
132
  previewer_scheduler=lcm_scheduler,
133
  return_dict=False,
134
  save_preview_row=True,
 
 
135
  )
136
  for i, preview_img in enumerate(out[1]):
137
  preview_img.append(f"preview_{i}")
 
150
  }
151
  """
152
 
153
+ with gr.Blocks() as demo:
154
  gr.Markdown(
155
  """
156
  # InstantIR: Blind Image Restoration with Instant Generative Reference.
 
164
  """)
165
  with gr.Row():
166
  lq_img = gr.Image(label="Low-quality image", type="pil")
167
+ with gr.Column():
168
  with gr.Row():
169
+ steps = gr.Number(label="Steps", value=30, step=1)
170
  cfg_scale = gr.Number(label="CFG Scale", value=7.0, step=0.1)
171
+ with gr.Row():
172
+ height = gr.Number(label="Height", value=1024, step=1)
173
+ weight = gr.Number(label="Weight", value=1024, step=1)
174
  seed = gr.Number(label="Seed", value=42, step=1)
175
  # guidance_start = gr.Slider(label="Guidance Start", value=1.0, minimum=0.0, maximum=1.0, step=0.05)
176
+ guidance_end = gr.Slider(label="Start Free Rendering", value=30, minimum=0, maximum=30, step=1)
177
+ preview_start = gr.Slider(label="Preview Start", value=0, minimum=0, maximum=30, step=1)
178
+ prompt = gr.Textbox(label="Restoration prompts (Optional)", placeholder="")
 
 
 
179
  mode = gr.Checkbox(label="Creative Restoration", value=False)
 
180
  with gr.Row():
181
  with gr.Row():
182
  restore_btn = gr.Button("InstantIR magic!")
183
  clear_btn = gr.ClearButton()
184
+ index = gr.Slider(label="Restoration Previews", value=29, minimum=0, maximum=29, step=1)
185
  with gr.Row():
186
  output = gr.Image(label="InstantIR restored", type="pil")
187
  preview = gr.Image(label="Preview", type="pil")
 
 
 
 
 
 
 
 
 
 
188
  pipe_out = gr.Gallery(visible=False)
189
  clear_btn.add([lq_img, output, preview])
190
+ restore_btn.click(
191
+ instantir_restore, inputs=[
192
+ lq_img, prompt, steps, cfg_scale, guidance_end,
193
+ mode, seed, height, weight, preview_start,
194
+ ],
195
+ outputs=[output, pipe_out], api_name="InstantIR"
196
+ )
197
  steps.change(dynamic_guidance_slider, inputs=steps, outputs=guidance_end)
198
  output.change(dynamic_preview_slider, inputs=steps, outputs=index)
199
  index.release(unpack_pipe_out, inputs=[pipe_out, index], outputs=preview)
 
229
  ```
230
  """)
231
 
232
+ demo.queue().launch()
diffusers/__init__.py DELETED
@@ -1,797 +0,0 @@
1
- __version__ = "0.28.0.dev0"
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
- "ControlNetXSAdapter",
84
- "I2VGenXLUNet",
85
- "Kandinsky3UNet",
86
- "ModelMixin",
87
- "MotionAdapter",
88
- "MultiAdapter",
89
- "PriorTransformer",
90
- "StableCascadeUNet",
91
- "T2IAdapter",
92
- "T5FilmDecoder",
93
- "Transformer2DModel",
94
- "UNet1DModel",
95
- "UNet2DConditionModel",
96
- "UNet2DModel",
97
- "UNet3DConditionModel",
98
- "UNetControlNetXSModel",
99
- "UNetMotionModel",
100
- "UNetSpatioTemporalConditionModel",
101
- "UVit2DModel",
102
- "VQModel",
103
- ]
104
- )
105
-
106
- _import_structure["optimization"] = [
107
- "get_constant_schedule",
108
- "get_constant_schedule_with_warmup",
109
- "get_cosine_schedule_with_warmup",
110
- "get_cosine_with_hard_restarts_schedule_with_warmup",
111
- "get_linear_schedule_with_warmup",
112
- "get_polynomial_decay_schedule_with_warmup",
113
- "get_scheduler",
114
- ]
115
- _import_structure["pipelines"].extend(
116
- [
117
- "AudioPipelineOutput",
118
- "AutoPipelineForImage2Image",
119
- "AutoPipelineForInpainting",
120
- "AutoPipelineForText2Image",
121
- "ConsistencyModelPipeline",
122
- "DanceDiffusionPipeline",
123
- "DDIMPipeline",
124
- "DDPMPipeline",
125
- "DiffusionPipeline",
126
- "DiTPipeline",
127
- "ImagePipelineOutput",
128
- "KarrasVePipeline",
129
- "LDMPipeline",
130
- "LDMSuperResolutionPipeline",
131
- "PNDMPipeline",
132
- "RePaintPipeline",
133
- "ScoreSdeVePipeline",
134
- "StableDiffusionMixin",
135
- ]
136
- )
137
- _import_structure["schedulers"].extend(
138
- [
139
- "AmusedScheduler",
140
- "CMStochasticIterativeScheduler",
141
- "DDIMInverseScheduler",
142
- "DDIMParallelScheduler",
143
- "DDIMScheduler",
144
- "DDPMParallelScheduler",
145
- "DDPMScheduler",
146
- "DDPMWuerstchenScheduler",
147
- "DEISMultistepScheduler",
148
- "DPMSolverMultistepInverseScheduler",
149
- "DPMSolverMultistepScheduler",
150
- "DPMSolverSinglestepScheduler",
151
- "EDMDPMSolverMultistepScheduler",
152
- "EDMEulerScheduler",
153
- "EulerAncestralDiscreteScheduler",
154
- "EulerDiscreteScheduler",
155
- "HeunDiscreteScheduler",
156
- "IPNDMScheduler",
157
- "KarrasVeScheduler",
158
- "KDPM2AncestralDiscreteScheduler",
159
- "KDPM2DiscreteScheduler",
160
- "LCMScheduler",
161
- "PNDMScheduler",
162
- "RePaintScheduler",
163
- "SASolverScheduler",
164
- "SchedulerMixin",
165
- "ScoreSdeVeScheduler",
166
- "TCDScheduler",
167
- "UnCLIPScheduler",
168
- "UniPCMultistepScheduler",
169
- "VQDiffusionScheduler",
170
- ]
171
- )
172
- _import_structure["training_utils"] = ["EMAModel"]
173
-
174
- try:
175
- if not (is_torch_available() and is_scipy_available()):
176
- raise OptionalDependencyNotAvailable()
177
- except OptionalDependencyNotAvailable:
178
- from .utils import dummy_torch_and_scipy_objects # noqa F403
179
-
180
- _import_structure["utils.dummy_torch_and_scipy_objects"] = [
181
- name for name in dir(dummy_torch_and_scipy_objects) if not name.startswith("_")
182
- ]
183
-
184
- else:
185
- _import_structure["schedulers"].extend(["LMSDiscreteScheduler"])
186
-
187
- try:
188
- if not (is_torch_available() and is_torchsde_available()):
189
- raise OptionalDependencyNotAvailable()
190
- except OptionalDependencyNotAvailable:
191
- from .utils import dummy_torch_and_torchsde_objects # noqa F403
192
-
193
- _import_structure["utils.dummy_torch_and_torchsde_objects"] = [
194
- name for name in dir(dummy_torch_and_torchsde_objects) if not name.startswith("_")
195
- ]
196
-
197
- else:
198
- _import_structure["schedulers"].extend(["DPMSolverSDEScheduler"])
199
-
200
- try:
201
- if not (is_torch_available() and is_transformers_available()):
202
- raise OptionalDependencyNotAvailable()
203
- except OptionalDependencyNotAvailable:
204
- from .utils import dummy_torch_and_transformers_objects # noqa F403
205
-
206
- _import_structure["utils.dummy_torch_and_transformers_objects"] = [
207
- name for name in dir(dummy_torch_and_transformers_objects) if not name.startswith("_")
208
- ]
209
-
210
- else:
211
- _import_structure["pipelines"].extend(
212
- [
213
- "AltDiffusionImg2ImgPipeline",
214
- "AltDiffusionPipeline",
215
- "AmusedImg2ImgPipeline",
216
- "AmusedInpaintPipeline",
217
- "AmusedPipeline",
218
- "AnimateDiffPipeline",
219
- "AnimateDiffVideoToVideoPipeline",
220
- "AudioLDM2Pipeline",
221
- "AudioLDM2ProjectionModel",
222
- "AudioLDM2UNet2DConditionModel",
223
- "AudioLDMPipeline",
224
- "BlipDiffusionControlNetPipeline",
225
- "BlipDiffusionPipeline",
226
- "CLIPImageProjection",
227
- "CycleDiffusionPipeline",
228
- "I2VGenXLPipeline",
229
- "IFImg2ImgPipeline",
230
- "IFImg2ImgSuperResolutionPipeline",
231
- "IFInpaintingPipeline",
232
- "IFInpaintingSuperResolutionPipeline",
233
- "IFPipeline",
234
- "IFSuperResolutionPipeline",
235
- "ImageTextPipelineOutput",
236
- "Kandinsky3Img2ImgPipeline",
237
- "Kandinsky3Pipeline",
238
- "KandinskyCombinedPipeline",
239
- "KandinskyImg2ImgCombinedPipeline",
240
- "KandinskyImg2ImgPipeline",
241
- "KandinskyInpaintCombinedPipeline",
242
- "KandinskyInpaintPipeline",
243
- "KandinskyPipeline",
244
- "KandinskyPriorPipeline",
245
- "KandinskyV22CombinedPipeline",
246
- "KandinskyV22ControlnetImg2ImgPipeline",
247
- "KandinskyV22ControlnetPipeline",
248
- "KandinskyV22Img2ImgCombinedPipeline",
249
- "KandinskyV22Img2ImgPipeline",
250
- "KandinskyV22InpaintCombinedPipeline",
251
- "KandinskyV22InpaintPipeline",
252
- "KandinskyV22Pipeline",
253
- "KandinskyV22PriorEmb2EmbPipeline",
254
- "KandinskyV22PriorPipeline",
255
- "LatentConsistencyModelImg2ImgPipeline",
256
- "LatentConsistencyModelPipeline",
257
- "LDMTextToImagePipeline",
258
- "LEditsPPPipelineStableDiffusion",
259
- "LEditsPPPipelineStableDiffusionXL",
260
- "MusicLDMPipeline",
261
- "PaintByExamplePipeline",
262
- "PIAPipeline",
263
- "PixArtAlphaPipeline",
264
- "PixArtSigmaPipeline",
265
- "SemanticStableDiffusionPipeline",
266
- "ShapEImg2ImgPipeline",
267
- "ShapEPipeline",
268
- "StableCascadeCombinedPipeline",
269
- "StableCascadeDecoderPipeline",
270
- "StableCascadePriorPipeline",
271
- "StableDiffusionAdapterPipeline",
272
- "StableDiffusionAttendAndExcitePipeline",
273
- "StableDiffusionControlNetImg2ImgPipeline",
274
- "StableDiffusionControlNetInpaintPipeline",
275
- "StableDiffusionControlNetPipeline",
276
- "StableDiffusionControlNetXSPipeline",
277
- "StableDiffusionDepth2ImgPipeline",
278
- "StableDiffusionDiffEditPipeline",
279
- "StableDiffusionGLIGENPipeline",
280
- "StableDiffusionGLIGENTextImagePipeline",
281
- "StableDiffusionImageVariationPipeline",
282
- "StableDiffusionImg2ImgPipeline",
283
- "StableDiffusionInpaintPipeline",
284
- "StableDiffusionInpaintPipelineLegacy",
285
- "StableDiffusionInstructPix2PixPipeline",
286
- "StableDiffusionLatentUpscalePipeline",
287
- "StableDiffusionLDM3DPipeline",
288
- "StableDiffusionModelEditingPipeline",
289
- "StableDiffusionPanoramaPipeline",
290
- "StableDiffusionParadigmsPipeline",
291
- "StableDiffusionPipeline",
292
- "StableDiffusionPipelineSafe",
293
- "StableDiffusionPix2PixZeroPipeline",
294
- "StableDiffusionSAGPipeline",
295
- "StableDiffusionUpscalePipeline",
296
- "StableDiffusionXLAdapterPipeline",
297
- "StableDiffusionXLControlNetImg2ImgPipeline",
298
- "StableDiffusionXLControlNetInpaintPipeline",
299
- "StableDiffusionXLControlNetPipeline",
300
- "StableDiffusionXLControlNetXSPipeline",
301
- "StableDiffusionXLImg2ImgPipeline",
302
- "StableDiffusionXLInpaintPipeline",
303
- "StableDiffusionXLInstructPix2PixPipeline",
304
- "StableDiffusionXLPipeline",
305
- "StableUnCLIPImg2ImgPipeline",
306
- "StableUnCLIPPipeline",
307
- "StableVideoDiffusionPipeline",
308
- "TextToVideoSDPipeline",
309
- "TextToVideoZeroPipeline",
310
- "TextToVideoZeroSDXLPipeline",
311
- "UnCLIPImageVariationPipeline",
312
- "UnCLIPPipeline",
313
- "UniDiffuserModel",
314
- "UniDiffuserPipeline",
315
- "UniDiffuserTextDecoder",
316
- "VersatileDiffusionDualGuidedPipeline",
317
- "VersatileDiffusionImageVariationPipeline",
318
- "VersatileDiffusionPipeline",
319
- "VersatileDiffusionTextToImagePipeline",
320
- "VideoToVideoSDPipeline",
321
- "VQDiffusionPipeline",
322
- "WuerstchenCombinedPipeline",
323
- "WuerstchenDecoderPipeline",
324
- "WuerstchenPriorPipeline",
325
- ]
326
- )
327
-
328
- try:
329
- if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
330
- raise OptionalDependencyNotAvailable()
331
- except OptionalDependencyNotAvailable:
332
- from .utils import dummy_torch_and_transformers_and_k_diffusion_objects # noqa F403
333
-
334
- _import_structure["utils.dummy_torch_and_transformers_and_k_diffusion_objects"] = [
335
- name for name in dir(dummy_torch_and_transformers_and_k_diffusion_objects) if not name.startswith("_")
336
- ]
337
-
338
- else:
339
- _import_structure["pipelines"].extend(["StableDiffusionKDiffusionPipeline", "StableDiffusionXLKDiffusionPipeline"])
340
-
341
- try:
342
- if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
343
- raise OptionalDependencyNotAvailable()
344
- except OptionalDependencyNotAvailable:
345
- from .utils import dummy_torch_and_transformers_and_onnx_objects # noqa F403
346
-
347
- _import_structure["utils.dummy_torch_and_transformers_and_onnx_objects"] = [
348
- name for name in dir(dummy_torch_and_transformers_and_onnx_objects) if not name.startswith("_")
349
- ]
350
-
351
- else:
352
- _import_structure["pipelines"].extend(
353
- [
354
- "OnnxStableDiffusionImg2ImgPipeline",
355
- "OnnxStableDiffusionInpaintPipeline",
356
- "OnnxStableDiffusionInpaintPipelineLegacy",
357
- "OnnxStableDiffusionPipeline",
358
- "OnnxStableDiffusionUpscalePipeline",
359
- "StableDiffusionOnnxPipeline",
360
- ]
361
- )
362
-
363
- try:
364
- if not (is_torch_available() and is_librosa_available()):
365
- raise OptionalDependencyNotAvailable()
366
- except OptionalDependencyNotAvailable:
367
- from .utils import dummy_torch_and_librosa_objects # noqa F403
368
-
369
- _import_structure["utils.dummy_torch_and_librosa_objects"] = [
370
- name for name in dir(dummy_torch_and_librosa_objects) if not name.startswith("_")
371
- ]
372
-
373
- else:
374
- _import_structure["pipelines"].extend(["AudioDiffusionPipeline", "Mel"])
375
-
376
- try:
377
- if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
378
- raise OptionalDependencyNotAvailable()
379
- except OptionalDependencyNotAvailable:
380
- from .utils import dummy_transformers_and_torch_and_note_seq_objects # noqa F403
381
-
382
- _import_structure["utils.dummy_transformers_and_torch_and_note_seq_objects"] = [
383
- name for name in dir(dummy_transformers_and_torch_and_note_seq_objects) if not name.startswith("_")
384
- ]
385
-
386
-
387
- else:
388
- _import_structure["pipelines"].extend(["SpectrogramDiffusionPipeline"])
389
-
390
- try:
391
- if not is_flax_available():
392
- raise OptionalDependencyNotAvailable()
393
- except OptionalDependencyNotAvailable:
394
- from .utils import dummy_flax_objects # noqa F403
395
-
396
- _import_structure["utils.dummy_flax_objects"] = [
397
- name for name in dir(dummy_flax_objects) if not name.startswith("_")
398
- ]
399
-
400
-
401
- else:
402
- _import_structure["models.controlnet_flax"] = ["FlaxControlNetModel"]
403
- _import_structure["models.modeling_flax_utils"] = ["FlaxModelMixin"]
404
- _import_structure["models.unets.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
405
- _import_structure["models.vae_flax"] = ["FlaxAutoencoderKL"]
406
- _import_structure["pipelines"].extend(["FlaxDiffusionPipeline"])
407
- _import_structure["schedulers"].extend(
408
- [
409
- "FlaxDDIMScheduler",
410
- "FlaxDDPMScheduler",
411
- "FlaxDPMSolverMultistepScheduler",
412
- "FlaxEulerDiscreteScheduler",
413
- "FlaxKarrasVeScheduler",
414
- "FlaxLMSDiscreteScheduler",
415
- "FlaxPNDMScheduler",
416
- "FlaxSchedulerMixin",
417
- "FlaxScoreSdeVeScheduler",
418
- ]
419
- )
420
-
421
-
422
- try:
423
- if not (is_flax_available() and is_transformers_available()):
424
- raise OptionalDependencyNotAvailable()
425
- except OptionalDependencyNotAvailable:
426
- from .utils import dummy_flax_and_transformers_objects # noqa F403
427
-
428
- _import_structure["utils.dummy_flax_and_transformers_objects"] = [
429
- name for name in dir(dummy_flax_and_transformers_objects) if not name.startswith("_")
430
- ]
431
-
432
-
433
- else:
434
- _import_structure["pipelines"].extend(
435
- [
436
- "FlaxStableDiffusionControlNetPipeline",
437
- "FlaxStableDiffusionImg2ImgPipeline",
438
- "FlaxStableDiffusionInpaintPipeline",
439
- "FlaxStableDiffusionPipeline",
440
- "FlaxStableDiffusionXLPipeline",
441
- ]
442
- )
443
-
444
- try:
445
- if not (is_note_seq_available()):
446
- raise OptionalDependencyNotAvailable()
447
- except OptionalDependencyNotAvailable:
448
- from .utils import dummy_note_seq_objects # noqa F403
449
-
450
- _import_structure["utils.dummy_note_seq_objects"] = [
451
- name for name in dir(dummy_note_seq_objects) if not name.startswith("_")
452
- ]
453
-
454
-
455
- else:
456
- _import_structure["pipelines"].extend(["MidiProcessor"])
457
-
458
- if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
459
- from .configuration_utils import ConfigMixin
460
-
461
- try:
462
- if not is_onnx_available():
463
- raise OptionalDependencyNotAvailable()
464
- except OptionalDependencyNotAvailable:
465
- from .utils.dummy_onnx_objects import * # noqa F403
466
- else:
467
- from .pipelines import OnnxRuntimeModel
468
-
469
- try:
470
- if not is_torch_available():
471
- raise OptionalDependencyNotAvailable()
472
- except OptionalDependencyNotAvailable:
473
- from .utils.dummy_pt_objects import * # noqa F403
474
- else:
475
- from .models import (
476
- AsymmetricAutoencoderKL,
477
- AutoencoderKL,
478
- AutoencoderKLTemporalDecoder,
479
- AutoencoderTiny,
480
- ConsistencyDecoderVAE,
481
- ControlNetModel,
482
- ControlNetXSAdapter,
483
- I2VGenXLUNet,
484
- Kandinsky3UNet,
485
- ModelMixin,
486
- MotionAdapter,
487
- MultiAdapter,
488
- PriorTransformer,
489
- T2IAdapter,
490
- T5FilmDecoder,
491
- Transformer2DModel,
492
- UNet1DModel,
493
- UNet2DConditionModel,
494
- UNet2DModel,
495
- UNet3DConditionModel,
496
- UNetControlNetXSModel,
497
- UNetMotionModel,
498
- UNetSpatioTemporalConditionModel,
499
- UVit2DModel,
500
- VQModel,
501
- )
502
- from .optimization import (
503
- get_constant_schedule,
504
- get_constant_schedule_with_warmup,
505
- get_cosine_schedule_with_warmup,
506
- get_cosine_with_hard_restarts_schedule_with_warmup,
507
- get_linear_schedule_with_warmup,
508
- get_polynomial_decay_schedule_with_warmup,
509
- get_scheduler,
510
- )
511
- from .pipelines import (
512
- AudioPipelineOutput,
513
- AutoPipelineForImage2Image,
514
- AutoPipelineForInpainting,
515
- AutoPipelineForText2Image,
516
- BlipDiffusionControlNetPipeline,
517
- BlipDiffusionPipeline,
518
- CLIPImageProjection,
519
- ConsistencyModelPipeline,
520
- DanceDiffusionPipeline,
521
- DDIMPipeline,
522
- DDPMPipeline,
523
- DiffusionPipeline,
524
- DiTPipeline,
525
- ImagePipelineOutput,
526
- KarrasVePipeline,
527
- LDMPipeline,
528
- LDMSuperResolutionPipeline,
529
- PNDMPipeline,
530
- RePaintPipeline,
531
- ScoreSdeVePipeline,
532
- StableDiffusionMixin,
533
- )
534
- from .schedulers import (
535
- AmusedScheduler,
536
- CMStochasticIterativeScheduler,
537
- DDIMInverseScheduler,
538
- DDIMParallelScheduler,
539
- DDIMScheduler,
540
- DDPMParallelScheduler,
541
- DDPMScheduler,
542
- DDPMWuerstchenScheduler,
543
- DEISMultistepScheduler,
544
- DPMSolverMultistepInverseScheduler,
545
- DPMSolverMultistepScheduler,
546
- DPMSolverSinglestepScheduler,
547
- EDMDPMSolverMultistepScheduler,
548
- EDMEulerScheduler,
549
- EulerAncestralDiscreteScheduler,
550
- EulerDiscreteScheduler,
551
- HeunDiscreteScheduler,
552
- IPNDMScheduler,
553
- KarrasVeScheduler,
554
- KDPM2AncestralDiscreteScheduler,
555
- KDPM2DiscreteScheduler,
556
- LCMScheduler,
557
- PNDMScheduler,
558
- RePaintScheduler,
559
- SASolverScheduler,
560
- SchedulerMixin,
561
- ScoreSdeVeScheduler,
562
- TCDScheduler,
563
- UnCLIPScheduler,
564
- UniPCMultistepScheduler,
565
- VQDiffusionScheduler,
566
- )
567
- from .training_utils import EMAModel
568
-
569
- try:
570
- if not (is_torch_available() and is_scipy_available()):
571
- raise OptionalDependencyNotAvailable()
572
- except OptionalDependencyNotAvailable:
573
- from .utils.dummy_torch_and_scipy_objects import * # noqa F403
574
- else:
575
- from .schedulers import LMSDiscreteScheduler
576
-
577
- try:
578
- if not (is_torch_available() and is_torchsde_available()):
579
- raise OptionalDependencyNotAvailable()
580
- except OptionalDependencyNotAvailable:
581
- from .utils.dummy_torch_and_torchsde_objects import * # noqa F403
582
- else:
583
- from .schedulers import DPMSolverSDEScheduler
584
-
585
- try:
586
- if not (is_torch_available() and is_transformers_available()):
587
- raise OptionalDependencyNotAvailable()
588
- except OptionalDependencyNotAvailable:
589
- from .utils.dummy_torch_and_transformers_objects import * # noqa F403
590
- else:
591
- from .pipelines import (
592
- AltDiffusionImg2ImgPipeline,
593
- AltDiffusionPipeline,
594
- AmusedImg2ImgPipeline,
595
- AmusedInpaintPipeline,
596
- AmusedPipeline,
597
- AnimateDiffPipeline,
598
- AnimateDiffVideoToVideoPipeline,
599
- AudioLDM2Pipeline,
600
- AudioLDM2ProjectionModel,
601
- AudioLDM2UNet2DConditionModel,
602
- AudioLDMPipeline,
603
- CLIPImageProjection,
604
- CycleDiffusionPipeline,
605
- I2VGenXLPipeline,
606
- IFImg2ImgPipeline,
607
- IFImg2ImgSuperResolutionPipeline,
608
- IFInpaintingPipeline,
609
- IFInpaintingSuperResolutionPipeline,
610
- IFPipeline,
611
- IFSuperResolutionPipeline,
612
- ImageTextPipelineOutput,
613
- Kandinsky3Img2ImgPipeline,
614
- Kandinsky3Pipeline,
615
- KandinskyCombinedPipeline,
616
- KandinskyImg2ImgCombinedPipeline,
617
- KandinskyImg2ImgPipeline,
618
- KandinskyInpaintCombinedPipeline,
619
- KandinskyInpaintPipeline,
620
- KandinskyPipeline,
621
- KandinskyPriorPipeline,
622
- KandinskyV22CombinedPipeline,
623
- KandinskyV22ControlnetImg2ImgPipeline,
624
- KandinskyV22ControlnetPipeline,
625
- KandinskyV22Img2ImgCombinedPipeline,
626
- KandinskyV22Img2ImgPipeline,
627
- KandinskyV22InpaintCombinedPipeline,
628
- KandinskyV22InpaintPipeline,
629
- KandinskyV22Pipeline,
630
- KandinskyV22PriorEmb2EmbPipeline,
631
- KandinskyV22PriorPipeline,
632
- LatentConsistencyModelImg2ImgPipeline,
633
- LatentConsistencyModelPipeline,
634
- LDMTextToImagePipeline,
635
- LEditsPPPipelineStableDiffusion,
636
- LEditsPPPipelineStableDiffusionXL,
637
- MusicLDMPipeline,
638
- PaintByExamplePipeline,
639
- PIAPipeline,
640
- PixArtAlphaPipeline,
641
- PixArtSigmaPipeline,
642
- SemanticStableDiffusionPipeline,
643
- ShapEImg2ImgPipeline,
644
- ShapEPipeline,
645
- StableCascadeCombinedPipeline,
646
- StableCascadeDecoderPipeline,
647
- StableCascadePriorPipeline,
648
- StableDiffusionAdapterPipeline,
649
- StableDiffusionAttendAndExcitePipeline,
650
- StableDiffusionControlNetImg2ImgPipeline,
651
- StableDiffusionControlNetInpaintPipeline,
652
- StableDiffusionControlNetPipeline,
653
- StableDiffusionControlNetXSPipeline,
654
- StableDiffusionDepth2ImgPipeline,
655
- StableDiffusionDiffEditPipeline,
656
- StableDiffusionGLIGENPipeline,
657
- StableDiffusionGLIGENTextImagePipeline,
658
- StableDiffusionImageVariationPipeline,
659
- StableDiffusionImg2ImgPipeline,
660
- StableDiffusionInpaintPipeline,
661
- StableDiffusionInpaintPipelineLegacy,
662
- StableDiffusionInstructPix2PixPipeline,
663
- StableDiffusionLatentUpscalePipeline,
664
- StableDiffusionLDM3DPipeline,
665
- StableDiffusionModelEditingPipeline,
666
- StableDiffusionPanoramaPipeline,
667
- StableDiffusionParadigmsPipeline,
668
- StableDiffusionPipeline,
669
- StableDiffusionPipelineSafe,
670
- StableDiffusionPix2PixZeroPipeline,
671
- StableDiffusionSAGPipeline,
672
- StableDiffusionUpscalePipeline,
673
- StableDiffusionXLAdapterPipeline,
674
- StableDiffusionXLControlNetImg2ImgPipeline,
675
- StableDiffusionXLControlNetInpaintPipeline,
676
- StableDiffusionXLControlNetPipeline,
677
- StableDiffusionXLControlNetXSPipeline,
678
- StableDiffusionXLImg2ImgPipeline,
679
- StableDiffusionXLInpaintPipeline,
680
- StableDiffusionXLInstructPix2PixPipeline,
681
- StableDiffusionXLPipeline,
682
- StableUnCLIPImg2ImgPipeline,
683
- StableUnCLIPPipeline,
684
- StableVideoDiffusionPipeline,
685
- TextToVideoSDPipeline,
686
- TextToVideoZeroPipeline,
687
- TextToVideoZeroSDXLPipeline,
688
- UnCLIPImageVariationPipeline,
689
- UnCLIPPipeline,
690
- UniDiffuserModel,
691
- UniDiffuserPipeline,
692
- UniDiffuserTextDecoder,
693
- VersatileDiffusionDualGuidedPipeline,
694
- VersatileDiffusionImageVariationPipeline,
695
- VersatileDiffusionPipeline,
696
- VersatileDiffusionTextToImagePipeline,
697
- VideoToVideoSDPipeline,
698
- VQDiffusionPipeline,
699
- WuerstchenCombinedPipeline,
700
- WuerstchenDecoderPipeline,
701
- WuerstchenPriorPipeline,
702
- )
703
-
704
- try:
705
- if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
706
- raise OptionalDependencyNotAvailable()
707
- except OptionalDependencyNotAvailable:
708
- from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
709
- else:
710
- from .pipelines import StableDiffusionKDiffusionPipeline, StableDiffusionXLKDiffusionPipeline
711
-
712
- try:
713
- if not (is_torch_available() and is_transformers_available() and is_onnx_available()):
714
- raise OptionalDependencyNotAvailable()
715
- except OptionalDependencyNotAvailable:
716
- from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403
717
- else:
718
- from .pipelines import (
719
- OnnxStableDiffusionImg2ImgPipeline,
720
- OnnxStableDiffusionInpaintPipeline,
721
- OnnxStableDiffusionInpaintPipelineLegacy,
722
- OnnxStableDiffusionPipeline,
723
- OnnxStableDiffusionUpscalePipeline,
724
- StableDiffusionOnnxPipeline,
725
- )
726
-
727
- try:
728
- if not (is_torch_available() and is_librosa_available()):
729
- raise OptionalDependencyNotAvailable()
730
- except OptionalDependencyNotAvailable:
731
- from .utils.dummy_torch_and_librosa_objects import * # noqa F403
732
- else:
733
- from .pipelines import AudioDiffusionPipeline, Mel
734
-
735
- try:
736
- if not (is_transformers_available() and is_torch_available() and is_note_seq_available()):
737
- raise OptionalDependencyNotAvailable()
738
- except OptionalDependencyNotAvailable:
739
- from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403
740
- else:
741
- from .pipelines import SpectrogramDiffusionPipeline
742
-
743
- try:
744
- if not is_flax_available():
745
- raise OptionalDependencyNotAvailable()
746
- except OptionalDependencyNotAvailable:
747
- from .utils.dummy_flax_objects import * # noqa F403
748
- else:
749
- from .models.controlnet_flax import FlaxControlNetModel
750
- from .models.modeling_flax_utils import FlaxModelMixin
751
- from .models.unets.unet_2d_condition_flax import FlaxUNet2DConditionModel
752
- from .models.vae_flax import FlaxAutoencoderKL
753
- from .pipelines import FlaxDiffusionPipeline
754
- from .schedulers import (
755
- FlaxDDIMScheduler,
756
- FlaxDDPMScheduler,
757
- FlaxDPMSolverMultistepScheduler,
758
- FlaxEulerDiscreteScheduler,
759
- FlaxKarrasVeScheduler,
760
- FlaxLMSDiscreteScheduler,
761
- FlaxPNDMScheduler,
762
- FlaxSchedulerMixin,
763
- FlaxScoreSdeVeScheduler,
764
- )
765
-
766
- try:
767
- if not (is_flax_available() and is_transformers_available()):
768
- raise OptionalDependencyNotAvailable()
769
- except OptionalDependencyNotAvailable:
770
- from .utils.dummy_flax_and_transformers_objects import * # noqa F403
771
- else:
772
- from .pipelines import (
773
- FlaxStableDiffusionControlNetPipeline,
774
- FlaxStableDiffusionImg2ImgPipeline,
775
- FlaxStableDiffusionInpaintPipeline,
776
- FlaxStableDiffusionPipeline,
777
- FlaxStableDiffusionXLPipeline,
778
- )
779
-
780
- try:
781
- if not (is_note_seq_available()):
782
- raise OptionalDependencyNotAvailable()
783
- except OptionalDependencyNotAvailable:
784
- from .utils.dummy_note_seq_objects import * # noqa F403
785
- else:
786
- from .pipelines import MidiProcessor
787
-
788
- else:
789
- import sys
790
-
791
- sys.modules[__name__] = _LazyModule(
792
- __name__,
793
- globals()["__file__"],
794
- _import_structure,
795
- module_spec=__spec__,
796
- extra_objects={"__version__": __version__},
797
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/commands/__init__.py DELETED
@@ -1,27 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from 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 DELETED
@@ -1,43 +0,0 @@
1
- #!/usr/bin/env python
2
- # Copyright 2024 The HuggingFace Team. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
-
16
- from argparse import ArgumentParser
17
-
18
- from .env import EnvironmentCommand
19
- from .fp16_safetensors import FP16SafetensorsCommand
20
-
21
-
22
- def main():
23
- parser = ArgumentParser("Diffusers CLI tool", usage="diffusers-cli <command> [<args>]")
24
- commands_parser = parser.add_subparsers(help="diffusers-cli command helpers")
25
-
26
- # Register commands
27
- EnvironmentCommand.register_subcommand(commands_parser)
28
- FP16SafetensorsCommand.register_subcommand(commands_parser)
29
-
30
- # Let's go
31
- args = parser.parse_args()
32
-
33
- if not hasattr(args, "func"):
34
- parser.print_help()
35
- exit(1)
36
-
37
- # Run
38
- service = args.func(args)
39
- service.run()
40
-
41
-
42
- if __name__ == "__main__":
43
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/commands/env.py DELETED
@@ -1,84 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import platform
16
- from argparse import ArgumentParser
17
-
18
- import huggingface_hub
19
-
20
- from .. import __version__ as version
21
- from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
22
- from . import BaseDiffusersCLICommand
23
-
24
-
25
- def info_command_factory(_):
26
- return EnvironmentCommand()
27
-
28
-
29
- class EnvironmentCommand(BaseDiffusersCLICommand):
30
- @staticmethod
31
- def register_subcommand(parser: ArgumentParser):
32
- download_parser = parser.add_parser("env")
33
- download_parser.set_defaults(func=info_command_factory)
34
-
35
- def run(self):
36
- hub_version = huggingface_hub.__version__
37
-
38
- pt_version = "not installed"
39
- pt_cuda_available = "NA"
40
- if is_torch_available():
41
- import torch
42
-
43
- pt_version = torch.__version__
44
- pt_cuda_available = torch.cuda.is_available()
45
-
46
- transformers_version = "not installed"
47
- if is_transformers_available():
48
- import transformers
49
-
50
- transformers_version = transformers.__version__
51
-
52
- accelerate_version = "not installed"
53
- if is_accelerate_available():
54
- import accelerate
55
-
56
- accelerate_version = accelerate.__version__
57
-
58
- xformers_version = "not installed"
59
- if is_xformers_available():
60
- import xformers
61
-
62
- xformers_version = xformers.__version__
63
-
64
- info = {
65
- "`diffusers` version": version,
66
- "Platform": platform.platform(),
67
- "Python version": platform.python_version(),
68
- "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})",
69
- "Huggingface_hub version": hub_version,
70
- "Transformers version": transformers_version,
71
- "Accelerate version": accelerate_version,
72
- "xFormers version": xformers_version,
73
- "Using GPU in script?": "<fill in>",
74
- "Using distributed or parallel set-up in script?": "<fill in>",
75
- }
76
-
77
- print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n")
78
- print(self.format_dict(info))
79
-
80
- return info
81
-
82
- @staticmethod
83
- def format_dict(d):
84
- return "\n".join([f"- {prop}: {val}" for prop, val in d.items()]) + "\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/commands/fp16_safetensors.py DELETED
@@ -1,132 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- """
16
- Usage example:
17
- diffusers-cli fp16_safetensors --ckpt_id=openai/shap-e --fp16 --use_safetensors
18
- """
19
-
20
- import glob
21
- import json
22
- import warnings
23
- from argparse import ArgumentParser, Namespace
24
- from importlib import import_module
25
-
26
- import huggingface_hub
27
- import torch
28
- from huggingface_hub import hf_hub_download
29
- from packaging import version
30
-
31
- from ..utils import logging
32
- from . import BaseDiffusersCLICommand
33
-
34
-
35
- def conversion_command_factory(args: Namespace):
36
- if args.use_auth_token:
37
- warnings.warn(
38
- "The `--use_auth_token` flag is deprecated and will be removed in a future version. Authentication is now"
39
- " handled automatically if user is logged in."
40
- )
41
- return FP16SafetensorsCommand(args.ckpt_id, args.fp16, args.use_safetensors)
42
-
43
-
44
- class FP16SafetensorsCommand(BaseDiffusersCLICommand):
45
- @staticmethod
46
- def register_subcommand(parser: ArgumentParser):
47
- conversion_parser = parser.add_parser("fp16_safetensors")
48
- conversion_parser.add_argument(
49
- "--ckpt_id",
50
- type=str,
51
- help="Repo id of the checkpoints on which to run the conversion. Example: 'openai/shap-e'.",
52
- )
53
- conversion_parser.add_argument(
54
- "--fp16", action="store_true", help="If serializing the variables in FP16 precision."
55
- )
56
- conversion_parser.add_argument(
57
- "--use_safetensors", action="store_true", help="If serializing in the safetensors format."
58
- )
59
- conversion_parser.add_argument(
60
- "--use_auth_token",
61
- action="store_true",
62
- help="When working with checkpoints having private visibility. When used `huggingface-cli login` needs to be run beforehand.",
63
- )
64
- conversion_parser.set_defaults(func=conversion_command_factory)
65
-
66
- def __init__(self, ckpt_id: str, fp16: bool, use_safetensors: bool):
67
- self.logger = logging.get_logger("diffusers-cli/fp16_safetensors")
68
- self.ckpt_id = ckpt_id
69
- self.local_ckpt_dir = f"/tmp/{ckpt_id}"
70
- self.fp16 = fp16
71
-
72
- self.use_safetensors = use_safetensors
73
-
74
- if not self.use_safetensors and not self.fp16:
75
- raise NotImplementedError(
76
- "When `use_safetensors` and `fp16` both are False, then this command is of no use."
77
- )
78
-
79
- def run(self):
80
- if version.parse(huggingface_hub.__version__) < version.parse("0.9.0"):
81
- raise ImportError(
82
- "The huggingface_hub version must be >= 0.9.0 to use this command. Please update your huggingface_hub"
83
- " installation."
84
- )
85
- else:
86
- from huggingface_hub import create_commit
87
- from huggingface_hub._commit_api import CommitOperationAdd
88
-
89
- model_index = hf_hub_download(repo_id=self.ckpt_id, filename="model_index.json")
90
- with open(model_index, "r") as f:
91
- pipeline_class_name = json.load(f)["_class_name"]
92
- pipeline_class = getattr(import_module("diffusers"), pipeline_class_name)
93
- self.logger.info(f"Pipeline class imported: {pipeline_class_name}.")
94
-
95
- # Load the appropriate pipeline. We could have use `DiffusionPipeline`
96
- # here, but just to avoid any rough edge cases.
97
- pipeline = pipeline_class.from_pretrained(
98
- self.ckpt_id, torch_dtype=torch.float16 if self.fp16 else torch.float32
99
- )
100
- pipeline.save_pretrained(
101
- self.local_ckpt_dir,
102
- safe_serialization=True if self.use_safetensors else False,
103
- variant="fp16" if self.fp16 else None,
104
- )
105
- self.logger.info(f"Pipeline locally saved to {self.local_ckpt_dir}.")
106
-
107
- # Fetch all the paths.
108
- if self.fp16:
109
- modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.fp16.*")
110
- elif self.use_safetensors:
111
- modified_paths = glob.glob(f"{self.local_ckpt_dir}/*/*.safetensors")
112
-
113
- # Prepare for the PR.
114
- commit_message = f"Serialize variables with FP16: {self.fp16} and safetensors: {self.use_safetensors}."
115
- operations = []
116
- for path in modified_paths:
117
- operations.append(CommitOperationAdd(path_in_repo="/".join(path.split("/")[4:]), path_or_fileobj=path))
118
-
119
- # Open the PR.
120
- commit_description = (
121
- "Variables converted by the [`diffusers`' `fp16_safetensors`"
122
- " CLI](https://github.com/huggingface/diffusers/blob/main/src/diffusers/commands/fp16_safetensors.py)."
123
- )
124
- hub_pr_url = create_commit(
125
- repo_id=self.ckpt_id,
126
- operations=operations,
127
- commit_message=commit_message,
128
- commit_description=commit_description,
129
- repo_type="model",
130
- create_pr=True,
131
- ).pr_url
132
- self.logger.info(f"PR created here: {hub_pr_url}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/configuration_utils.py DELETED
@@ -1,704 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The HuggingFace Inc. team.
3
- # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
- #
5
- # Licensed under the Apache License, Version 2.0 (the "License");
6
- # you may not use this file except in compliance with the License.
7
- # You may obtain a copy of the License at
8
- #
9
- # http://www.apache.org/licenses/LICENSE-2.0
10
- #
11
- # Unless required by applicable law or agreed to in writing, software
12
- # distributed under the License is distributed on an "AS IS" BASIS,
13
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
- # See the License for the specific language governing permissions and
15
- # limitations under the License.
16
- """ConfigMixin base class and utilities."""
17
-
18
- import dataclasses
19
- import functools
20
- import importlib
21
- import inspect
22
- import json
23
- import os
24
- import re
25
- from collections import OrderedDict
26
- from pathlib import PosixPath
27
- from typing import Any, Dict, Tuple, Union
28
-
29
- import numpy as np
30
- from huggingface_hub import create_repo, hf_hub_download
31
- from huggingface_hub.utils import (
32
- EntryNotFoundError,
33
- RepositoryNotFoundError,
34
- RevisionNotFoundError,
35
- validate_hf_hub_args,
36
- )
37
- from requests import HTTPError
38
-
39
- from . import __version__
40
- from .utils import (
41
- HUGGINGFACE_CO_RESOLVE_ENDPOINT,
42
- DummyObject,
43
- deprecate,
44
- extract_commit_hash,
45
- http_user_agent,
46
- logging,
47
- )
48
-
49
-
50
- logger = logging.get_logger(__name__)
51
-
52
- _re_configuration_file = re.compile(r"config\.(.*)\.json")
53
-
54
-
55
- class FrozenDict(OrderedDict):
56
- def __init__(self, *args, **kwargs):
57
- super().__init__(*args, **kwargs)
58
-
59
- for key, value in self.items():
60
- setattr(self, key, value)
61
-
62
- self.__frozen = True
63
-
64
- def __delitem__(self, *args, **kwargs):
65
- raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
66
-
67
- def setdefault(self, *args, **kwargs):
68
- raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
69
-
70
- def pop(self, *args, **kwargs):
71
- raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
72
-
73
- def update(self, *args, **kwargs):
74
- raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
75
-
76
- def __setattr__(self, name, value):
77
- if hasattr(self, "__frozen") and self.__frozen:
78
- raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
79
- super().__setattr__(name, value)
80
-
81
- def __setitem__(self, name, value):
82
- if hasattr(self, "__frozen") and self.__frozen:
83
- raise Exception(f"You cannot use ``__setattr__`` on a {self.__class__.__name__} instance.")
84
- super().__setitem__(name, value)
85
-
86
-
87
- class ConfigMixin:
88
- r"""
89
- Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
90
- provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
91
- saving classes that inherit from [`ConfigMixin`].
92
-
93
- Class attributes:
94
- - **config_name** (`str`) -- A filename under which the config should stored when calling
95
- [`~ConfigMixin.save_config`] (should be overridden by parent class).
96
- - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
97
- overridden by subclass).
98
- - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
99
- - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
100
- should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
101
- subclass).
102
- """
103
-
104
- config_name = None
105
- ignore_for_config = []
106
- has_compatibles = False
107
-
108
- _deprecated_kwargs = []
109
-
110
- def register_to_config(self, **kwargs):
111
- if self.config_name is None:
112
- raise NotImplementedError(f"Make sure that {self.__class__} has defined a class name `config_name`")
113
- # Special case for `kwargs` used in deprecation warning added to schedulers
114
- # TODO: remove this when we remove the deprecation warning, and the `kwargs` argument,
115
- # or solve in a more general way.
116
- kwargs.pop("kwargs", None)
117
-
118
- if not hasattr(self, "_internal_dict"):
119
- internal_dict = kwargs
120
- else:
121
- previous_dict = dict(self._internal_dict)
122
- internal_dict = {**self._internal_dict, **kwargs}
123
- logger.debug(f"Updating config from {previous_dict} to {internal_dict}")
124
-
125
- self._internal_dict = FrozenDict(internal_dict)
126
-
127
- def __getattr__(self, name: str) -> Any:
128
- """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
129
- config attributes directly. See https://github.com/huggingface/diffusers/pull/3129
130
-
131
- This function is mostly copied from PyTorch's __getattr__ overwrite:
132
- https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
133
- """
134
-
135
- is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
136
- is_attribute = name in self.__dict__
137
-
138
- if is_in_config and not is_attribute:
139
- deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'scheduler.config.{name}'."
140
- deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False)
141
- return self._internal_dict[name]
142
-
143
- raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
144
-
145
- def save_config(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
146
- """
147
- Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
148
- [`~ConfigMixin.from_config`] class method.
149
-
150
- Args:
151
- save_directory (`str` or `os.PathLike`):
152
- Directory where the configuration JSON file is saved (will be created if it does not exist).
153
- push_to_hub (`bool`, *optional*, defaults to `False`):
154
- Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
155
- repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
156
- namespace).
157
- kwargs (`Dict[str, Any]`, *optional*):
158
- Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
159
- """
160
- if os.path.isfile(save_directory):
161
- raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file")
162
-
163
- os.makedirs(save_directory, exist_ok=True)
164
-
165
- # If we save using the predefined names, we can load using `from_config`
166
- output_config_file = os.path.join(save_directory, self.config_name)
167
-
168
- self.to_json_file(output_config_file)
169
- logger.info(f"Configuration saved in {output_config_file}")
170
-
171
- if push_to_hub:
172
- commit_message = kwargs.pop("commit_message", None)
173
- private = kwargs.pop("private", False)
174
- create_pr = kwargs.pop("create_pr", False)
175
- token = kwargs.pop("token", None)
176
- repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
177
- repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
178
-
179
- self._upload_folder(
180
- save_directory,
181
- repo_id,
182
- token=token,
183
- commit_message=commit_message,
184
- create_pr=create_pr,
185
- )
186
-
187
- @classmethod
188
- def from_config(cls, config: Union[FrozenDict, Dict[str, Any]] = None, return_unused_kwargs=False, **kwargs):
189
- r"""
190
- Instantiate a Python class from a config dictionary.
191
-
192
- Parameters:
193
- config (`Dict[str, Any]`):
194
- A config dictionary from which the Python class is instantiated. Make sure to only load configuration
195
- files of compatible classes.
196
- return_unused_kwargs (`bool`, *optional*, defaults to `False`):
197
- Whether kwargs that are not consumed by the Python class should be returned or not.
198
- kwargs (remaining dictionary of keyword arguments, *optional*):
199
- Can be used to update the configuration object (after it is loaded) and initiate the Python class.
200
- `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
201
- overwrite the same named arguments in `config`.
202
-
203
- Returns:
204
- [`ModelMixin`] or [`SchedulerMixin`]:
205
- A model or scheduler object instantiated from a config dictionary.
206
-
207
- Examples:
208
-
209
- ```python
210
- >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler
211
-
212
- >>> # Download scheduler from huggingface.co and cache.
213
- >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")
214
-
215
- >>> # Instantiate DDIM scheduler class with same config as DDPM
216
- >>> scheduler = DDIMScheduler.from_config(scheduler.config)
217
-
218
- >>> # Instantiate PNDM scheduler class with same config as DDPM
219
- >>> scheduler = PNDMScheduler.from_config(scheduler.config)
220
- ```
221
- """
222
- # <===== TO BE REMOVED WITH DEPRECATION
223
- # TODO(Patrick) - make sure to remove the following lines when config=="model_path" is deprecated
224
- if "pretrained_model_name_or_path" in kwargs:
225
- config = kwargs.pop("pretrained_model_name_or_path")
226
-
227
- if config is None:
228
- raise ValueError("Please make sure to provide a config as the first positional argument.")
229
- # ======>
230
-
231
- if not isinstance(config, dict):
232
- deprecation_message = "It is deprecated to pass a pretrained model name or path to `from_config`."
233
- if "Scheduler" in cls.__name__:
234
- deprecation_message += (
235
- f"If you were trying to load a scheduler, please use {cls}.from_pretrained(...) instead."
236
- " Otherwise, please make sure to pass a configuration dictionary instead. This functionality will"
237
- " be removed in v1.0.0."
238
- )
239
- elif "Model" in cls.__name__:
240
- deprecation_message += (
241
- f"If you were trying to load a model, please use {cls}.load_config(...) followed by"
242
- f" {cls}.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary"
243
- " instead. This functionality will be removed in v1.0.0."
244
- )
245
- deprecate("config-passed-as-path", "1.0.0", deprecation_message, standard_warn=False)
246
- config, kwargs = cls.load_config(pretrained_model_name_or_path=config, return_unused_kwargs=True, **kwargs)
247
-
248
- init_dict, unused_kwargs, hidden_dict = cls.extract_init_dict(config, **kwargs)
249
-
250
- # Allow dtype to be specified on initialization
251
- if "dtype" in unused_kwargs:
252
- init_dict["dtype"] = unused_kwargs.pop("dtype")
253
-
254
- # add possible deprecated kwargs
255
- for deprecated_kwarg in cls._deprecated_kwargs:
256
- if deprecated_kwarg in unused_kwargs:
257
- init_dict[deprecated_kwarg] = unused_kwargs.pop(deprecated_kwarg)
258
-
259
- # Return model and optionally state and/or unused_kwargs
260
- model = cls(**init_dict)
261
-
262
- # make sure to also save config parameters that might be used for compatible classes
263
- # update _class_name
264
- if "_class_name" in hidden_dict:
265
- hidden_dict["_class_name"] = cls.__name__
266
-
267
- model.register_to_config(**hidden_dict)
268
-
269
- # add hidden kwargs of compatible classes to unused_kwargs
270
- unused_kwargs = {**unused_kwargs, **hidden_dict}
271
-
272
- if return_unused_kwargs:
273
- return (model, unused_kwargs)
274
- else:
275
- return model
276
-
277
- @classmethod
278
- def get_config_dict(cls, *args, **kwargs):
279
- deprecation_message = (
280
- f" The function get_config_dict is deprecated. Please use {cls}.load_config instead. This function will be"
281
- " removed in version v1.0.0"
282
- )
283
- deprecate("get_config_dict", "1.0.0", deprecation_message, standard_warn=False)
284
- return cls.load_config(*args, **kwargs)
285
-
286
- @classmethod
287
- @validate_hf_hub_args
288
- def load_config(
289
- cls,
290
- pretrained_model_name_or_path: Union[str, os.PathLike],
291
- return_unused_kwargs=False,
292
- return_commit_hash=False,
293
- **kwargs,
294
- ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
295
- r"""
296
- Load a model or scheduler configuration.
297
-
298
- Parameters:
299
- pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
300
- Can be either:
301
-
302
- - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
303
- the Hub.
304
- - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
305
- [`~ConfigMixin.save_config`].
306
-
307
- cache_dir (`Union[str, os.PathLike]`, *optional*):
308
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
309
- is not used.
310
- force_download (`bool`, *optional*, defaults to `False`):
311
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
312
- cached versions if they exist.
313
- resume_download:
314
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
315
- of Diffusers.
316
- proxies (`Dict[str, str]`, *optional*):
317
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
318
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
319
- output_loading_info(`bool`, *optional*, defaults to `False`):
320
- Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
321
- local_files_only (`bool`, *optional*, defaults to `False`):
322
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
323
- won't be downloaded from the Hub.
324
- token (`str` or *bool*, *optional*):
325
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
326
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
327
- revision (`str`, *optional*, defaults to `"main"`):
328
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
329
- allowed by Git.
330
- subfolder (`str`, *optional*, defaults to `""`):
331
- The subfolder location of a model file within a larger model repository on the Hub or locally.
332
- return_unused_kwargs (`bool`, *optional*, defaults to `False):
333
- Whether unused keyword arguments of the config are returned.
334
- return_commit_hash (`bool`, *optional*, defaults to `False):
335
- Whether the `commit_hash` of the loaded configuration are returned.
336
-
337
- Returns:
338
- `dict`:
339
- A dictionary of all the parameters stored in a JSON configuration file.
340
-
341
- """
342
- cache_dir = kwargs.pop("cache_dir", None)
343
- force_download = kwargs.pop("force_download", False)
344
- resume_download = kwargs.pop("resume_download", None)
345
- proxies = kwargs.pop("proxies", None)
346
- token = kwargs.pop("token", None)
347
- local_files_only = kwargs.pop("local_files_only", False)
348
- revision = kwargs.pop("revision", None)
349
- _ = kwargs.pop("mirror", None)
350
- subfolder = kwargs.pop("subfolder", None)
351
- user_agent = kwargs.pop("user_agent", {})
352
-
353
- user_agent = {**user_agent, "file_type": "config"}
354
- user_agent = http_user_agent(user_agent)
355
-
356
- pretrained_model_name_or_path = str(pretrained_model_name_or_path)
357
-
358
- if cls.config_name is None:
359
- raise ValueError(
360
- "`self.config_name` is not defined. Note that one should not load a config from "
361
- "`ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`"
362
- )
363
-
364
- if os.path.isfile(pretrained_model_name_or_path):
365
- config_file = pretrained_model_name_or_path
366
- elif os.path.isdir(pretrained_model_name_or_path):
367
- if os.path.isfile(os.path.join(pretrained_model_name_or_path, cls.config_name)):
368
- # Load from a PyTorch checkpoint
369
- config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
370
- elif subfolder is not None and os.path.isfile(
371
- os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
372
- ):
373
- config_file = os.path.join(pretrained_model_name_or_path, subfolder, cls.config_name)
374
- else:
375
- raise EnvironmentError(
376
- f"Error no file named {cls.config_name} found in directory {pretrained_model_name_or_path}."
377
- )
378
- else:
379
- try:
380
- # Load from URL or cache if already cached
381
- config_file = hf_hub_download(
382
- pretrained_model_name_or_path,
383
- filename=cls.config_name,
384
- cache_dir=cache_dir,
385
- force_download=force_download,
386
- proxies=proxies,
387
- resume_download=resume_download,
388
- local_files_only=local_files_only,
389
- token=token,
390
- user_agent=user_agent,
391
- subfolder=subfolder,
392
- revision=revision,
393
- )
394
- except RepositoryNotFoundError:
395
- raise EnvironmentError(
396
- f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier"
397
- " listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a"
398
- " token having permission to this repo with `token` or log in with `huggingface-cli login`."
399
- )
400
- except RevisionNotFoundError:
401
- raise EnvironmentError(
402
- f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for"
403
- " this model name. Check the model page at"
404
- f" 'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
405
- )
406
- except EntryNotFoundError:
407
- raise EnvironmentError(
408
- f"{pretrained_model_name_or_path} does not appear to have a file named {cls.config_name}."
409
- )
410
- except HTTPError as err:
411
- raise EnvironmentError(
412
- "There was a specific connection error when trying to load"
413
- f" {pretrained_model_name_or_path}:\n{err}"
414
- )
415
- except ValueError:
416
- raise EnvironmentError(
417
- f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
418
- f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
419
- f" directory containing a {cls.config_name} file.\nCheckout your internet connection or see how to"
420
- " run the library in offline mode at"
421
- " 'https://huggingface.co/docs/diffusers/installation#offline-mode'."
422
- )
423
- except EnvironmentError:
424
- raise EnvironmentError(
425
- f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
426
- "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
427
- f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
428
- f"containing a {cls.config_name} file"
429
- )
430
-
431
- try:
432
- # Load config dict
433
- config_dict = cls._dict_from_json_file(config_file)
434
-
435
- commit_hash = extract_commit_hash(config_file)
436
- except (json.JSONDecodeError, UnicodeDecodeError):
437
- raise EnvironmentError(f"It looks like the config file at '{config_file}' is not a valid JSON file.")
438
-
439
- if not (return_unused_kwargs or return_commit_hash):
440
- return config_dict
441
-
442
- outputs = (config_dict,)
443
-
444
- if return_unused_kwargs:
445
- outputs += (kwargs,)
446
-
447
- if return_commit_hash:
448
- outputs += (commit_hash,)
449
-
450
- return outputs
451
-
452
- @staticmethod
453
- def _get_init_keys(input_class):
454
- return set(dict(inspect.signature(input_class.__init__).parameters).keys())
455
-
456
- @classmethod
457
- def extract_init_dict(cls, config_dict, **kwargs):
458
- # Skip keys that were not present in the original config, so default __init__ values were used
459
- used_defaults = config_dict.get("_use_default_values", [])
460
- config_dict = {k: v for k, v in config_dict.items() if k not in used_defaults and k != "_use_default_values"}
461
-
462
- # 0. Copy origin config dict
463
- original_dict = dict(config_dict.items())
464
-
465
- # 1. Retrieve expected config attributes from __init__ signature
466
- expected_keys = cls._get_init_keys(cls)
467
- expected_keys.remove("self")
468
- # remove general kwargs if present in dict
469
- if "kwargs" in expected_keys:
470
- expected_keys.remove("kwargs")
471
- # remove flax internal keys
472
- if hasattr(cls, "_flax_internal_args"):
473
- for arg in cls._flax_internal_args:
474
- expected_keys.remove(arg)
475
-
476
- # 2. Remove attributes that cannot be expected from expected config attributes
477
- # remove keys to be ignored
478
- if len(cls.ignore_for_config) > 0:
479
- expected_keys = expected_keys - set(cls.ignore_for_config)
480
-
481
- # load diffusers library to import compatible and original scheduler
482
- diffusers_library = importlib.import_module(__name__.split(".")[0])
483
-
484
- if cls.has_compatibles:
485
- compatible_classes = [c for c in cls._get_compatibles() if not isinstance(c, DummyObject)]
486
- else:
487
- compatible_classes = []
488
-
489
- expected_keys_comp_cls = set()
490
- for c in compatible_classes:
491
- expected_keys_c = cls._get_init_keys(c)
492
- expected_keys_comp_cls = expected_keys_comp_cls.union(expected_keys_c)
493
- expected_keys_comp_cls = expected_keys_comp_cls - cls._get_init_keys(cls)
494
- config_dict = {k: v for k, v in config_dict.items() if k not in expected_keys_comp_cls}
495
-
496
- # remove attributes from orig class that cannot be expected
497
- orig_cls_name = config_dict.pop("_class_name", cls.__name__)
498
- if (
499
- isinstance(orig_cls_name, str)
500
- and orig_cls_name != cls.__name__
501
- and hasattr(diffusers_library, orig_cls_name)
502
- ):
503
- orig_cls = getattr(diffusers_library, orig_cls_name)
504
- unexpected_keys_from_orig = cls._get_init_keys(orig_cls) - expected_keys
505
- config_dict = {k: v for k, v in config_dict.items() if k not in unexpected_keys_from_orig}
506
- elif not isinstance(orig_cls_name, str) and not isinstance(orig_cls_name, (list, tuple)):
507
- raise ValueError(
508
- "Make sure that the `_class_name` is of type string or list of string (for custom pipelines)."
509
- )
510
-
511
- # remove private attributes
512
- config_dict = {k: v for k, v in config_dict.items() if not k.startswith("_")}
513
-
514
- # 3. Create keyword arguments that will be passed to __init__ from expected keyword arguments
515
- init_dict = {}
516
- for key in expected_keys:
517
- # if config param is passed to kwarg and is present in config dict
518
- # it should overwrite existing config dict key
519
- if key in kwargs and key in config_dict:
520
- config_dict[key] = kwargs.pop(key)
521
-
522
- if key in kwargs:
523
- # overwrite key
524
- init_dict[key] = kwargs.pop(key)
525
- elif key in config_dict:
526
- # use value from config dict
527
- init_dict[key] = config_dict.pop(key)
528
-
529
- # 4. Give nice warning if unexpected values have been passed
530
- if len(config_dict) > 0:
531
- logger.warning(
532
- f"The config attributes {config_dict} were passed to {cls.__name__}, "
533
- "but are not expected and will be ignored. Please verify your "
534
- f"{cls.config_name} configuration file."
535
- )
536
-
537
- # 5. Give nice info if config attributes are initialized to default because they have not been passed
538
- passed_keys = set(init_dict.keys())
539
- if len(expected_keys - passed_keys) > 0:
540
- logger.info(
541
- f"{expected_keys - passed_keys} was not found in config. Values will be initialized to default values."
542
- )
543
-
544
- # 6. Define unused keyword arguments
545
- unused_kwargs = {**config_dict, **kwargs}
546
-
547
- # 7. Define "hidden" config parameters that were saved for compatible classes
548
- hidden_config_dict = {k: v for k, v in original_dict.items() if k not in init_dict}
549
-
550
- return init_dict, unused_kwargs, hidden_config_dict
551
-
552
- @classmethod
553
- def _dict_from_json_file(cls, json_file: Union[str, os.PathLike]):
554
- with open(json_file, "r", encoding="utf-8") as reader:
555
- text = reader.read()
556
- return json.loads(text)
557
-
558
- def __repr__(self):
559
- return f"{self.__class__.__name__} {self.to_json_string()}"
560
-
561
- @property
562
- def config(self) -> Dict[str, Any]:
563
- """
564
- Returns the config of the class as a frozen dictionary
565
-
566
- Returns:
567
- `Dict[str, Any]`: Config of the class.
568
- """
569
- return self._internal_dict
570
-
571
- def to_json_string(self) -> str:
572
- """
573
- Serializes the configuration instance to a JSON string.
574
-
575
- Returns:
576
- `str`:
577
- String containing all the attributes that make up the configuration instance in JSON format.
578
- """
579
- config_dict = self._internal_dict if hasattr(self, "_internal_dict") else {}
580
- config_dict["_class_name"] = self.__class__.__name__
581
- config_dict["_diffusers_version"] = __version__
582
-
583
- def to_json_saveable(value):
584
- if isinstance(value, np.ndarray):
585
- value = value.tolist()
586
- elif isinstance(value, PosixPath):
587
- value = str(value)
588
- return value
589
-
590
- config_dict = {k: to_json_saveable(v) for k, v in config_dict.items()}
591
- # Don't save "_ignore_files" or "_use_default_values"
592
- config_dict.pop("_ignore_files", None)
593
- config_dict.pop("_use_default_values", None)
594
-
595
- return json.dumps(config_dict, indent=2, sort_keys=True) + "\n"
596
-
597
- def to_json_file(self, json_file_path: Union[str, os.PathLike]):
598
- """
599
- Save the configuration instance's parameters to a JSON file.
600
-
601
- Args:
602
- json_file_path (`str` or `os.PathLike`):
603
- Path to the JSON file to save a configuration instance's parameters.
604
- """
605
- with open(json_file_path, "w", encoding="utf-8") as writer:
606
- writer.write(self.to_json_string())
607
-
608
-
609
- def register_to_config(init):
610
- r"""
611
- Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
612
- automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
613
- shouldn't be registered in the config, use the `ignore_for_config` class variable
614
-
615
- Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
616
- """
617
-
618
- @functools.wraps(init)
619
- def inner_init(self, *args, **kwargs):
620
- # Ignore private kwargs in the init.
621
- init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")}
622
- config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")}
623
- if not isinstance(self, ConfigMixin):
624
- raise RuntimeError(
625
- f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
626
- "not inherit from `ConfigMixin`."
627
- )
628
-
629
- ignore = getattr(self, "ignore_for_config", [])
630
- # Get positional arguments aligned with kwargs
631
- new_kwargs = {}
632
- signature = inspect.signature(init)
633
- parameters = {
634
- name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore
635
- }
636
- for arg, name in zip(args, parameters.keys()):
637
- new_kwargs[name] = arg
638
-
639
- # Then add all kwargs
640
- new_kwargs.update(
641
- {
642
- k: init_kwargs.get(k, default)
643
- for k, default in parameters.items()
644
- if k not in ignore and k not in new_kwargs
645
- }
646
- )
647
-
648
- # Take note of the parameters that were not present in the loaded config
649
- if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
650
- new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
651
-
652
- new_kwargs = {**config_init_kwargs, **new_kwargs}
653
- getattr(self, "register_to_config")(**new_kwargs)
654
- init(self, *args, **init_kwargs)
655
-
656
- return inner_init
657
-
658
-
659
- def flax_register_to_config(cls):
660
- original_init = cls.__init__
661
-
662
- @functools.wraps(original_init)
663
- def init(self, *args, **kwargs):
664
- if not isinstance(self, ConfigMixin):
665
- raise RuntimeError(
666
- f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does "
667
- "not inherit from `ConfigMixin`."
668
- )
669
-
670
- # Ignore private kwargs in the init. Retrieve all passed attributes
671
- init_kwargs = dict(kwargs.items())
672
-
673
- # Retrieve default values
674
- fields = dataclasses.fields(self)
675
- default_kwargs = {}
676
- for field in fields:
677
- # ignore flax specific attributes
678
- if field.name in self._flax_internal_args:
679
- continue
680
- if type(field.default) == dataclasses._MISSING_TYPE:
681
- default_kwargs[field.name] = None
682
- else:
683
- default_kwargs[field.name] = getattr(self, field.name)
684
-
685
- # Make sure init_kwargs override default kwargs
686
- new_kwargs = {**default_kwargs, **init_kwargs}
687
- # dtype should be part of `init_kwargs`, but not `new_kwargs`
688
- if "dtype" in new_kwargs:
689
- new_kwargs.pop("dtype")
690
-
691
- # Get positional arguments aligned with kwargs
692
- for i, arg in enumerate(args):
693
- name = fields[i].name
694
- new_kwargs[name] = arg
695
-
696
- # Take note of the parameters that were not present in the loaded config
697
- if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0:
698
- new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs))
699
-
700
- getattr(self, "register_to_config")(**new_kwargs)
701
- original_init(self, *args, **kwargs)
702
-
703
- cls.__init__ = init
704
- return cls
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/dependency_versions_check.py DELETED
@@ -1,34 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from .dependency_versions_table import deps
16
- from .utils.versions import require_version, require_version_core
17
-
18
-
19
- # define which module versions we always want to check at run time
20
- # (usually the ones defined in `install_requires` in setup.py)
21
- #
22
- # order specific notes:
23
- # - tqdm must be checked before tokenizers
24
-
25
- pkgs_to_check_at_runtime = "python requests filelock numpy".split()
26
- for pkg in pkgs_to_check_at_runtime:
27
- if pkg in deps:
28
- require_version_core(deps[pkg])
29
- else:
30
- raise ValueError(f"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py")
31
-
32
-
33
- def dep_version_check(pkg, hint=None):
34
- require_version(deps[pkg], hint)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/dependency_versions_table.py DELETED
@@ -1,46 +0,0 @@
1
- # THIS FILE HAS BEEN AUTOGENERATED. To update:
2
- # 1. modify the `_deps` dict in setup.py
3
- # 2. run `make deps_table_update`
4
- deps = {
5
- "Pillow": "Pillow",
6
- "accelerate": "accelerate>=0.29.3",
7
- "compel": "compel==0.1.8",
8
- "datasets": "datasets",
9
- "filelock": "filelock",
10
- "flax": "flax>=0.4.1",
11
- "hf-doc-builder": "hf-doc-builder>=0.3.0",
12
- "huggingface-hub": "huggingface-hub>=0.20.2",
13
- "requests-mock": "requests-mock==1.10.0",
14
- "importlib_metadata": "importlib_metadata",
15
- "invisible-watermark": "invisible-watermark>=0.2.0",
16
- "isort": "isort>=5.5.4",
17
- "jax": "jax>=0.4.1",
18
- "jaxlib": "jaxlib>=0.4.1",
19
- "Jinja2": "Jinja2",
20
- "k-diffusion": "k-diffusion>=0.0.12",
21
- "torchsde": "torchsde",
22
- "note_seq": "note_seq",
23
- "librosa": "librosa",
24
- "numpy": "numpy",
25
- "parameterized": "parameterized",
26
- "peft": "peft>=0.6.0",
27
- "protobuf": "protobuf>=3.20.3,<4",
28
- "pytest": "pytest",
29
- "pytest-timeout": "pytest-timeout",
30
- "pytest-xdist": "pytest-xdist",
31
- "python": "python>=3.8.0",
32
- "ruff": "ruff==0.1.5",
33
- "safetensors": "safetensors>=0.3.1",
34
- "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92",
35
- "GitPython": "GitPython<3.1.19",
36
- "scipy": "scipy",
37
- "onnx": "onnx",
38
- "regex": "regex!=2019.12.17",
39
- "requests": "requests",
40
- "tensorboard": "tensorboard",
41
- "torch": "torch>=1.4",
42
- "torchvision": "torchvision",
43
- "transformers": "transformers>=4.25.1",
44
- "urllib3": "urllib3<=2.0.0",
45
- "black": "black",
46
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/experimental/README.md DELETED
@@ -1,5 +0,0 @@
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 DELETED
@@ -1 +0,0 @@
1
- from .rl import ValueGuidedRLPipeline
 
 
diffusers/experimental/rl/__init__.py DELETED
@@ -1 +0,0 @@
1
- from .value_guided_sampling import ValueGuidedRLPipeline
 
 
diffusers/experimental/rl/value_guided_sampling.py DELETED
@@ -1,153 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import numpy as np
16
- import torch
17
- import tqdm
18
-
19
- from ...models.unets.unet_1d import UNet1DModel
20
- from ...pipelines import DiffusionPipeline
21
- from ...utils.dummy_pt_objects import DDPMScheduler
22
- from ...utils.torch_utils import randn_tensor
23
-
24
-
25
- class ValueGuidedRLPipeline(DiffusionPipeline):
26
- r"""
27
- Pipeline for value-guided sampling from a diffusion model trained to predict sequences of states.
28
-
29
- This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
30
- implemented for all pipelines (downloading, saving, running on a particular device, etc.).
31
-
32
- Parameters:
33
- value_function ([`UNet1DModel`]):
34
- A specialized UNet for fine-tuning trajectories base on reward.
35
- unet ([`UNet1DModel`]):
36
- UNet architecture to denoise the encoded trajectories.
37
- scheduler ([`SchedulerMixin`]):
38
- A scheduler to be used in combination with `unet` to denoise the encoded trajectories. Default for this
39
- application is [`DDPMScheduler`].
40
- env ():
41
- An environment following the OpenAI gym API to act in. For now only Hopper has pretrained models.
42
- """
43
-
44
- def __init__(
45
- self,
46
- value_function: UNet1DModel,
47
- unet: UNet1DModel,
48
- scheduler: DDPMScheduler,
49
- env,
50
- ):
51
- super().__init__()
52
-
53
- self.register_modules(value_function=value_function, unet=unet, scheduler=scheduler, env=env)
54
-
55
- self.data = env.get_dataset()
56
- self.means = {}
57
- for key in self.data.keys():
58
- try:
59
- self.means[key] = self.data[key].mean()
60
- except: # noqa: E722
61
- pass
62
- self.stds = {}
63
- for key in self.data.keys():
64
- try:
65
- self.stds[key] = self.data[key].std()
66
- except: # noqa: E722
67
- pass
68
- self.state_dim = env.observation_space.shape[0]
69
- self.action_dim = env.action_space.shape[0]
70
-
71
- def normalize(self, x_in, key):
72
- return (x_in - self.means[key]) / self.stds[key]
73
-
74
- def de_normalize(self, x_in, key):
75
- return x_in * self.stds[key] + self.means[key]
76
-
77
- def to_torch(self, x_in):
78
- if isinstance(x_in, dict):
79
- return {k: self.to_torch(v) for k, v in x_in.items()}
80
- elif torch.is_tensor(x_in):
81
- return x_in.to(self.unet.device)
82
- return torch.tensor(x_in, device=self.unet.device)
83
-
84
- def reset_x0(self, x_in, cond, act_dim):
85
- for key, val in cond.items():
86
- x_in[:, key, act_dim:] = val.clone()
87
- return x_in
88
-
89
- def run_diffusion(self, x, conditions, n_guide_steps, scale):
90
- batch_size = x.shape[0]
91
- y = None
92
- for i in tqdm.tqdm(self.scheduler.timesteps):
93
- # create batch of timesteps to pass into model
94
- timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
95
- for _ in range(n_guide_steps):
96
- with torch.enable_grad():
97
- x.requires_grad_()
98
-
99
- # permute to match dimension for pre-trained models
100
- y = self.value_function(x.permute(0, 2, 1), timesteps).sample
101
- grad = torch.autograd.grad([y.sum()], [x])[0]
102
-
103
- posterior_variance = self.scheduler._get_variance(i)
104
- model_std = torch.exp(0.5 * posterior_variance)
105
- grad = model_std * grad
106
-
107
- grad[timesteps < 2] = 0
108
- x = x.detach()
109
- x = x + scale * grad
110
- x = self.reset_x0(x, conditions, self.action_dim)
111
-
112
- prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
113
-
114
- # TODO: verify deprecation of this kwarg
115
- x = self.scheduler.step(prev_x, i, x)["prev_sample"]
116
-
117
- # apply conditions to the trajectory (set the initial state)
118
- x = self.reset_x0(x, conditions, self.action_dim)
119
- x = self.to_torch(x)
120
- return x, y
121
-
122
- def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
123
- # normalize the observations and create batch dimension
124
- obs = self.normalize(obs, "observations")
125
- obs = obs[None].repeat(batch_size, axis=0)
126
-
127
- conditions = {0: self.to_torch(obs)}
128
- shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
129
-
130
- # generate initial noise and apply our conditions (to make the trajectories start at current state)
131
- x1 = randn_tensor(shape, device=self.unet.device)
132
- x = self.reset_x0(x1, conditions, self.action_dim)
133
- x = self.to_torch(x)
134
-
135
- # run the diffusion process
136
- x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
137
-
138
- # sort output trajectories by value
139
- sorted_idx = y.argsort(0, descending=True).squeeze()
140
- sorted_values = x[sorted_idx]
141
- actions = sorted_values[:, :, : self.action_dim]
142
- actions = actions.detach().cpu().numpy()
143
- denorm_actions = self.de_normalize(actions, key="actions")
144
-
145
- # select the action with the highest value
146
- if y is not None:
147
- selected_index = 0
148
- else:
149
- # if we didn't run value guiding, select a random action
150
- selected_index = np.random.randint(0, batch_size)
151
-
152
- denorm_actions = denorm_actions[selected_index, 0]
153
- return denorm_actions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/image_processor.py DELETED
@@ -1,1070 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import math
16
- import warnings
17
- from typing import List, Optional, Tuple, Union
18
-
19
- import numpy as np
20
- import PIL.Image
21
- import torch
22
- import torch.nn.functional as F
23
- from PIL import Image, ImageFilter, ImageOps
24
-
25
- from .configuration_utils import ConfigMixin, register_to_config
26
- from .utils import CONFIG_NAME, PIL_INTERPOLATION, deprecate
27
-
28
-
29
- PipelineImageInput = Union[
30
- PIL.Image.Image,
31
- np.ndarray,
32
- torch.FloatTensor,
33
- List[PIL.Image.Image],
34
- List[np.ndarray],
35
- List[torch.FloatTensor],
36
- ]
37
-
38
- PipelineDepthInput = PipelineImageInput
39
-
40
-
41
- class VaeImageProcessor(ConfigMixin):
42
- """
43
- Image processor for VAE.
44
-
45
- Args:
46
- do_resize (`bool`, *optional*, defaults to `True`):
47
- Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
48
- `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
49
- vae_scale_factor (`int`, *optional*, defaults to `8`):
50
- VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
51
- resample (`str`, *optional*, defaults to `lanczos`):
52
- Resampling filter to use when resizing the image.
53
- do_normalize (`bool`, *optional*, defaults to `True`):
54
- Whether to normalize the image to [-1,1].
55
- do_binarize (`bool`, *optional*, defaults to `False`):
56
- Whether to binarize the image to 0/1.
57
- do_convert_rgb (`bool`, *optional*, defaults to be `False`):
58
- Whether to convert the images to RGB format.
59
- do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
60
- Whether to convert the images to grayscale format.
61
- """
62
-
63
- config_name = CONFIG_NAME
64
-
65
- @register_to_config
66
- def __init__(
67
- self,
68
- do_resize: bool = True,
69
- vae_scale_factor: int = 8,
70
- resample: str = "lanczos",
71
- do_normalize: bool = True,
72
- do_binarize: bool = False,
73
- do_convert_rgb: bool = False,
74
- do_convert_grayscale: bool = False,
75
- ):
76
- super().__init__()
77
- if do_convert_rgb and do_convert_grayscale:
78
- raise ValueError(
79
- "`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`,"
80
- " if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.",
81
- " if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`",
82
- )
83
- self.config.do_convert_rgb = False
84
-
85
- @staticmethod
86
- def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
87
- """
88
- Convert a numpy image or a batch of images to a PIL image.
89
- """
90
- if images.ndim == 3:
91
- images = images[None, ...]
92
- images = (images * 255).round().astype("uint8")
93
- if images.shape[-1] == 1:
94
- # special case for grayscale (single channel) images
95
- pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
96
- else:
97
- pil_images = [Image.fromarray(image) for image in images]
98
-
99
- return pil_images
100
-
101
- @staticmethod
102
- def pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
103
- """
104
- Convert a PIL image or a list of PIL images to NumPy arrays.
105
- """
106
- if not isinstance(images, list):
107
- images = [images]
108
- images = [np.array(image).astype(np.float32) / 255.0 for image in images]
109
- images = np.stack(images, axis=0)
110
-
111
- return images
112
-
113
- @staticmethod
114
- def numpy_to_pt(images: np.ndarray) -> torch.FloatTensor:
115
- """
116
- Convert a NumPy image to a PyTorch tensor.
117
- """
118
- if images.ndim == 3:
119
- images = images[..., None]
120
-
121
- images = torch.from_numpy(images.transpose(0, 3, 1, 2))
122
- return images
123
-
124
- @staticmethod
125
- def pt_to_numpy(images: torch.FloatTensor) -> np.ndarray:
126
- """
127
- Convert a PyTorch tensor to a NumPy image.
128
- """
129
- images = images.cpu().permute(0, 2, 3, 1).float().numpy()
130
- return images
131
-
132
- @staticmethod
133
- def normalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
134
- """
135
- Normalize an image array to [-1,1].
136
- """
137
- return 2.0 * images - 1.0
138
-
139
- @staticmethod
140
- def denormalize(images: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
141
- """
142
- Denormalize an image array to [0,1].
143
- """
144
- return (images / 2 + 0.5).clamp(0, 1)
145
-
146
- @staticmethod
147
- def convert_to_rgb(image: PIL.Image.Image) -> PIL.Image.Image:
148
- """
149
- Converts a PIL image to RGB format.
150
- """
151
- image = image.convert("RGB")
152
-
153
- return image
154
-
155
- @staticmethod
156
- def convert_to_grayscale(image: PIL.Image.Image) -> PIL.Image.Image:
157
- """
158
- Converts a PIL image to grayscale format.
159
- """
160
- image = image.convert("L")
161
-
162
- return image
163
-
164
- @staticmethod
165
- def blur(image: PIL.Image.Image, blur_factor: int = 4) -> PIL.Image.Image:
166
- """
167
- Applies Gaussian blur to an image.
168
- """
169
- image = image.filter(ImageFilter.GaussianBlur(blur_factor))
170
-
171
- return image
172
-
173
- @staticmethod
174
- def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0):
175
- """
176
- Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect
177
- ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for
178
- processing are 512x512, the region will be expanded to 128x128.
179
-
180
- Args:
181
- mask_image (PIL.Image.Image): Mask image.
182
- width (int): Width of the image to be processed.
183
- height (int): Height of the image to be processed.
184
- pad (int, optional): Padding to be added to the crop region. Defaults to 0.
185
-
186
- Returns:
187
- tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and
188
- matches the original aspect ratio.
189
- """
190
-
191
- mask_image = mask_image.convert("L")
192
- mask = np.array(mask_image)
193
-
194
- # 1. find a rectangular region that contains all masked ares in an image
195
- h, w = mask.shape
196
- crop_left = 0
197
- for i in range(w):
198
- if not (mask[:, i] == 0).all():
199
- break
200
- crop_left += 1
201
-
202
- crop_right = 0
203
- for i in reversed(range(w)):
204
- if not (mask[:, i] == 0).all():
205
- break
206
- crop_right += 1
207
-
208
- crop_top = 0
209
- for i in range(h):
210
- if not (mask[i] == 0).all():
211
- break
212
- crop_top += 1
213
-
214
- crop_bottom = 0
215
- for i in reversed(range(h)):
216
- if not (mask[i] == 0).all():
217
- break
218
- crop_bottom += 1
219
-
220
- # 2. add padding to the crop region
221
- x1, y1, x2, y2 = (
222
- int(max(crop_left - pad, 0)),
223
- int(max(crop_top - pad, 0)),
224
- int(min(w - crop_right + pad, w)),
225
- int(min(h - crop_bottom + pad, h)),
226
- )
227
-
228
- # 3. expands crop region to match the aspect ratio of the image to be processed
229
- ratio_crop_region = (x2 - x1) / (y2 - y1)
230
- ratio_processing = width / height
231
-
232
- if ratio_crop_region > ratio_processing:
233
- desired_height = (x2 - x1) / ratio_processing
234
- desired_height_diff = int(desired_height - (y2 - y1))
235
- y1 -= desired_height_diff // 2
236
- y2 += desired_height_diff - desired_height_diff // 2
237
- if y2 >= mask_image.height:
238
- diff = y2 - mask_image.height
239
- y2 -= diff
240
- y1 -= diff
241
- if y1 < 0:
242
- y2 -= y1
243
- y1 -= y1
244
- if y2 >= mask_image.height:
245
- y2 = mask_image.height
246
- else:
247
- desired_width = (y2 - y1) * ratio_processing
248
- desired_width_diff = int(desired_width - (x2 - x1))
249
- x1 -= desired_width_diff // 2
250
- x2 += desired_width_diff - desired_width_diff // 2
251
- if x2 >= mask_image.width:
252
- diff = x2 - mask_image.width
253
- x2 -= diff
254
- x1 -= diff
255
- if x1 < 0:
256
- x2 -= x1
257
- x1 -= x1
258
- if x2 >= mask_image.width:
259
- x2 = mask_image.width
260
-
261
- return x1, y1, x2, y2
262
-
263
- def _resize_and_fill(
264
- self,
265
- image: PIL.Image.Image,
266
- width: int,
267
- height: int,
268
- ) -> PIL.Image.Image:
269
- """
270
- Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
271
- the image within the dimensions, filling empty with data from image.
272
-
273
- Args:
274
- image: The image to resize.
275
- width: The width to resize the image to.
276
- height: The height to resize the image to.
277
- """
278
-
279
- ratio = width / height
280
- src_ratio = image.width / image.height
281
-
282
- src_w = width if ratio < src_ratio else image.width * height // image.height
283
- src_h = height if ratio >= src_ratio else image.height * width // image.width
284
-
285
- resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
286
- res = Image.new("RGB", (width, height))
287
- res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
288
-
289
- if ratio < src_ratio:
290
- fill_height = height // 2 - src_h // 2
291
- if fill_height > 0:
292
- res.paste(resized.resize((width, fill_height), box=(0, 0, width, 0)), box=(0, 0))
293
- res.paste(
294
- resized.resize((width, fill_height), box=(0, resized.height, width, resized.height)),
295
- box=(0, fill_height + src_h),
296
- )
297
- elif ratio > src_ratio:
298
- fill_width = width // 2 - src_w // 2
299
- if fill_width > 0:
300
- res.paste(resized.resize((fill_width, height), box=(0, 0, 0, height)), box=(0, 0))
301
- res.paste(
302
- resized.resize((fill_width, height), box=(resized.width, 0, resized.width, height)),
303
- box=(fill_width + src_w, 0),
304
- )
305
-
306
- return res
307
-
308
- def _resize_and_crop(
309
- self,
310
- image: PIL.Image.Image,
311
- width: int,
312
- height: int,
313
- ) -> PIL.Image.Image:
314
- """
315
- Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
316
- the image within the dimensions, cropping the excess.
317
-
318
- Args:
319
- image: The image to resize.
320
- width: The width to resize the image to.
321
- height: The height to resize the image to.
322
- """
323
- ratio = width / height
324
- src_ratio = image.width / image.height
325
-
326
- src_w = width if ratio > src_ratio else image.width * height // image.height
327
- src_h = height if ratio <= src_ratio else image.height * width // image.width
328
-
329
- resized = image.resize((src_w, src_h), resample=PIL_INTERPOLATION["lanczos"])
330
- res = Image.new("RGB", (width, height))
331
- res.paste(resized, box=(width // 2 - src_w // 2, height // 2 - src_h // 2))
332
- return res
333
-
334
- def resize(
335
- self,
336
- image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
337
- height: int,
338
- width: int,
339
- resize_mode: str = "default", # "default", "fill", "crop"
340
- ) -> Union[PIL.Image.Image, np.ndarray, torch.Tensor]:
341
- """
342
- Resize image.
343
-
344
- Args:
345
- image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
346
- The image input, can be a PIL image, numpy array or pytorch tensor.
347
- height (`int`):
348
- The height to resize to.
349
- width (`int`):
350
- The width to resize to.
351
- resize_mode (`str`, *optional*, defaults to `default`):
352
- The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
353
- within the specified width and height, and it may not maintaining the original aspect ratio. If `fill`,
354
- will resize the image to fit within the specified width and height, maintaining the aspect ratio, and
355
- then center the image within the dimensions, filling empty with data from image. If `crop`, will resize
356
- the image to fit within the specified width and height, maintaining the aspect ratio, and then center
357
- the image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
358
- supported for PIL image input.
359
-
360
- Returns:
361
- `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
362
- The resized image.
363
- """
364
- if resize_mode != "default" and not isinstance(image, PIL.Image.Image):
365
- raise ValueError(f"Only PIL image input is supported for resize_mode {resize_mode}")
366
- if isinstance(image, PIL.Image.Image):
367
- if resize_mode == "default":
368
- image = image.resize((width, height), resample=PIL_INTERPOLATION[self.config.resample])
369
- elif resize_mode == "fill":
370
- image = self._resize_and_fill(image, width, height)
371
- elif resize_mode == "crop":
372
- image = self._resize_and_crop(image, width, height)
373
- else:
374
- raise ValueError(f"resize_mode {resize_mode} is not supported")
375
-
376
- elif isinstance(image, torch.Tensor):
377
- image = torch.nn.functional.interpolate(
378
- image,
379
- size=(height, width),
380
- )
381
- elif isinstance(image, np.ndarray):
382
- image = self.numpy_to_pt(image)
383
- image = torch.nn.functional.interpolate(
384
- image,
385
- size=(height, width),
386
- )
387
- image = self.pt_to_numpy(image)
388
- return image
389
-
390
- def binarize(self, image: PIL.Image.Image) -> PIL.Image.Image:
391
- """
392
- Create a mask.
393
-
394
- Args:
395
- image (`PIL.Image.Image`):
396
- The image input, should be a PIL image.
397
-
398
- Returns:
399
- `PIL.Image.Image`:
400
- The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
401
- """
402
- image[image < 0.5] = 0
403
- image[image >= 0.5] = 1
404
-
405
- return image
406
-
407
- def get_default_height_width(
408
- self,
409
- image: Union[PIL.Image.Image, np.ndarray, torch.Tensor],
410
- height: Optional[int] = None,
411
- width: Optional[int] = None,
412
- ) -> Tuple[int, int]:
413
- """
414
- This function return the height and width that are downscaled to the next integer multiple of
415
- `vae_scale_factor`.
416
-
417
- Args:
418
- image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
419
- The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
420
- shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
421
- have shape `[batch, channel, height, width]`.
422
- height (`int`, *optional*, defaults to `None`):
423
- The height in preprocessed image. If `None`, will use the height of `image` input.
424
- width (`int`, *optional*`, defaults to `None`):
425
- The width in preprocessed. If `None`, will use the width of the `image` input.
426
- """
427
-
428
- if height is None:
429
- if isinstance(image, PIL.Image.Image):
430
- height = image.height
431
- elif isinstance(image, torch.Tensor):
432
- height = image.shape[2]
433
- else:
434
- height = image.shape[1]
435
-
436
- if width is None:
437
- if isinstance(image, PIL.Image.Image):
438
- width = image.width
439
- elif isinstance(image, torch.Tensor):
440
- width = image.shape[3]
441
- else:
442
- width = image.shape[2]
443
-
444
- width, height = (
445
- x - x % self.config.vae_scale_factor for x in (width, height)
446
- ) # resize to integer multiple of vae_scale_factor
447
-
448
- return height, width
449
-
450
- def preprocess(
451
- self,
452
- image: PipelineImageInput,
453
- height: Optional[int] = None,
454
- width: Optional[int] = None,
455
- resize_mode: str = "default", # "default", "fill", "crop"
456
- crops_coords: Optional[Tuple[int, int, int, int]] = None,
457
- ) -> torch.Tensor:
458
- """
459
- Preprocess the image input.
460
-
461
- Args:
462
- image (`pipeline_image_input`):
463
- The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
464
- supported formats.
465
- height (`int`, *optional*, defaults to `None`):
466
- The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default
467
- height.
468
- width (`int`, *optional*`, defaults to `None`):
469
- The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
470
- resize_mode (`str`, *optional*, defaults to `default`):
471
- The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit within
472
- the specified width and height, and it may not maintaining the original aspect ratio. If `fill`, will
473
- resize the image to fit within the specified width and height, maintaining the aspect ratio, and then
474
- center the image within the dimensions, filling empty with data from image. If `crop`, will resize the
475
- image to fit within the specified width and height, maintaining the aspect ratio, and then center the
476
- image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
477
- supported for PIL image input.
478
- crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
479
- The crop coordinates for each image in the batch. If `None`, will not crop the image.
480
- """
481
- supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
482
-
483
- # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
484
- if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3:
485
- if isinstance(image, torch.Tensor):
486
- # if image is a pytorch tensor could have 2 possible shapes:
487
- # 1. batch x height x width: we should insert the channel dimension at position 1
488
- # 2. channel x height x width: we should insert batch dimension at position 0,
489
- # however, since both channel and batch dimension has same size 1, it is same to insert at position 1
490
- # for simplicity, we insert a dimension of size 1 at position 1 for both cases
491
- image = image.unsqueeze(1)
492
- else:
493
- # if it is a numpy array, it could have 2 possible shapes:
494
- # 1. batch x height x width: insert channel dimension on last position
495
- # 2. height x width x channel: insert batch dimension on first position
496
- if image.shape[-1] == 1:
497
- image = np.expand_dims(image, axis=0)
498
- else:
499
- image = np.expand_dims(image, axis=-1)
500
-
501
- if isinstance(image, supported_formats):
502
- image = [image]
503
- elif not (isinstance(image, list) and all(isinstance(i, supported_formats) for i in image)):
504
- raise ValueError(
505
- f"Input is in incorrect format: {[type(i) for i in image]}. Currently, we only support {', '.join(supported_formats)}"
506
- )
507
-
508
- if isinstance(image[0], PIL.Image.Image):
509
- if crops_coords is not None:
510
- image = [i.crop(crops_coords) for i in image]
511
- if self.config.do_resize:
512
- height, width = self.get_default_height_width(image[0], height, width)
513
- image = [self.resize(i, height, width, resize_mode=resize_mode) for i in image]
514
- if self.config.do_convert_rgb:
515
- image = [self.convert_to_rgb(i) for i in image]
516
- elif self.config.do_convert_grayscale:
517
- image = [self.convert_to_grayscale(i) for i in image]
518
- image = self.pil_to_numpy(image) # to np
519
- image = self.numpy_to_pt(image) # to pt
520
-
521
- elif isinstance(image[0], np.ndarray):
522
- image = np.concatenate(image, axis=0) if image[0].ndim == 4 else np.stack(image, axis=0)
523
-
524
- image = self.numpy_to_pt(image)
525
-
526
- height, width = self.get_default_height_width(image, height, width)
527
- if self.config.do_resize:
528
- image = self.resize(image, height, width)
529
-
530
- elif isinstance(image[0], torch.Tensor):
531
- image = torch.cat(image, axis=0) if image[0].ndim == 4 else torch.stack(image, axis=0)
532
-
533
- if self.config.do_convert_grayscale and image.ndim == 3:
534
- image = image.unsqueeze(1)
535
-
536
- channel = image.shape[1]
537
- # don't need any preprocess if the image is latents
538
- if channel == 4:
539
- return image
540
-
541
- height, width = self.get_default_height_width(image, height, width)
542
- if self.config.do_resize:
543
- image = self.resize(image, height, width)
544
-
545
- # expected range [0,1], normalize to [-1,1]
546
- do_normalize = self.config.do_normalize
547
- if do_normalize and image.min() < 0:
548
- warnings.warn(
549
- "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
550
- f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{image.min()},{image.max()}]",
551
- FutureWarning,
552
- )
553
- do_normalize = False
554
-
555
- if do_normalize:
556
- image = self.normalize(image)
557
-
558
- if self.config.do_binarize:
559
- image = self.binarize(image)
560
-
561
- return image
562
-
563
- def postprocess(
564
- self,
565
- image: torch.FloatTensor,
566
- output_type: str = "pil",
567
- do_denormalize: Optional[List[bool]] = None,
568
- ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
569
- """
570
- Postprocess the image output from tensor to `output_type`.
571
-
572
- Args:
573
- image (`torch.FloatTensor`):
574
- The image input, should be a pytorch tensor with shape `B x C x H x W`.
575
- output_type (`str`, *optional*, defaults to `pil`):
576
- The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
577
- do_denormalize (`List[bool]`, *optional*, defaults to `None`):
578
- Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
579
- `VaeImageProcessor` config.
580
-
581
- Returns:
582
- `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
583
- The postprocessed image.
584
- """
585
- if not isinstance(image, torch.Tensor):
586
- raise ValueError(
587
- f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
588
- )
589
- if output_type not in ["latent", "pt", "np", "pil"]:
590
- deprecation_message = (
591
- f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
592
- "`pil`, `np`, `pt`, `latent`"
593
- )
594
- deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
595
- output_type = "np"
596
-
597
- if output_type == "latent":
598
- return image
599
-
600
- if do_denormalize is None:
601
- do_denormalize = [self.config.do_normalize] * image.shape[0]
602
-
603
- image = torch.stack(
604
- [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
605
- )
606
-
607
- if output_type == "pt":
608
- return image
609
-
610
- image = self.pt_to_numpy(image)
611
-
612
- if output_type == "np":
613
- return image
614
-
615
- if output_type == "pil":
616
- return self.numpy_to_pil(image)
617
-
618
- def apply_overlay(
619
- self,
620
- mask: PIL.Image.Image,
621
- init_image: PIL.Image.Image,
622
- image: PIL.Image.Image,
623
- crop_coords: Optional[Tuple[int, int, int, int]] = None,
624
- ) -> PIL.Image.Image:
625
- """
626
- overlay the inpaint output to the original image
627
- """
628
-
629
- width, height = image.width, image.height
630
-
631
- init_image = self.resize(init_image, width=width, height=height)
632
- mask = self.resize(mask, width=width, height=height)
633
-
634
- init_image_masked = PIL.Image.new("RGBa", (width, height))
635
- init_image_masked.paste(init_image.convert("RGBA").convert("RGBa"), mask=ImageOps.invert(mask.convert("L")))
636
- init_image_masked = init_image_masked.convert("RGBA")
637
-
638
- if crop_coords is not None:
639
- x, y, x2, y2 = crop_coords
640
- w = x2 - x
641
- h = y2 - y
642
- base_image = PIL.Image.new("RGBA", (width, height))
643
- image = self.resize(image, height=h, width=w, resize_mode="crop")
644
- base_image.paste(image, (x, y))
645
- image = base_image.convert("RGB")
646
-
647
- image = image.convert("RGBA")
648
- image.alpha_composite(init_image_masked)
649
- image = image.convert("RGB")
650
-
651
- return image
652
-
653
-
654
- class VaeImageProcessorLDM3D(VaeImageProcessor):
655
- """
656
- Image processor for VAE LDM3D.
657
-
658
- Args:
659
- do_resize (`bool`, *optional*, defaults to `True`):
660
- Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
661
- vae_scale_factor (`int`, *optional*, defaults to `8`):
662
- VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
663
- resample (`str`, *optional*, defaults to `lanczos`):
664
- Resampling filter to use when resizing the image.
665
- do_normalize (`bool`, *optional*, defaults to `True`):
666
- Whether to normalize the image to [-1,1].
667
- """
668
-
669
- config_name = CONFIG_NAME
670
-
671
- @register_to_config
672
- def __init__(
673
- self,
674
- do_resize: bool = True,
675
- vae_scale_factor: int = 8,
676
- resample: str = "lanczos",
677
- do_normalize: bool = True,
678
- ):
679
- super().__init__()
680
-
681
- @staticmethod
682
- def numpy_to_pil(images: np.ndarray) -> List[PIL.Image.Image]:
683
- """
684
- Convert a NumPy image or a batch of images to a PIL image.
685
- """
686
- if images.ndim == 3:
687
- images = images[None, ...]
688
- images = (images * 255).round().astype("uint8")
689
- if images.shape[-1] == 1:
690
- # special case for grayscale (single channel) images
691
- pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
692
- else:
693
- pil_images = [Image.fromarray(image[:, :, :3]) for image in images]
694
-
695
- return pil_images
696
-
697
- @staticmethod
698
- def depth_pil_to_numpy(images: Union[List[PIL.Image.Image], PIL.Image.Image]) -> np.ndarray:
699
- """
700
- Convert a PIL image or a list of PIL images to NumPy arrays.
701
- """
702
- if not isinstance(images, list):
703
- images = [images]
704
-
705
- images = [np.array(image).astype(np.float32) / (2**16 - 1) for image in images]
706
- images = np.stack(images, axis=0)
707
- return images
708
-
709
- @staticmethod
710
- def rgblike_to_depthmap(image: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]:
711
- """
712
- Args:
713
- image: RGB-like depth image
714
-
715
- Returns: depth map
716
-
717
- """
718
- return image[:, :, 1] * 2**8 + image[:, :, 2]
719
-
720
- def numpy_to_depth(self, images: np.ndarray) -> List[PIL.Image.Image]:
721
- """
722
- Convert a NumPy depth image or a batch of images to a PIL image.
723
- """
724
- if images.ndim == 3:
725
- images = images[None, ...]
726
- images_depth = images[:, :, :, 3:]
727
- if images.shape[-1] == 6:
728
- images_depth = (images_depth * 255).round().astype("uint8")
729
- pil_images = [
730
- Image.fromarray(self.rgblike_to_depthmap(image_depth), mode="I;16") for image_depth in images_depth
731
- ]
732
- elif images.shape[-1] == 4:
733
- images_depth = (images_depth * 65535.0).astype(np.uint16)
734
- pil_images = [Image.fromarray(image_depth, mode="I;16") for image_depth in images_depth]
735
- else:
736
- raise Exception("Not supported")
737
-
738
- return pil_images
739
-
740
- def postprocess(
741
- self,
742
- image: torch.FloatTensor,
743
- output_type: str = "pil",
744
- do_denormalize: Optional[List[bool]] = None,
745
- ) -> Union[PIL.Image.Image, np.ndarray, torch.FloatTensor]:
746
- """
747
- Postprocess the image output from tensor to `output_type`.
748
-
749
- Args:
750
- image (`torch.FloatTensor`):
751
- The image input, should be a pytorch tensor with shape `B x C x H x W`.
752
- output_type (`str`, *optional*, defaults to `pil`):
753
- The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
754
- do_denormalize (`List[bool]`, *optional*, defaults to `None`):
755
- Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
756
- `VaeImageProcessor` config.
757
-
758
- Returns:
759
- `PIL.Image.Image`, `np.ndarray` or `torch.FloatTensor`:
760
- The postprocessed image.
761
- """
762
- if not isinstance(image, torch.Tensor):
763
- raise ValueError(
764
- f"Input for postprocessing is in incorrect format: {type(image)}. We only support pytorch tensor"
765
- )
766
- if output_type not in ["latent", "pt", "np", "pil"]:
767
- deprecation_message = (
768
- f"the output_type {output_type} is outdated and has been set to `np`. Please make sure to set it to one of these instead: "
769
- "`pil`, `np`, `pt`, `latent`"
770
- )
771
- deprecate("Unsupported output_type", "1.0.0", deprecation_message, standard_warn=False)
772
- output_type = "np"
773
-
774
- if do_denormalize is None:
775
- do_denormalize = [self.config.do_normalize] * image.shape[0]
776
-
777
- image = torch.stack(
778
- [self.denormalize(image[i]) if do_denormalize[i] else image[i] for i in range(image.shape[0])]
779
- )
780
-
781
- image = self.pt_to_numpy(image)
782
-
783
- if output_type == "np":
784
- if image.shape[-1] == 6:
785
- image_depth = np.stack([self.rgblike_to_depthmap(im[:, :, 3:]) for im in image], axis=0)
786
- else:
787
- image_depth = image[:, :, :, 3:]
788
- return image[:, :, :, :3], image_depth
789
-
790
- if output_type == "pil":
791
- return self.numpy_to_pil(image), self.numpy_to_depth(image)
792
- else:
793
- raise Exception(f"This type {output_type} is not supported")
794
-
795
- def preprocess(
796
- self,
797
- rgb: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
798
- depth: Union[torch.FloatTensor, PIL.Image.Image, np.ndarray],
799
- height: Optional[int] = None,
800
- width: Optional[int] = None,
801
- target_res: Optional[int] = None,
802
- ) -> torch.Tensor:
803
- """
804
- Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
805
- """
806
- supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor)
807
-
808
- # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image
809
- if self.config.do_convert_grayscale and isinstance(rgb, (torch.Tensor, np.ndarray)) and rgb.ndim == 3:
810
- raise Exception("This is not yet supported")
811
-
812
- if isinstance(rgb, supported_formats):
813
- rgb = [rgb]
814
- depth = [depth]
815
- elif not (isinstance(rgb, list) and all(isinstance(i, supported_formats) for i in rgb)):
816
- raise ValueError(
817
- f"Input is in incorrect format: {[type(i) for i in rgb]}. Currently, we only support {', '.join(supported_formats)}"
818
- )
819
-
820
- if isinstance(rgb[0], PIL.Image.Image):
821
- if self.config.do_convert_rgb:
822
- raise Exception("This is not yet supported")
823
- # rgb = [self.convert_to_rgb(i) for i in rgb]
824
- # depth = [self.convert_to_depth(i) for i in depth] #TODO define convert_to_depth
825
- if self.config.do_resize or target_res:
826
- height, width = self.get_default_height_width(rgb[0], height, width) if not target_res else target_res
827
- rgb = [self.resize(i, height, width) for i in rgb]
828
- depth = [self.resize(i, height, width) for i in depth]
829
- rgb = self.pil_to_numpy(rgb) # to np
830
- rgb = self.numpy_to_pt(rgb) # to pt
831
-
832
- depth = self.depth_pil_to_numpy(depth) # to np
833
- depth = self.numpy_to_pt(depth) # to pt
834
-
835
- elif isinstance(rgb[0], np.ndarray):
836
- rgb = np.concatenate(rgb, axis=0) if rgb[0].ndim == 4 else np.stack(rgb, axis=0)
837
- rgb = self.numpy_to_pt(rgb)
838
- height, width = self.get_default_height_width(rgb, height, width)
839
- if self.config.do_resize:
840
- rgb = self.resize(rgb, height, width)
841
-
842
- depth = np.concatenate(depth, axis=0) if rgb[0].ndim == 4 else np.stack(depth, axis=0)
843
- depth = self.numpy_to_pt(depth)
844
- height, width = self.get_default_height_width(depth, height, width)
845
- if self.config.do_resize:
846
- depth = self.resize(depth, height, width)
847
-
848
- elif isinstance(rgb[0], torch.Tensor):
849
- raise Exception("This is not yet supported")
850
- # rgb = torch.cat(rgb, axis=0) if rgb[0].ndim == 4 else torch.stack(rgb, axis=0)
851
-
852
- # if self.config.do_convert_grayscale and rgb.ndim == 3:
853
- # rgb = rgb.unsqueeze(1)
854
-
855
- # channel = rgb.shape[1]
856
-
857
- # height, width = self.get_default_height_width(rgb, height, width)
858
- # if self.config.do_resize:
859
- # rgb = self.resize(rgb, height, width)
860
-
861
- # depth = torch.cat(depth, axis=0) if depth[0].ndim == 4 else torch.stack(depth, axis=0)
862
-
863
- # if self.config.do_convert_grayscale and depth.ndim == 3:
864
- # depth = depth.unsqueeze(1)
865
-
866
- # channel = depth.shape[1]
867
- # # don't need any preprocess if the image is latents
868
- # if depth == 4:
869
- # return rgb, depth
870
-
871
- # height, width = self.get_default_height_width(depth, height, width)
872
- # if self.config.do_resize:
873
- # depth = self.resize(depth, height, width)
874
- # expected range [0,1], normalize to [-1,1]
875
- do_normalize = self.config.do_normalize
876
- if rgb.min() < 0 and do_normalize:
877
- warnings.warn(
878
- "Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] "
879
- f"when passing as pytorch tensor or numpy Array. You passed `image` with value range [{rgb.min()},{rgb.max()}]",
880
- FutureWarning,
881
- )
882
- do_normalize = False
883
-
884
- if do_normalize:
885
- rgb = self.normalize(rgb)
886
- depth = self.normalize(depth)
887
-
888
- if self.config.do_binarize:
889
- rgb = self.binarize(rgb)
890
- depth = self.binarize(depth)
891
-
892
- return rgb, depth
893
-
894
-
895
- class IPAdapterMaskProcessor(VaeImageProcessor):
896
- """
897
- Image processor for IP Adapter image masks.
898
-
899
- Args:
900
- do_resize (`bool`, *optional*, defaults to `True`):
901
- Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
902
- vae_scale_factor (`int`, *optional*, defaults to `8`):
903
- VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
904
- resample (`str`, *optional*, defaults to `lanczos`):
905
- Resampling filter to use when resizing the image.
906
- do_normalize (`bool`, *optional*, defaults to `False`):
907
- Whether to normalize the image to [-1,1].
908
- do_binarize (`bool`, *optional*, defaults to `True`):
909
- Whether to binarize the image to 0/1.
910
- do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
911
- Whether to convert the images to grayscale format.
912
-
913
- """
914
-
915
- config_name = CONFIG_NAME
916
-
917
- @register_to_config
918
- def __init__(
919
- self,
920
- do_resize: bool = True,
921
- vae_scale_factor: int = 8,
922
- resample: str = "lanczos",
923
- do_normalize: bool = False,
924
- do_binarize: bool = True,
925
- do_convert_grayscale: bool = True,
926
- ):
927
- super().__init__(
928
- do_resize=do_resize,
929
- vae_scale_factor=vae_scale_factor,
930
- resample=resample,
931
- do_normalize=do_normalize,
932
- do_binarize=do_binarize,
933
- do_convert_grayscale=do_convert_grayscale,
934
- )
935
-
936
- @staticmethod
937
- def downsample(mask: torch.FloatTensor, batch_size: int, num_queries: int, value_embed_dim: int):
938
- """
939
- Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention. If the
940
- aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.
941
-
942
- Args:
943
- mask (`torch.FloatTensor`):
944
- The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
945
- batch_size (`int`):
946
- The batch size.
947
- num_queries (`int`):
948
- The number of queries.
949
- value_embed_dim (`int`):
950
- The dimensionality of the value embeddings.
951
-
952
- Returns:
953
- `torch.FloatTensor`:
954
- The downsampled mask tensor.
955
-
956
- """
957
- o_h = mask.shape[1]
958
- o_w = mask.shape[2]
959
- ratio = o_w / o_h
960
- mask_h = int(math.sqrt(num_queries / ratio))
961
- mask_h = int(mask_h) + int((num_queries % int(mask_h)) != 0)
962
- mask_w = num_queries // mask_h
963
-
964
- mask_downsample = F.interpolate(mask.unsqueeze(0), size=(mask_h, mask_w), mode="bicubic").squeeze(0)
965
-
966
- # Repeat batch_size times
967
- if mask_downsample.shape[0] < batch_size:
968
- mask_downsample = mask_downsample.repeat(batch_size, 1, 1)
969
-
970
- mask_downsample = mask_downsample.view(mask_downsample.shape[0], -1)
971
-
972
- downsampled_area = mask_h * mask_w
973
- # If the output image and the mask do not have the same aspect ratio, tensor shapes will not match
974
- # Pad tensor if downsampled_mask.shape[1] is smaller than num_queries
975
- if downsampled_area < num_queries:
976
- warnings.warn(
977
- "The aspect ratio of the mask does not match the aspect ratio of the output image. "
978
- "Please update your masks or adjust the output size for optimal performance.",
979
- UserWarning,
980
- )
981
- mask_downsample = F.pad(mask_downsample, (0, num_queries - mask_downsample.shape[1]), value=0.0)
982
- # Discard last embeddings if downsampled_mask.shape[1] is bigger than num_queries
983
- if downsampled_area > num_queries:
984
- warnings.warn(
985
- "The aspect ratio of the mask does not match the aspect ratio of the output image. "
986
- "Please update your masks or adjust the output size for optimal performance.",
987
- UserWarning,
988
- )
989
- mask_downsample = mask_downsample[:, :num_queries]
990
-
991
- # Repeat last dimension to match SDPA output shape
992
- mask_downsample = mask_downsample.view(mask_downsample.shape[0], mask_downsample.shape[1], 1).repeat(
993
- 1, 1, value_embed_dim
994
- )
995
-
996
- return mask_downsample
997
-
998
-
999
- class PixArtImageProcessor(VaeImageProcessor):
1000
- """
1001
- Image processor for PixArt image resize and crop.
1002
-
1003
- Args:
1004
- do_resize (`bool`, *optional*, defaults to `True`):
1005
- Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
1006
- `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
1007
- vae_scale_factor (`int`, *optional*, defaults to `8`):
1008
- VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
1009
- resample (`str`, *optional*, defaults to `lanczos`):
1010
- Resampling filter to use when resizing the image.
1011
- do_normalize (`bool`, *optional*, defaults to `True`):
1012
- Whether to normalize the image to [-1,1].
1013
- do_binarize (`bool`, *optional*, defaults to `False`):
1014
- Whether to binarize the image to 0/1.
1015
- do_convert_rgb (`bool`, *optional*, defaults to be `False`):
1016
- Whether to convert the images to RGB format.
1017
- do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
1018
- Whether to convert the images to grayscale format.
1019
- """
1020
-
1021
- @register_to_config
1022
- def __init__(
1023
- self,
1024
- do_resize: bool = True,
1025
- vae_scale_factor: int = 8,
1026
- resample: str = "lanczos",
1027
- do_normalize: bool = True,
1028
- do_binarize: bool = False,
1029
- do_convert_grayscale: bool = False,
1030
- ):
1031
- super().__init__(
1032
- do_resize=do_resize,
1033
- vae_scale_factor=vae_scale_factor,
1034
- resample=resample,
1035
- do_normalize=do_normalize,
1036
- do_binarize=do_binarize,
1037
- do_convert_grayscale=do_convert_grayscale,
1038
- )
1039
-
1040
- @staticmethod
1041
- def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
1042
- """Returns binned height and width."""
1043
- ar = float(height / width)
1044
- closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
1045
- default_hw = ratios[closest_ratio]
1046
- return int(default_hw[0]), int(default_hw[1])
1047
-
1048
- @staticmethod
1049
- def resize_and_crop_tensor(samples: torch.Tensor, new_width: int, new_height: int) -> torch.Tensor:
1050
- orig_height, orig_width = samples.shape[2], samples.shape[3]
1051
-
1052
- # Check if resizing is needed
1053
- if orig_height != new_height or orig_width != new_width:
1054
- ratio = max(new_height / orig_height, new_width / orig_width)
1055
- resized_width = int(orig_width * ratio)
1056
- resized_height = int(orig_height * ratio)
1057
-
1058
- # Resize
1059
- samples = F.interpolate(
1060
- samples, size=(resized_height, resized_width), mode="bilinear", align_corners=False
1061
- )
1062
-
1063
- # Center Crop
1064
- start_x = (resized_width - new_width) // 2
1065
- end_x = start_x + new_width
1066
- start_y = (resized_height - new_height) // 2
1067
- end_y = start_y + new_height
1068
- samples = samples[:, :, start_y:end_y, start_x:end_x]
1069
-
1070
- return samples
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/__init__.py DELETED
@@ -1,88 +0,0 @@
1
- from typing import TYPE_CHECKING
2
-
3
- from ..utils import DIFFUSERS_SLOW_IMPORT, _LazyModule, deprecate
4
- from ..utils.import_utils import is_peft_available, 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["autoencoder"] = ["FromOriginalVAEMixin"]
58
-
59
- _import_structure["controlnet"] = ["FromOriginalControlNetMixin"]
60
- _import_structure["unet"] = ["UNet2DConditionLoadersMixin"]
61
- _import_structure["utils"] = ["AttnProcsLayers"]
62
- if is_transformers_available():
63
- _import_structure["single_file"] = ["FromSingleFileMixin"]
64
- _import_structure["lora"] = ["LoraLoaderMixin", "StableDiffusionXLLoraLoaderMixin"]
65
- _import_structure["textual_inversion"] = ["TextualInversionLoaderMixin"]
66
- _import_structure["ip_adapter"] = ["IPAdapterMixin"]
67
-
68
- _import_structure["peft"] = ["PeftAdapterMixin"]
69
-
70
-
71
- if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
72
- if is_torch_available():
73
- from .autoencoder import FromOriginalVAEMixin
74
- from .controlnet import FromOriginalControlNetMixin
75
- from .unet import UNet2DConditionLoadersMixin
76
- from .utils import AttnProcsLayers
77
-
78
- if is_transformers_available():
79
- from .ip_adapter import IPAdapterMixin
80
- from .lora import LoraLoaderMixin, StableDiffusionXLLoraLoaderMixin
81
- from .single_file import FromSingleFileMixin
82
- from .textual_inversion import TextualInversionLoaderMixin
83
-
84
- from .peft import PeftAdapterMixin
85
- else:
86
- import sys
87
-
88
- sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/autoencoder.py DELETED
@@ -1,146 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from huggingface_hub.utils import validate_hf_hub_args
16
-
17
- from .single_file_utils import (
18
- create_diffusers_vae_model_from_ldm,
19
- fetch_ldm_config_and_checkpoint,
20
- )
21
-
22
-
23
- class FromOriginalVAEMixin:
24
- """
25
- Load pretrained AutoencoderKL weights saved in the `.ckpt` or `.safetensors` format into a [`AutoencoderKL`].
26
- """
27
-
28
- @classmethod
29
- @validate_hf_hub_args
30
- def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
- r"""
32
- Instantiate a [`AutoencoderKL`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
- `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
-
35
- Parameters:
36
- pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
- Can be either:
38
- - A link to the `.ckpt` file (for example
39
- `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
- - A path to a *file* containing all pipeline weights.
41
- config_file (`str`, *optional*):
42
- Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
- https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml
44
- torch_dtype (`str` or `torch.dtype`, *optional*):
45
- Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
- dtype is automatically derived from the model's weights.
47
- force_download (`bool`, *optional*, defaults to `False`):
48
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
- cached versions if they exist.
50
- cache_dir (`Union[str, os.PathLike]`, *optional*):
51
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
- is not used.
53
- resume_download:
54
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
55
- of Diffusers.
56
- proxies (`Dict[str, str]`, *optional*):
57
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
- local_files_only (`bool`, *optional*, defaults to `False`):
60
- Whether to only load local model weights and configuration files or not. If set to True, the model
61
- won't be downloaded from the Hub.
62
- token (`str` or *bool*, *optional*):
63
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
- revision (`str`, *optional*, defaults to `"main"`):
66
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
- allowed by Git.
68
- image_size (`int`, *optional*, defaults to 512):
69
- The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
- Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
- scaling_factor (`float`, *optional*, defaults to 0.18215):
72
- The component-wise standard deviation of the trained latent space computed using the first batch of the
73
- training set. This is used to scale the latent space to have unit variance when training the diffusion
74
- model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
75
- diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z
76
- = 1 / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution
77
- Image Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
78
- kwargs (remaining dictionary of keyword arguments, *optional*):
79
- Can be used to overwrite load and saveable variables (for example the pipeline components of the
80
- specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
81
- method. See example below for more information.
82
-
83
- <Tip warning={true}>
84
-
85
- Make sure to pass both `image_size` and `scaling_factor` to `from_single_file()` if you're loading
86
- a VAE from SDXL or a Stable Diffusion v2 model or higher.
87
-
88
- </Tip>
89
-
90
- Examples:
91
-
92
- ```py
93
- from diffusers import AutoencoderKL
94
-
95
- url = "https://huggingface.co/stabilityai/sd-vae-ft-mse-original/blob/main/vae-ft-mse-840000-ema-pruned.safetensors" # can also be local file
96
- model = AutoencoderKL.from_single_file(url)
97
- ```
98
- """
99
-
100
- original_config_file = kwargs.pop("original_config_file", None)
101
- config_file = kwargs.pop("config_file", None)
102
- resume_download = kwargs.pop("resume_download", None)
103
- force_download = kwargs.pop("force_download", False)
104
- proxies = kwargs.pop("proxies", None)
105
- token = kwargs.pop("token", None)
106
- cache_dir = kwargs.pop("cache_dir", None)
107
- local_files_only = kwargs.pop("local_files_only", None)
108
- revision = kwargs.pop("revision", None)
109
- torch_dtype = kwargs.pop("torch_dtype", None)
110
-
111
- class_name = cls.__name__
112
-
113
- if (config_file is not None) and (original_config_file is not None):
114
- raise ValueError(
115
- "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
116
- )
117
-
118
- original_config_file = original_config_file or config_file
119
- original_config, checkpoint = fetch_ldm_config_and_checkpoint(
120
- pretrained_model_link_or_path=pretrained_model_link_or_path,
121
- class_name=class_name,
122
- original_config_file=original_config_file,
123
- resume_download=resume_download,
124
- force_download=force_download,
125
- proxies=proxies,
126
- token=token,
127
- revision=revision,
128
- local_files_only=local_files_only,
129
- cache_dir=cache_dir,
130
- )
131
-
132
- image_size = kwargs.pop("image_size", None)
133
- scaling_factor = kwargs.pop("scaling_factor", None)
134
- component = create_diffusers_vae_model_from_ldm(
135
- class_name,
136
- original_config,
137
- checkpoint,
138
- image_size=image_size,
139
- scaling_factor=scaling_factor,
140
- torch_dtype=torch_dtype,
141
- )
142
- vae = component["vae"]
143
- if torch_dtype is not None:
144
- vae = vae.to(torch_dtype)
145
-
146
- return vae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/controlnet.py DELETED
@@ -1,136 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from huggingface_hub.utils import validate_hf_hub_args
16
-
17
- from .single_file_utils import (
18
- create_diffusers_controlnet_model_from_ldm,
19
- fetch_ldm_config_and_checkpoint,
20
- )
21
-
22
-
23
- class FromOriginalControlNetMixin:
24
- """
25
- Load pretrained ControlNet weights saved in the `.ckpt` or `.safetensors` format into a [`ControlNetModel`].
26
- """
27
-
28
- @classmethod
29
- @validate_hf_hub_args
30
- def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
31
- r"""
32
- Instantiate a [`ControlNetModel`] from pretrained ControlNet weights saved in the original `.ckpt` or
33
- `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
34
-
35
- Parameters:
36
- pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
37
- Can be either:
38
- - A link to the `.ckpt` file (for example
39
- `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
40
- - A path to a *file* containing all pipeline weights.
41
- config_file (`str`, *optional*):
42
- Filepath to the configuration YAML file associated with the model. If not provided it will default to:
43
- https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml
44
- torch_dtype (`str` or `torch.dtype`, *optional*):
45
- Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
46
- dtype is automatically derived from the model's weights.
47
- force_download (`bool`, *optional*, defaults to `False`):
48
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
49
- cached versions if they exist.
50
- cache_dir (`Union[str, os.PathLike]`, *optional*):
51
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
52
- is not used.
53
- resume_download:
54
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
55
- of Diffusers.
56
- proxies (`Dict[str, str]`, *optional*):
57
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
58
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
59
- local_files_only (`bool`, *optional*, defaults to `False`):
60
- Whether to only load local model weights and configuration files or not. If set to True, the model
61
- won't be downloaded from the Hub.
62
- token (`str` or *bool*, *optional*):
63
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
64
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
65
- revision (`str`, *optional*, defaults to `"main"`):
66
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
67
- allowed by Git.
68
- image_size (`int`, *optional*, defaults to 512):
69
- The image size the model was trained on. Use 512 for all Stable Diffusion v1 models and the Stable
70
- Diffusion v2 base model. Use 768 for Stable Diffusion v2.
71
- upcast_attention (`bool`, *optional*, defaults to `None`):
72
- Whether the attention computation should always be upcasted.
73
- kwargs (remaining dictionary of keyword arguments, *optional*):
74
- Can be used to overwrite load and saveable variables (for example the pipeline components of the
75
- specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
76
- method. See example below for more information.
77
-
78
- Examples:
79
-
80
- ```py
81
- from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
82
-
83
- url = "https://huggingface.co/lllyasviel/ControlNet-v1-1/blob/main/control_v11p_sd15_canny.pth" # can also be a local path
84
- model = ControlNetModel.from_single_file(url)
85
-
86
- url = "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned.safetensors" # can also be a local path
87
- pipe = StableDiffusionControlNetPipeline.from_single_file(url, controlnet=controlnet)
88
- ```
89
- """
90
- original_config_file = kwargs.pop("original_config_file", None)
91
- config_file = kwargs.pop("config_file", None)
92
- resume_download = kwargs.pop("resume_download", None)
93
- force_download = kwargs.pop("force_download", False)
94
- proxies = kwargs.pop("proxies", None)
95
- token = kwargs.pop("token", None)
96
- cache_dir = kwargs.pop("cache_dir", None)
97
- local_files_only = kwargs.pop("local_files_only", None)
98
- revision = kwargs.pop("revision", None)
99
- torch_dtype = kwargs.pop("torch_dtype", None)
100
-
101
- class_name = cls.__name__
102
- if (config_file is not None) and (original_config_file is not None):
103
- raise ValueError(
104
- "You cannot pass both `config_file` and `original_config_file` to `from_single_file`. Please use only one of these arguments."
105
- )
106
-
107
- original_config_file = config_file or original_config_file
108
- original_config, checkpoint = fetch_ldm_config_and_checkpoint(
109
- pretrained_model_link_or_path=pretrained_model_link_or_path,
110
- class_name=class_name,
111
- original_config_file=original_config_file,
112
- resume_download=resume_download,
113
- force_download=force_download,
114
- proxies=proxies,
115
- token=token,
116
- revision=revision,
117
- local_files_only=local_files_only,
118
- cache_dir=cache_dir,
119
- )
120
-
121
- upcast_attention = kwargs.pop("upcast_attention", False)
122
- image_size = kwargs.pop("image_size", None)
123
-
124
- component = create_diffusers_controlnet_model_from_ldm(
125
- class_name,
126
- original_config,
127
- checkpoint,
128
- upcast_attention=upcast_attention,
129
- image_size=image_size,
130
- torch_dtype=torch_dtype,
131
- )
132
- controlnet = component["controlnet"]
133
- if torch_dtype is not None:
134
- controlnet = controlnet.to(torch_dtype)
135
-
136
- return controlnet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/ip_adapter.py DELETED
@@ -1,339 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from pathlib import Path
16
- from typing import Dict, List, Optional, Union
17
-
18
- import torch
19
- import torch.nn.functional as F
20
- from huggingface_hub.utils import validate_hf_hub_args
21
- from safetensors import safe_open
22
-
23
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_state_dict
24
- from ..utils import (
25
- USE_PEFT_BACKEND,
26
- _get_model_file,
27
- is_accelerate_available,
28
- is_torch_version,
29
- is_transformers_available,
30
- logging,
31
- )
32
- from .unet_loader_utils import _maybe_expand_lora_scales
33
-
34
-
35
- if is_transformers_available():
36
- from transformers import (
37
- CLIPImageProcessor,
38
- CLIPVisionModelWithProjection,
39
- )
40
-
41
- from ..models.attention_processor import (
42
- AttnProcessor,
43
- AttnProcessor2_0,
44
- IPAdapterAttnProcessor,
45
- IPAdapterAttnProcessor2_0,
46
- )
47
-
48
- logger = logging.get_logger(__name__)
49
-
50
-
51
- class IPAdapterMixin:
52
- """Mixin for handling IP Adapters."""
53
-
54
- @validate_hf_hub_args
55
- def load_ip_adapter(
56
- self,
57
- pretrained_model_name_or_path_or_dict: Union[str, List[str], Dict[str, torch.Tensor]],
58
- subfolder: Union[str, List[str]],
59
- weight_name: Union[str, List[str]],
60
- image_encoder_folder: Optional[str] = "image_encoder",
61
- **kwargs,
62
- ):
63
- """
64
- Parameters:
65
- pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
66
- Can be either:
67
-
68
- - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
69
- the Hub.
70
- - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
71
- with [`ModelMixin.save_pretrained`].
72
- - A [torch state
73
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
74
- subfolder (`str` or `List[str]`):
75
- The subfolder location of a model file within a larger model repository on the Hub or locally. If a
76
- list is passed, it should have the same length as `weight_name`.
77
- weight_name (`str` or `List[str]`):
78
- The name of the weight file to load. If a list is passed, it should have the same length as
79
- `weight_name`.
80
- image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
81
- The subfolder location of the image encoder within a larger model repository on the Hub or locally.
82
- Pass `None` to not load the image encoder. If the image encoder is located in a folder inside
83
- `subfolder`, you only need to pass the name of the folder that contains image encoder weights, e.g.
84
- `image_encoder_folder="image_encoder"`. If the image encoder is located in a folder other than
85
- `subfolder`, you should pass the path to the folder that contains image encoder weights, for example,
86
- `image_encoder_folder="different_subfolder/image_encoder"`.
87
- cache_dir (`Union[str, os.PathLike]`, *optional*):
88
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
89
- is not used.
90
- force_download (`bool`, *optional*, defaults to `False`):
91
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
92
- cached versions if they exist.
93
- resume_download:
94
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
95
- of Diffusers.
96
- proxies (`Dict[str, str]`, *optional*):
97
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
98
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
99
- local_files_only (`bool`, *optional*, defaults to `False`):
100
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
101
- won't be downloaded from the Hub.
102
- token (`str` or *bool*, *optional*):
103
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
104
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
105
- revision (`str`, *optional*, defaults to `"main"`):
106
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
107
- allowed by Git.
108
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
109
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
110
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
111
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
112
- argument to `True` will raise an error.
113
- """
114
-
115
- # handle the list inputs for multiple IP Adapters
116
- if not isinstance(weight_name, list):
117
- weight_name = [weight_name]
118
-
119
- if not isinstance(pretrained_model_name_or_path_or_dict, list):
120
- pretrained_model_name_or_path_or_dict = [pretrained_model_name_or_path_or_dict]
121
- if len(pretrained_model_name_or_path_or_dict) == 1:
122
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict * len(weight_name)
123
-
124
- if not isinstance(subfolder, list):
125
- subfolder = [subfolder]
126
- if len(subfolder) == 1:
127
- subfolder = subfolder * len(weight_name)
128
-
129
- if len(weight_name) != len(pretrained_model_name_or_path_or_dict):
130
- raise ValueError("`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.")
131
-
132
- if len(weight_name) != len(subfolder):
133
- raise ValueError("`weight_name` and `subfolder` must have the same length.")
134
-
135
- # Load the main state dict first.
136
- cache_dir = kwargs.pop("cache_dir", None)
137
- force_download = kwargs.pop("force_download", False)
138
- resume_download = kwargs.pop("resume_download", None)
139
- proxies = kwargs.pop("proxies", None)
140
- local_files_only = kwargs.pop("local_files_only", None)
141
- token = kwargs.pop("token", None)
142
- revision = kwargs.pop("revision", None)
143
- low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
144
-
145
- if low_cpu_mem_usage and not is_accelerate_available():
146
- low_cpu_mem_usage = False
147
- logger.warning(
148
- "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
149
- " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
150
- " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
151
- " install accelerate\n```\n."
152
- )
153
-
154
- if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
155
- raise NotImplementedError(
156
- "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
157
- " `low_cpu_mem_usage=False`."
158
- )
159
-
160
- user_agent = {
161
- "file_type": "attn_procs_weights",
162
- "framework": "pytorch",
163
- }
164
- state_dicts = []
165
- for pretrained_model_name_or_path_or_dict, weight_name, subfolder in zip(
166
- pretrained_model_name_or_path_or_dict, weight_name, subfolder
167
- ):
168
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
169
- model_file = _get_model_file(
170
- pretrained_model_name_or_path_or_dict,
171
- weights_name=weight_name,
172
- cache_dir=cache_dir,
173
- force_download=force_download,
174
- resume_download=resume_download,
175
- proxies=proxies,
176
- local_files_only=local_files_only,
177
- token=token,
178
- revision=revision,
179
- subfolder=subfolder,
180
- user_agent=user_agent,
181
- )
182
- if weight_name.endswith(".safetensors"):
183
- state_dict = {"image_proj": {}, "ip_adapter": {}}
184
- with safe_open(model_file, framework="pt", device="cpu") as f:
185
- for key in f.keys():
186
- if key.startswith("image_proj."):
187
- state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
188
- elif key.startswith("ip_adapter."):
189
- state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
190
- else:
191
- state_dict = load_state_dict(model_file)
192
- else:
193
- state_dict = pretrained_model_name_or_path_or_dict
194
-
195
- keys = list(state_dict.keys())
196
- if keys != ["image_proj", "ip_adapter"]:
197
- raise ValueError("Required keys are (`image_proj` and `ip_adapter`) missing from the state dict.")
198
-
199
- state_dicts.append(state_dict)
200
-
201
- # load CLIP image encoder here if it has not been registered to the pipeline yet
202
- if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is None:
203
- if image_encoder_folder is not None:
204
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
205
- logger.info(f"loading image_encoder from {pretrained_model_name_or_path_or_dict}")
206
- if image_encoder_folder.count("/") == 0:
207
- image_encoder_subfolder = Path(subfolder, image_encoder_folder).as_posix()
208
- else:
209
- image_encoder_subfolder = Path(image_encoder_folder).as_posix()
210
-
211
- image_encoder = CLIPVisionModelWithProjection.from_pretrained(
212
- pretrained_model_name_or_path_or_dict,
213
- subfolder=image_encoder_subfolder,
214
- low_cpu_mem_usage=low_cpu_mem_usage,
215
- ).to(self.device, dtype=self.dtype)
216
- self.register_modules(image_encoder=image_encoder)
217
- else:
218
- raise ValueError(
219
- "`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict."
220
- )
221
- else:
222
- logger.warning(
223
- "image_encoder is not loaded since `image_encoder_folder=None` passed. You will not be able to use `ip_adapter_image` when calling the pipeline with IP-Adapter."
224
- "Use `ip_adapter_image_embeds` to pass pre-generated image embedding instead."
225
- )
226
-
227
- # create feature extractor if it has not been registered to the pipeline yet
228
- if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is None:
229
- feature_extractor = CLIPImageProcessor()
230
- self.register_modules(feature_extractor=feature_extractor)
231
-
232
- # load ip-adapter into unet
233
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
234
- unet._load_ip_adapter_weights(state_dicts, low_cpu_mem_usage=low_cpu_mem_usage)
235
-
236
- extra_loras = unet._load_ip_adapter_loras(state_dicts)
237
- if extra_loras != {}:
238
- if not USE_PEFT_BACKEND:
239
- logger.warning("PEFT backend is required to load these weights.")
240
- else:
241
- # apply the IP Adapter Face ID LoRA weights
242
- peft_config = getattr(unet, "peft_config", {})
243
- for k, lora in extra_loras.items():
244
- if f"faceid_{k}" not in peft_config:
245
- self.load_lora_weights(lora, adapter_name=f"faceid_{k}")
246
- self.set_adapters([f"faceid_{k}"], adapter_weights=[1.0])
247
-
248
- def set_ip_adapter_scale(self, scale):
249
- """
250
- Set IP-Adapter scales per-transformer block. Input `scale` could be a single config or a list of configs for
251
- granular control over each IP-Adapter behavior. A config can be a float or a dictionary.
252
-
253
- Example:
254
-
255
- ```py
256
- # To use original IP-Adapter
257
- scale = 1.0
258
- pipeline.set_ip_adapter_scale(scale)
259
-
260
- # To use style block only
261
- scale = {
262
- "up": {"block_0": [0.0, 1.0, 0.0]},
263
- }
264
- pipeline.set_ip_adapter_scale(scale)
265
-
266
- # To use style+layout blocks
267
- scale = {
268
- "down": {"block_2": [0.0, 1.0]},
269
- "up": {"block_0": [0.0, 1.0, 0.0]},
270
- }
271
- pipeline.set_ip_adapter_scale(scale)
272
-
273
- # To use style and layout from 2 reference images
274
- scales = [{"down": {"block_2": [0.0, 1.0]}}, {"up": {"block_0": [0.0, 1.0, 0.0]}}]
275
- pipeline.set_ip_adapter_scale(scales)
276
- ```
277
- """
278
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
279
- if not isinstance(scale, list):
280
- scale = [scale]
281
- scale_configs = _maybe_expand_lora_scales(unet, scale, default_scale=0.0)
282
-
283
- for attn_name, attn_processor in unet.attn_processors.items():
284
- if isinstance(attn_processor, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0)):
285
- if len(scale_configs) != len(attn_processor.scale):
286
- raise ValueError(
287
- f"Cannot assign {len(scale_configs)} scale_configs to "
288
- f"{len(attn_processor.scale)} IP-Adapter."
289
- )
290
- elif len(scale_configs) == 1:
291
- scale_configs = scale_configs * len(attn_processor.scale)
292
- for i, scale_config in enumerate(scale_configs):
293
- if isinstance(scale_config, dict):
294
- for k, s in scale_config.items():
295
- if attn_name.startswith(k):
296
- attn_processor.scale[i] = s
297
- else:
298
- attn_processor.scale[i] = scale_config
299
-
300
- def unload_ip_adapter(self):
301
- """
302
- Unloads the IP Adapter weights
303
-
304
- Examples:
305
-
306
- ```python
307
- >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
308
- >>> pipeline.unload_ip_adapter()
309
- >>> ...
310
- ```
311
- """
312
- # remove CLIP image encoder
313
- if hasattr(self, "image_encoder") and getattr(self, "image_encoder", None) is not None:
314
- self.image_encoder = None
315
- self.register_to_config(image_encoder=[None, None])
316
-
317
- # remove feature extractor only when safety_checker is None as safety_checker uses
318
- # the feature_extractor later
319
- if not hasattr(self, "safety_checker"):
320
- if hasattr(self, "feature_extractor") and getattr(self, "feature_extractor", None) is not None:
321
- self.feature_extractor = None
322
- self.register_to_config(feature_extractor=[None, None])
323
-
324
- # remove hidden encoder
325
- self.unet.encoder_hid_proj = None
326
- self.config.encoder_hid_dim_type = None
327
-
328
- # restore original Unet attention processors layers
329
- attn_procs = {}
330
- for name, value in self.unet.attn_processors.items():
331
- attn_processor_class = (
332
- AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnProcessor()
333
- )
334
- attn_procs[name] = (
335
- attn_processor_class
336
- if isinstance(value, (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0))
337
- else value.__class__()
338
- )
339
- self.unet.set_attn_processor(attn_procs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/lora.py DELETED
@@ -1,1458 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import copy
15
- import inspect
16
- import os
17
- from pathlib import Path
18
- from typing import Callable, Dict, List, Optional, Union
19
-
20
- import safetensors
21
- import torch
22
- from huggingface_hub import model_info
23
- from huggingface_hub.constants import HF_HUB_OFFLINE
24
- from huggingface_hub.utils import validate_hf_hub_args
25
- from packaging import version
26
- from torch import nn
27
-
28
- from .. import __version__
29
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_state_dict
30
- from ..utils import (
31
- USE_PEFT_BACKEND,
32
- _get_model_file,
33
- convert_state_dict_to_diffusers,
34
- convert_state_dict_to_peft,
35
- convert_unet_state_dict_to_peft,
36
- delete_adapter_layers,
37
- get_adapter_name,
38
- get_peft_kwargs,
39
- is_accelerate_available,
40
- is_peft_version,
41
- is_transformers_available,
42
- logging,
43
- recurse_remove_peft_layers,
44
- scale_lora_layers,
45
- set_adapter_layers,
46
- set_weights_and_activate_adapters,
47
- )
48
- from .lora_conversion_utils import _convert_kohya_lora_to_diffusers, _maybe_map_sgm_blocks_to_diffusers
49
-
50
-
51
- if is_transformers_available():
52
- from transformers import PreTrainedModel
53
-
54
- from ..models.lora import text_encoder_attn_modules, text_encoder_mlp_modules
55
-
56
- if is_accelerate_available():
57
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
58
-
59
- logger = logging.get_logger(__name__)
60
-
61
- TEXT_ENCODER_NAME = "text_encoder"
62
- UNET_NAME = "unet"
63
- TRANSFORMER_NAME = "transformer"
64
-
65
- LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
66
- LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
67
-
68
- LORA_DEPRECATION_MESSAGE = "You are using an old version of LoRA backend. This will be deprecated in the next releases in favor of PEFT make sure to install the latest PEFT and transformers packages in the future."
69
-
70
-
71
- class LoraLoaderMixin:
72
- r"""
73
- Load LoRA layers into [`UNet2DConditionModel`] and
74
- [`CLIPTextModel`](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel).
75
- """
76
-
77
- text_encoder_name = TEXT_ENCODER_NAME
78
- unet_name = UNET_NAME
79
- transformer_name = TRANSFORMER_NAME
80
- num_fused_loras = 0
81
-
82
- def load_lora_weights(
83
- self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], adapter_name=None, **kwargs
84
- ):
85
- """
86
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
87
- `self.text_encoder`.
88
-
89
- All kwargs are forwarded to `self.lora_state_dict`.
90
-
91
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
92
-
93
- See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
94
- `self.unet`.
95
-
96
- See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
97
- into `self.text_encoder`.
98
-
99
- Parameters:
100
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
101
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
102
- kwargs (`dict`, *optional*):
103
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
104
- adapter_name (`str`, *optional*):
105
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
106
- `default_{i}` where i is the total number of adapters being loaded.
107
- """
108
- if not USE_PEFT_BACKEND:
109
- raise ValueError("PEFT backend is required for this method.")
110
-
111
- # if a dict is passed, copy it instead of modifying it inplace
112
- if isinstance(pretrained_model_name_or_path_or_dict, dict):
113
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
114
-
115
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
116
- state_dict, network_alphas = self.lora_state_dict(pretrained_model_name_or_path_or_dict, **kwargs)
117
-
118
- is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
119
- if not is_correct_format:
120
- raise ValueError("Invalid LoRA checkpoint.")
121
-
122
- low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
123
-
124
- self.load_lora_into_unet(
125
- state_dict,
126
- network_alphas=network_alphas,
127
- unet=getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet,
128
- low_cpu_mem_usage=low_cpu_mem_usage,
129
- adapter_name=adapter_name,
130
- _pipeline=self,
131
- )
132
- self.load_lora_into_text_encoder(
133
- state_dict,
134
- network_alphas=network_alphas,
135
- text_encoder=getattr(self, self.text_encoder_name)
136
- if not hasattr(self, "text_encoder")
137
- else self.text_encoder,
138
- lora_scale=self.lora_scale,
139
- low_cpu_mem_usage=low_cpu_mem_usage,
140
- adapter_name=adapter_name,
141
- _pipeline=self,
142
- )
143
-
144
- @classmethod
145
- @validate_hf_hub_args
146
- def lora_state_dict(
147
- cls,
148
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
149
- **kwargs,
150
- ):
151
- r"""
152
- Return state dict for lora weights and the network alphas.
153
-
154
- <Tip warning={true}>
155
-
156
- We support loading A1111 formatted LoRA checkpoints in a limited capacity.
157
-
158
- This function is experimental and might change in the future.
159
-
160
- </Tip>
161
-
162
- Parameters:
163
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
164
- Can be either:
165
-
166
- - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
167
- the Hub.
168
- - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
169
- with [`ModelMixin.save_pretrained`].
170
- - A [torch state
171
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
172
-
173
- cache_dir (`Union[str, os.PathLike]`, *optional*):
174
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
175
- is not used.
176
- force_download (`bool`, *optional*, defaults to `False`):
177
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
178
- cached versions if they exist.
179
- resume_download:
180
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
181
- of Diffusers.
182
- proxies (`Dict[str, str]`, *optional*):
183
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
184
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
185
- local_files_only (`bool`, *optional*, defaults to `False`):
186
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
187
- won't be downloaded from the Hub.
188
- token (`str` or *bool*, *optional*):
189
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
190
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
191
- revision (`str`, *optional*, defaults to `"main"`):
192
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
193
- allowed by Git.
194
- subfolder (`str`, *optional*, defaults to `""`):
195
- The subfolder location of a model file within a larger model repository on the Hub or locally.
196
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
197
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
198
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
199
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
200
- argument to `True` will raise an error.
201
- mirror (`str`, *optional*):
202
- Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
203
- guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
204
- information.
205
-
206
- """
207
- # Load the main state dict first which has the LoRA layers for either of
208
- # UNet and text encoder or both.
209
- cache_dir = kwargs.pop("cache_dir", None)
210
- force_download = kwargs.pop("force_download", False)
211
- resume_download = kwargs.pop("resume_download", None)
212
- proxies = kwargs.pop("proxies", None)
213
- local_files_only = kwargs.pop("local_files_only", None)
214
- token = kwargs.pop("token", None)
215
- revision = kwargs.pop("revision", None)
216
- subfolder = kwargs.pop("subfolder", None)
217
- weight_name = kwargs.pop("weight_name", None)
218
- unet_config = kwargs.pop("unet_config", None)
219
- use_safetensors = kwargs.pop("use_safetensors", None)
220
-
221
- allow_pickle = False
222
- if use_safetensors is None:
223
- use_safetensors = True
224
- allow_pickle = True
225
-
226
- user_agent = {
227
- "file_type": "attn_procs_weights",
228
- "framework": "pytorch",
229
- }
230
-
231
- model_file = None
232
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
233
- # Let's first try to load .safetensors weights
234
- if (use_safetensors and weight_name is None) or (
235
- weight_name is not None and weight_name.endswith(".safetensors")
236
- ):
237
- try:
238
- # Here we're relaxing the loading check to enable more Inference API
239
- # friendliness where sometimes, it's not at all possible to automatically
240
- # determine `weight_name`.
241
- if weight_name is None:
242
- weight_name = cls._best_guess_weight_name(
243
- pretrained_model_name_or_path_or_dict,
244
- file_extension=".safetensors",
245
- local_files_only=local_files_only,
246
- )
247
- model_file = _get_model_file(
248
- pretrained_model_name_or_path_or_dict,
249
- weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
250
- cache_dir=cache_dir,
251
- force_download=force_download,
252
- resume_download=resume_download,
253
- proxies=proxies,
254
- local_files_only=local_files_only,
255
- token=token,
256
- revision=revision,
257
- subfolder=subfolder,
258
- user_agent=user_agent,
259
- )
260
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
261
- except (IOError, safetensors.SafetensorError) as e:
262
- if not allow_pickle:
263
- raise e
264
- # try loading non-safetensors weights
265
- model_file = None
266
- pass
267
-
268
- if model_file is None:
269
- if weight_name is None:
270
- weight_name = cls._best_guess_weight_name(
271
- pretrained_model_name_or_path_or_dict, file_extension=".bin", local_files_only=local_files_only
272
- )
273
- model_file = _get_model_file(
274
- pretrained_model_name_or_path_or_dict,
275
- weights_name=weight_name or LORA_WEIGHT_NAME,
276
- cache_dir=cache_dir,
277
- force_download=force_download,
278
- resume_download=resume_download,
279
- proxies=proxies,
280
- local_files_only=local_files_only,
281
- token=token,
282
- revision=revision,
283
- subfolder=subfolder,
284
- user_agent=user_agent,
285
- )
286
- state_dict = load_state_dict(model_file)
287
- else:
288
- state_dict = pretrained_model_name_or_path_or_dict
289
-
290
- network_alphas = None
291
- # TODO: replace it with a method from `state_dict_utils`
292
- if all(
293
- (
294
- k.startswith("lora_te_")
295
- or k.startswith("lora_unet_")
296
- or k.startswith("lora_te1_")
297
- or k.startswith("lora_te2_")
298
- )
299
- for k in state_dict.keys()
300
- ):
301
- # Map SDXL blocks correctly.
302
- if unet_config is not None:
303
- # use unet config to remap block numbers
304
- state_dict = _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config)
305
- state_dict, network_alphas = _convert_kohya_lora_to_diffusers(state_dict)
306
-
307
- return state_dict, network_alphas
308
-
309
- @classmethod
310
- def _best_guess_weight_name(
311
- cls, pretrained_model_name_or_path_or_dict, file_extension=".safetensors", local_files_only=False
312
- ):
313
- if local_files_only or HF_HUB_OFFLINE:
314
- raise ValueError("When using the offline mode, you must specify a `weight_name`.")
315
-
316
- targeted_files = []
317
-
318
- if os.path.isfile(pretrained_model_name_or_path_or_dict):
319
- return
320
- elif os.path.isdir(pretrained_model_name_or_path_or_dict):
321
- targeted_files = [
322
- f for f in os.listdir(pretrained_model_name_or_path_or_dict) if f.endswith(file_extension)
323
- ]
324
- else:
325
- files_in_repo = model_info(pretrained_model_name_or_path_or_dict).siblings
326
- targeted_files = [f.rfilename for f in files_in_repo if f.rfilename.endswith(file_extension)]
327
- if len(targeted_files) == 0:
328
- return
329
-
330
- # "scheduler" does not correspond to a LoRA checkpoint.
331
- # "optimizer" does not correspond to a LoRA checkpoint
332
- # only top-level checkpoints are considered and not the other ones, hence "checkpoint".
333
- unallowed_substrings = {"scheduler", "optimizer", "checkpoint"}
334
- targeted_files = list(
335
- filter(lambda x: all(substring not in x for substring in unallowed_substrings), targeted_files)
336
- )
337
-
338
- if any(f.endswith(LORA_WEIGHT_NAME) for f in targeted_files):
339
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME), targeted_files))
340
- elif any(f.endswith(LORA_WEIGHT_NAME_SAFE) for f in targeted_files):
341
- targeted_files = list(filter(lambda x: x.endswith(LORA_WEIGHT_NAME_SAFE), targeted_files))
342
-
343
- if len(targeted_files) > 1:
344
- raise ValueError(
345
- f"Provided path contains more than one weights file in the {file_extension} format. Either specify `weight_name` in `load_lora_weights` or make sure there's only one `.safetensors` or `.bin` file in {pretrained_model_name_or_path_or_dict}."
346
- )
347
- weight_name = targeted_files[0]
348
- return weight_name
349
-
350
- @classmethod
351
- def _optionally_disable_offloading(cls, _pipeline):
352
- """
353
- Optionally removes offloading in case the pipeline has been already sequentially offloaded to CPU.
354
-
355
- Args:
356
- _pipeline (`DiffusionPipeline`):
357
- The pipeline to disable offloading for.
358
-
359
- Returns:
360
- tuple:
361
- A tuple indicating if `is_model_cpu_offload` or `is_sequential_cpu_offload` is True.
362
- """
363
- is_model_cpu_offload = False
364
- is_sequential_cpu_offload = False
365
-
366
- if _pipeline is not None:
367
- for _, component in _pipeline.components.items():
368
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
369
- if not is_model_cpu_offload:
370
- is_model_cpu_offload = isinstance(component._hf_hook, CpuOffload)
371
- if not is_sequential_cpu_offload:
372
- is_sequential_cpu_offload = (
373
- isinstance(component._hf_hook, AlignDevicesHook)
374
- or hasattr(component._hf_hook, "hooks")
375
- and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
376
- )
377
-
378
- logger.info(
379
- "Accelerate hooks detected. Since you have called `load_lora_weights()`, the previous hooks will be first removed. Then the LoRA parameters will be loaded and the hooks will be applied again."
380
- )
381
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
382
-
383
- return (is_model_cpu_offload, is_sequential_cpu_offload)
384
-
385
- @classmethod
386
- def load_lora_into_unet(
387
- cls, state_dict, network_alphas, unet, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
388
- ):
389
- """
390
- This will load the LoRA layers specified in `state_dict` into `unet`.
391
-
392
- Parameters:
393
- state_dict (`dict`):
394
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
395
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
396
- encoder lora layers.
397
- network_alphas (`Dict[str, float]`):
398
- See `LoRALinearLayer` for more details.
399
- unet (`UNet2DConditionModel`):
400
- The UNet model to load the LoRA layers into.
401
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
402
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
403
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
404
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
405
- argument to `True` will raise an error.
406
- adapter_name (`str`, *optional*):
407
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
408
- `default_{i}` where i is the total number of adapters being loaded.
409
- """
410
- if not USE_PEFT_BACKEND:
411
- raise ValueError("PEFT backend is required for this method.")
412
-
413
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
414
-
415
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
416
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
417
- # then the `state_dict` keys should have `cls.unet_name` and/or `cls.text_encoder_name` as
418
- # their prefixes.
419
- keys = list(state_dict.keys())
420
-
421
- if all(key.startswith(cls.unet_name) or key.startswith(cls.text_encoder_name) for key in keys):
422
- # Load the layers corresponding to UNet.
423
- logger.info(f"Loading {cls.unet_name}.")
424
-
425
- unet_keys = [k for k in keys if k.startswith(cls.unet_name)]
426
- state_dict = {k.replace(f"{cls.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
427
-
428
- if network_alphas is not None:
429
- alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.unet_name)]
430
- network_alphas = {
431
- k.replace(f"{cls.unet_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
432
- }
433
-
434
- else:
435
- # Otherwise, we're dealing with the old format. This means the `state_dict` should only
436
- # contain the module names of the `unet` as its keys WITHOUT any prefix.
437
- if not USE_PEFT_BACKEND:
438
- warn_message = "You have saved the LoRA weights using the old format. To convert the old LoRA weights to the new format, you can first load them in a dictionary and then create a new dictionary like the following: `new_state_dict = {f'unet.{module_name}': params for module_name, params in old_state_dict.items()}`."
439
- logger.warning(warn_message)
440
-
441
- if len(state_dict.keys()) > 0:
442
- if adapter_name in getattr(unet, "peft_config", {}):
443
- raise ValueError(
444
- f"Adapter name {adapter_name} already in use in the Unet - please select a new adapter name."
445
- )
446
-
447
- state_dict = convert_unet_state_dict_to_peft(state_dict)
448
-
449
- if network_alphas is not None:
450
- # The alphas state dict have the same structure as Unet, thus we convert it to peft format using
451
- # `convert_unet_state_dict_to_peft` method.
452
- network_alphas = convert_unet_state_dict_to_peft(network_alphas)
453
-
454
- rank = {}
455
- for key, val in state_dict.items():
456
- if "lora_B" in key:
457
- rank[key] = val.shape[1]
458
-
459
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict, is_unet=True)
460
- if "use_dora" in lora_config_kwargs:
461
- if lora_config_kwargs["use_dora"]:
462
- if is_peft_version("<", "0.9.0"):
463
- raise ValueError(
464
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
465
- )
466
- else:
467
- if is_peft_version("<", "0.9.0"):
468
- lora_config_kwargs.pop("use_dora")
469
- lora_config = LoraConfig(**lora_config_kwargs)
470
-
471
- # adapter_name
472
- if adapter_name is None:
473
- adapter_name = get_adapter_name(unet)
474
-
475
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
476
- # otherwise loading LoRA weights will lead to an error
477
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
478
-
479
- inject_adapter_in_model(lora_config, unet, adapter_name=adapter_name)
480
- incompatible_keys = set_peft_model_state_dict(unet, state_dict, adapter_name)
481
-
482
- if incompatible_keys is not None:
483
- # check only for unexpected keys
484
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
485
- if unexpected_keys:
486
- logger.warning(
487
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
488
- f" {unexpected_keys}. "
489
- )
490
-
491
- # Offload back.
492
- if is_model_cpu_offload:
493
- _pipeline.enable_model_cpu_offload()
494
- elif is_sequential_cpu_offload:
495
- _pipeline.enable_sequential_cpu_offload()
496
- # Unsafe code />
497
-
498
- unet.load_attn_procs(
499
- state_dict, network_alphas=network_alphas, low_cpu_mem_usage=low_cpu_mem_usage, _pipeline=_pipeline
500
- )
501
-
502
- @classmethod
503
- def load_lora_into_text_encoder(
504
- cls,
505
- state_dict,
506
- network_alphas,
507
- text_encoder,
508
- prefix=None,
509
- lora_scale=1.0,
510
- low_cpu_mem_usage=None,
511
- adapter_name=None,
512
- _pipeline=None,
513
- ):
514
- """
515
- This will load the LoRA layers specified in `state_dict` into `text_encoder`
516
-
517
- Parameters:
518
- state_dict (`dict`):
519
- A standard state dict containing the lora layer parameters. The key should be prefixed with an
520
- additional `text_encoder` to distinguish between unet lora layers.
521
- network_alphas (`Dict[str, float]`):
522
- See `LoRALinearLayer` for more details.
523
- text_encoder (`CLIPTextModel`):
524
- The text encoder model to load the LoRA layers into.
525
- prefix (`str`):
526
- Expected prefix of the `text_encoder` in the `state_dict`.
527
- lora_scale (`float`):
528
- How much to scale the output of the lora linear layer before it is added with the output of the regular
529
- lora layer.
530
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
531
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
532
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
533
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
534
- argument to `True` will raise an error.
535
- adapter_name (`str`, *optional*):
536
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
537
- `default_{i}` where i is the total number of adapters being loaded.
538
- """
539
- if not USE_PEFT_BACKEND:
540
- raise ValueError("PEFT backend is required for this method.")
541
-
542
- from peft import LoraConfig
543
-
544
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
545
-
546
- # If the serialization format is new (introduced in https://github.com/huggingface/diffusers/pull/2918),
547
- # then the `state_dict` keys should have `self.unet_name` and/or `self.text_encoder_name` as
548
- # their prefixes.
549
- keys = list(state_dict.keys())
550
- prefix = cls.text_encoder_name if prefix is None else prefix
551
-
552
- # Safe prefix to check with.
553
- if any(cls.text_encoder_name in key for key in keys):
554
- # Load the layers corresponding to text encoder and make necessary adjustments.
555
- text_encoder_keys = [k for k in keys if k.startswith(prefix) and k.split(".")[0] == prefix]
556
- text_encoder_lora_state_dict = {
557
- k.replace(f"{prefix}.", ""): v for k, v in state_dict.items() if k in text_encoder_keys
558
- }
559
-
560
- if len(text_encoder_lora_state_dict) > 0:
561
- logger.info(f"Loading {prefix}.")
562
- rank = {}
563
- text_encoder_lora_state_dict = convert_state_dict_to_diffusers(text_encoder_lora_state_dict)
564
-
565
- # convert state dict
566
- text_encoder_lora_state_dict = convert_state_dict_to_peft(text_encoder_lora_state_dict)
567
-
568
- for name, _ in text_encoder_attn_modules(text_encoder):
569
- rank_key = f"{name}.out_proj.lora_B.weight"
570
- rank[rank_key] = text_encoder_lora_state_dict[rank_key].shape[1]
571
-
572
- patch_mlp = any(".mlp." in key for key in text_encoder_lora_state_dict.keys())
573
- if patch_mlp:
574
- for name, _ in text_encoder_mlp_modules(text_encoder):
575
- rank_key_fc1 = f"{name}.fc1.lora_B.weight"
576
- rank_key_fc2 = f"{name}.fc2.lora_B.weight"
577
-
578
- rank[rank_key_fc1] = text_encoder_lora_state_dict[rank_key_fc1].shape[1]
579
- rank[rank_key_fc2] = text_encoder_lora_state_dict[rank_key_fc2].shape[1]
580
-
581
- if network_alphas is not None:
582
- alpha_keys = [
583
- k for k in network_alphas.keys() if k.startswith(prefix) and k.split(".")[0] == prefix
584
- ]
585
- network_alphas = {
586
- k.replace(f"{prefix}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
587
- }
588
-
589
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, text_encoder_lora_state_dict, is_unet=False)
590
- if "use_dora" in lora_config_kwargs:
591
- if lora_config_kwargs["use_dora"]:
592
- if is_peft_version("<", "0.9.0"):
593
- raise ValueError(
594
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
595
- )
596
- else:
597
- if is_peft_version("<", "0.9.0"):
598
- lora_config_kwargs.pop("use_dora")
599
- lora_config = LoraConfig(**lora_config_kwargs)
600
-
601
- # adapter_name
602
- if adapter_name is None:
603
- adapter_name = get_adapter_name(text_encoder)
604
-
605
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
606
-
607
- # inject LoRA layers and load the state dict
608
- # in transformers we automatically check whether the adapter name is already in use or not
609
- text_encoder.load_adapter(
610
- adapter_name=adapter_name,
611
- adapter_state_dict=text_encoder_lora_state_dict,
612
- peft_config=lora_config,
613
- )
614
-
615
- # scale LoRA layers with `lora_scale`
616
- scale_lora_layers(text_encoder, weight=lora_scale)
617
-
618
- text_encoder.to(device=text_encoder.device, dtype=text_encoder.dtype)
619
-
620
- # Offload back.
621
- if is_model_cpu_offload:
622
- _pipeline.enable_model_cpu_offload()
623
- elif is_sequential_cpu_offload:
624
- _pipeline.enable_sequential_cpu_offload()
625
- # Unsafe code />
626
-
627
- @classmethod
628
- def load_lora_into_transformer(
629
- cls, state_dict, network_alphas, transformer, low_cpu_mem_usage=None, adapter_name=None, _pipeline=None
630
- ):
631
- """
632
- This will load the LoRA layers specified in `state_dict` into `transformer`.
633
-
634
- Parameters:
635
- state_dict (`dict`):
636
- A standard state dict containing the lora layer parameters. The keys can either be indexed directly
637
- into the unet or prefixed with an additional `unet` which can be used to distinguish between text
638
- encoder lora layers.
639
- network_alphas (`Dict[str, float]`):
640
- See `LoRALinearLayer` for more details.
641
- unet (`UNet2DConditionModel`):
642
- The UNet model to load the LoRA layers into.
643
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
644
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
645
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
646
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
647
- argument to `True` will raise an error.
648
- adapter_name (`str`, *optional*):
649
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
650
- `default_{i}` where i is the total number of adapters being loaded.
651
- """
652
- from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
653
-
654
- low_cpu_mem_usage = low_cpu_mem_usage if low_cpu_mem_usage is not None else _LOW_CPU_MEM_USAGE_DEFAULT
655
-
656
- keys = list(state_dict.keys())
657
-
658
- transformer_keys = [k for k in keys if k.startswith(cls.transformer_name)]
659
- state_dict = {
660
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in state_dict.items() if k in transformer_keys
661
- }
662
-
663
- if network_alphas is not None:
664
- alpha_keys = [k for k in network_alphas.keys() if k.startswith(cls.transformer_name)]
665
- network_alphas = {
666
- k.replace(f"{cls.transformer_name}.", ""): v for k, v in network_alphas.items() if k in alpha_keys
667
- }
668
-
669
- if len(state_dict.keys()) > 0:
670
- if adapter_name in getattr(transformer, "peft_config", {}):
671
- raise ValueError(
672
- f"Adapter name {adapter_name} already in use in the transformer - please select a new adapter name."
673
- )
674
-
675
- rank = {}
676
- for key, val in state_dict.items():
677
- if "lora_B" in key:
678
- rank[key] = val.shape[1]
679
-
680
- lora_config_kwargs = get_peft_kwargs(rank, network_alphas, state_dict)
681
- if "use_dora" in lora_config_kwargs:
682
- if lora_config_kwargs["use_dora"] and is_peft_version("<", "0.9.0"):
683
- raise ValueError(
684
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
685
- )
686
- else:
687
- lora_config_kwargs.pop("use_dora")
688
- lora_config = LoraConfig(**lora_config_kwargs)
689
-
690
- # adapter_name
691
- if adapter_name is None:
692
- adapter_name = get_adapter_name(transformer)
693
-
694
- # In case the pipeline has been already offloaded to CPU - temporarily remove the hooks
695
- # otherwise loading LoRA weights will lead to an error
696
- is_model_cpu_offload, is_sequential_cpu_offload = cls._optionally_disable_offloading(_pipeline)
697
-
698
- inject_adapter_in_model(lora_config, transformer, adapter_name=adapter_name)
699
- incompatible_keys = set_peft_model_state_dict(transformer, state_dict, adapter_name)
700
-
701
- if incompatible_keys is not None:
702
- # check only for unexpected keys
703
- unexpected_keys = getattr(incompatible_keys, "unexpected_keys", None)
704
- if unexpected_keys:
705
- logger.warning(
706
- f"Loading adapter weights from state_dict led to unexpected keys not found in the model: "
707
- f" {unexpected_keys}. "
708
- )
709
-
710
- # Offload back.
711
- if is_model_cpu_offload:
712
- _pipeline.enable_model_cpu_offload()
713
- elif is_sequential_cpu_offload:
714
- _pipeline.enable_sequential_cpu_offload()
715
- # Unsafe code />
716
-
717
- @property
718
- def lora_scale(self) -> float:
719
- # property function that returns the lora scale which can be set at run time by the pipeline.
720
- # if _lora_scale has not been set, return 1
721
- return self._lora_scale if hasattr(self, "_lora_scale") else 1.0
722
-
723
- def _remove_text_encoder_monkey_patch(self):
724
- remove_method = recurse_remove_peft_layers
725
- if hasattr(self, "text_encoder"):
726
- remove_method(self.text_encoder)
727
- # In case text encoder have no Lora attached
728
- if getattr(self.text_encoder, "peft_config", None) is not None:
729
- del self.text_encoder.peft_config
730
- self.text_encoder._hf_peft_config_loaded = None
731
-
732
- if hasattr(self, "text_encoder_2"):
733
- remove_method(self.text_encoder_2)
734
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
735
- del self.text_encoder_2.peft_config
736
- self.text_encoder_2._hf_peft_config_loaded = None
737
-
738
- @classmethod
739
- def save_lora_weights(
740
- cls,
741
- save_directory: Union[str, os.PathLike],
742
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
743
- text_encoder_lora_layers: Dict[str, torch.nn.Module] = None,
744
- transformer_lora_layers: Dict[str, torch.nn.Module] = None,
745
- is_main_process: bool = True,
746
- weight_name: str = None,
747
- save_function: Callable = None,
748
- safe_serialization: bool = True,
749
- ):
750
- r"""
751
- Save the LoRA parameters corresponding to the UNet and text encoder.
752
-
753
- Arguments:
754
- save_directory (`str` or `os.PathLike`):
755
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
756
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
757
- State dict of the LoRA layers corresponding to the `unet`.
758
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
759
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
760
- encoder LoRA state dict because it comes from 🤗 Transformers.
761
- is_main_process (`bool`, *optional*, defaults to `True`):
762
- Whether the process calling this is the main process or not. Useful during distributed training and you
763
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
764
- process to avoid race conditions.
765
- save_function (`Callable`):
766
- The function to use to save the state dictionary. Useful during distributed training when you need to
767
- replace `torch.save` with another method. Can be configured with the environment variable
768
- `DIFFUSERS_SAVE_MODE`.
769
- safe_serialization (`bool`, *optional*, defaults to `True`):
770
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
771
- """
772
- state_dict = {}
773
-
774
- def pack_weights(layers, prefix):
775
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
776
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
777
- return layers_state_dict
778
-
779
- if not (unet_lora_layers or text_encoder_lora_layers or transformer_lora_layers):
780
- raise ValueError(
781
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers`, or `transformer_lora_layers`."
782
- )
783
-
784
- if unet_lora_layers:
785
- state_dict.update(pack_weights(unet_lora_layers, cls.unet_name))
786
-
787
- if text_encoder_lora_layers:
788
- state_dict.update(pack_weights(text_encoder_lora_layers, cls.text_encoder_name))
789
-
790
- if transformer_lora_layers:
791
- state_dict.update(pack_weights(transformer_lora_layers, "transformer"))
792
-
793
- # Save the model
794
- cls.write_lora_layers(
795
- state_dict=state_dict,
796
- save_directory=save_directory,
797
- is_main_process=is_main_process,
798
- weight_name=weight_name,
799
- save_function=save_function,
800
- safe_serialization=safe_serialization,
801
- )
802
-
803
- @staticmethod
804
- def write_lora_layers(
805
- state_dict: Dict[str, torch.Tensor],
806
- save_directory: str,
807
- is_main_process: bool,
808
- weight_name: str,
809
- save_function: Callable,
810
- safe_serialization: bool,
811
- ):
812
- if os.path.isfile(save_directory):
813
- logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
814
- return
815
-
816
- if save_function is None:
817
- if safe_serialization:
818
-
819
- def save_function(weights, filename):
820
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
821
-
822
- else:
823
- save_function = torch.save
824
-
825
- os.makedirs(save_directory, exist_ok=True)
826
-
827
- if weight_name is None:
828
- if safe_serialization:
829
- weight_name = LORA_WEIGHT_NAME_SAFE
830
- else:
831
- weight_name = LORA_WEIGHT_NAME
832
-
833
- save_path = Path(save_directory, weight_name).as_posix()
834
- save_function(state_dict, save_path)
835
- logger.info(f"Model weights saved in {save_path}")
836
-
837
- def unload_lora_weights(self):
838
- """
839
- Unloads the LoRA parameters.
840
-
841
- Examples:
842
-
843
- ```python
844
- >>> # Assuming `pipeline` is already loaded with the LoRA parameters.
845
- >>> pipeline.unload_lora_weights()
846
- >>> ...
847
- ```
848
- """
849
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
850
-
851
- if not USE_PEFT_BACKEND:
852
- if version.parse(__version__) > version.parse("0.23"):
853
- logger.warning(
854
- "You are using `unload_lora_weights` to disable and unload lora weights. If you want to iteratively enable and disable adapter weights,"
855
- "you can use `pipe.enable_lora()` or `pipe.disable_lora()`. After installing the latest version of PEFT."
856
- )
857
-
858
- for _, module in unet.named_modules():
859
- if hasattr(module, "set_lora_layer"):
860
- module.set_lora_layer(None)
861
- else:
862
- recurse_remove_peft_layers(unet)
863
- if hasattr(unet, "peft_config"):
864
- del unet.peft_config
865
-
866
- # Safe to call the following regardless of LoRA.
867
- self._remove_text_encoder_monkey_patch()
868
-
869
- def fuse_lora(
870
- self,
871
- fuse_unet: bool = True,
872
- fuse_text_encoder: bool = True,
873
- lora_scale: float = 1.0,
874
- safe_fusing: bool = False,
875
- adapter_names: Optional[List[str]] = None,
876
- ):
877
- r"""
878
- Fuses the LoRA parameters into the original parameters of the corresponding blocks.
879
-
880
- <Tip warning={true}>
881
-
882
- This is an experimental API.
883
-
884
- </Tip>
885
-
886
- Args:
887
- fuse_unet (`bool`, defaults to `True`): Whether to fuse the UNet LoRA parameters.
888
- fuse_text_encoder (`bool`, defaults to `True`):
889
- Whether to fuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
890
- LoRA parameters then it won't have any effect.
891
- lora_scale (`float`, defaults to 1.0):
892
- Controls how much to influence the outputs with the LoRA parameters.
893
- safe_fusing (`bool`, defaults to `False`):
894
- Whether to check fused weights for NaN values before fusing and if values are NaN not fusing them.
895
- adapter_names (`List[str]`, *optional*):
896
- Adapter names to be used for fusing. If nothing is passed, all active adapters will be fused.
897
-
898
- Example:
899
-
900
- ```py
901
- from diffusers import DiffusionPipeline
902
- import torch
903
-
904
- pipeline = DiffusionPipeline.from_pretrained(
905
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
906
- ).to("cuda")
907
- pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
908
- pipeline.fuse_lora(lora_scale=0.7)
909
- ```
910
- """
911
- from peft.tuners.tuners_utils import BaseTunerLayer
912
-
913
- if fuse_unet or fuse_text_encoder:
914
- self.num_fused_loras += 1
915
- if self.num_fused_loras > 1:
916
- logger.warning(
917
- "The current API is supported for operating with a single LoRA file. You are trying to load and fuse more than one LoRA which is not well-supported.",
918
- )
919
-
920
- if fuse_unet:
921
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
922
- unet.fuse_lora(lora_scale, safe_fusing=safe_fusing, adapter_names=adapter_names)
923
-
924
- def fuse_text_encoder_lora(text_encoder, lora_scale=1.0, safe_fusing=False, adapter_names=None):
925
- merge_kwargs = {"safe_merge": safe_fusing}
926
-
927
- for module in text_encoder.modules():
928
- if isinstance(module, BaseTunerLayer):
929
- if lora_scale != 1.0:
930
- module.scale_layer(lora_scale)
931
-
932
- # For BC with previous PEFT versions, we need to check the signature
933
- # of the `merge` method to see if it supports the `adapter_names` argument.
934
- supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
935
- if "adapter_names" in supported_merge_kwargs:
936
- merge_kwargs["adapter_names"] = adapter_names
937
- elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
938
- raise ValueError(
939
- "The `adapter_names` argument is not supported with your PEFT version. "
940
- "Please upgrade to the latest version of PEFT. `pip install -U peft`"
941
- )
942
-
943
- module.merge(**merge_kwargs)
944
-
945
- if fuse_text_encoder:
946
- if hasattr(self, "text_encoder"):
947
- fuse_text_encoder_lora(self.text_encoder, lora_scale, safe_fusing, adapter_names=adapter_names)
948
- if hasattr(self, "text_encoder_2"):
949
- fuse_text_encoder_lora(self.text_encoder_2, lora_scale, safe_fusing, adapter_names=adapter_names)
950
-
951
- def unfuse_lora(self, unfuse_unet: bool = True, unfuse_text_encoder: bool = True):
952
- r"""
953
- Reverses the effect of
954
- [`pipe.fuse_lora()`](https://huggingface.co/docs/diffusers/main/en/api/loaders#diffusers.loaders.LoraLoaderMixin.fuse_lora).
955
-
956
- <Tip warning={true}>
957
-
958
- This is an experimental API.
959
-
960
- </Tip>
961
-
962
- Args:
963
- unfuse_unet (`bool`, defaults to `True`): Whether to unfuse the UNet LoRA parameters.
964
- unfuse_text_encoder (`bool`, defaults to `True`):
965
- Whether to unfuse the text encoder LoRA parameters. If the text encoder wasn't monkey-patched with the
966
- LoRA parameters then it won't have any effect.
967
- """
968
- from peft.tuners.tuners_utils import BaseTunerLayer
969
-
970
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
971
- if unfuse_unet:
972
- for module in unet.modules():
973
- if isinstance(module, BaseTunerLayer):
974
- module.unmerge()
975
-
976
- def unfuse_text_encoder_lora(text_encoder):
977
- for module in text_encoder.modules():
978
- if isinstance(module, BaseTunerLayer):
979
- module.unmerge()
980
-
981
- if unfuse_text_encoder:
982
- if hasattr(self, "text_encoder"):
983
- unfuse_text_encoder_lora(self.text_encoder)
984
- if hasattr(self, "text_encoder_2"):
985
- unfuse_text_encoder_lora(self.text_encoder_2)
986
-
987
- self.num_fused_loras -= 1
988
-
989
- def set_adapters_for_text_encoder(
990
- self,
991
- adapter_names: Union[List[str], str],
992
- text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
993
- text_encoder_weights: Optional[Union[float, List[float], List[None]]] = None,
994
- ):
995
- """
996
- Sets the adapter layers for the text encoder.
997
-
998
- Args:
999
- adapter_names (`List[str]` or `str`):
1000
- The names of the adapters to use.
1001
- text_encoder (`torch.nn.Module`, *optional*):
1002
- The text encoder module to set the adapter layers for. If `None`, it will try to get the `text_encoder`
1003
- attribute.
1004
- text_encoder_weights (`List[float]`, *optional*):
1005
- The weights to use for the text encoder. If `None`, the weights are set to `1.0` for all the adapters.
1006
- """
1007
- if not USE_PEFT_BACKEND:
1008
- raise ValueError("PEFT backend is required for this method.")
1009
-
1010
- def process_weights(adapter_names, weights):
1011
- # Expand weights into a list, one entry per adapter
1012
- # e.g. for 2 adapters: 7 -> [7,7] ; [3, None] -> [3, None]
1013
- if not isinstance(weights, list):
1014
- weights = [weights] * len(adapter_names)
1015
-
1016
- if len(adapter_names) != len(weights):
1017
- raise ValueError(
1018
- f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(weights)}"
1019
- )
1020
-
1021
- # Set None values to default of 1.0
1022
- # e.g. [7,7] -> [7,7] ; [3, None] -> [3,1]
1023
- weights = [w if w is not None else 1.0 for w in weights]
1024
-
1025
- return weights
1026
-
1027
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1028
- text_encoder_weights = process_weights(adapter_names, text_encoder_weights)
1029
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
1030
- if text_encoder is None:
1031
- raise ValueError(
1032
- "The pipeline does not have a default `pipe.text_encoder` class. Please make sure to pass a `text_encoder` instead."
1033
- )
1034
- set_weights_and_activate_adapters(text_encoder, adapter_names, text_encoder_weights)
1035
-
1036
- def disable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1037
- """
1038
- Disables the LoRA layers for the text encoder.
1039
-
1040
- Args:
1041
- text_encoder (`torch.nn.Module`, *optional*):
1042
- The text encoder module to disable the LoRA layers for. If `None`, it will try to get the
1043
- `text_encoder` attribute.
1044
- """
1045
- if not USE_PEFT_BACKEND:
1046
- raise ValueError("PEFT backend is required for this method.")
1047
-
1048
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
1049
- if text_encoder is None:
1050
- raise ValueError("Text Encoder not found.")
1051
- set_adapter_layers(text_encoder, enabled=False)
1052
-
1053
- def enable_lora_for_text_encoder(self, text_encoder: Optional["PreTrainedModel"] = None):
1054
- """
1055
- Enables the LoRA layers for the text encoder.
1056
-
1057
- Args:
1058
- text_encoder (`torch.nn.Module`, *optional*):
1059
- The text encoder module to enable the LoRA layers for. If `None`, it will try to get the `text_encoder`
1060
- attribute.
1061
- """
1062
- if not USE_PEFT_BACKEND:
1063
- raise ValueError("PEFT backend is required for this method.")
1064
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
1065
- if text_encoder is None:
1066
- raise ValueError("Text Encoder not found.")
1067
- set_adapter_layers(self.text_encoder, enabled=True)
1068
-
1069
- def set_adapters(
1070
- self,
1071
- adapter_names: Union[List[str], str],
1072
- adapter_weights: Optional[Union[float, Dict, List[float], List[Dict]]] = None,
1073
- ):
1074
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
1075
-
1076
- adapter_weights = copy.deepcopy(adapter_weights)
1077
-
1078
- # Expand weights into a list, one entry per adapter
1079
- if not isinstance(adapter_weights, list):
1080
- adapter_weights = [adapter_weights] * len(adapter_names)
1081
-
1082
- if len(adapter_names) != len(adapter_weights):
1083
- raise ValueError(
1084
- f"Length of adapter names {len(adapter_names)} is not equal to the length of the weights {len(adapter_weights)}"
1085
- )
1086
-
1087
- # Decompose weights into weights for unet, text_encoder and text_encoder_2
1088
- unet_lora_weights, text_encoder_lora_weights, text_encoder_2_lora_weights = [], [], []
1089
-
1090
- list_adapters = self.get_list_adapters() # eg {"unet": ["adapter1", "adapter2"], "text_encoder": ["adapter2"]}
1091
- all_adapters = {
1092
- adapter for adapters in list_adapters.values() for adapter in adapters
1093
- } # eg ["adapter1", "adapter2"]
1094
- invert_list_adapters = {
1095
- adapter: [part for part, adapters in list_adapters.items() if adapter in adapters]
1096
- for adapter in all_adapters
1097
- } # eg {"adapter1": ["unet"], "adapter2": ["unet", "text_encoder"]}
1098
-
1099
- for adapter_name, weights in zip(adapter_names, adapter_weights):
1100
- if isinstance(weights, dict):
1101
- unet_lora_weight = weights.pop("unet", None)
1102
- text_encoder_lora_weight = weights.pop("text_encoder", None)
1103
- text_encoder_2_lora_weight = weights.pop("text_encoder_2", None)
1104
-
1105
- if len(weights) > 0:
1106
- raise ValueError(
1107
- f"Got invalid key '{weights.keys()}' in lora weight dict for adapter {adapter_name}."
1108
- )
1109
-
1110
- if text_encoder_2_lora_weight is not None and not hasattr(self, "text_encoder_2"):
1111
- logger.warning(
1112
- "Lora weight dict contains text_encoder_2 weights but will be ignored because pipeline does not have text_encoder_2."
1113
- )
1114
-
1115
- # warn if adapter doesn't have parts specified by adapter_weights
1116
- for part_weight, part_name in zip(
1117
- [unet_lora_weight, text_encoder_lora_weight, text_encoder_2_lora_weight],
1118
- ["unet", "text_encoder", "text_encoder_2"],
1119
- ):
1120
- if part_weight is not None and part_name not in invert_list_adapters[adapter_name]:
1121
- logger.warning(
1122
- f"Lora weight dict for adapter '{adapter_name}' contains {part_name}, but this will be ignored because {adapter_name} does not contain weights for {part_name}. Valid parts for {adapter_name} are: {invert_list_adapters[adapter_name]}."
1123
- )
1124
-
1125
- else:
1126
- unet_lora_weight = weights
1127
- text_encoder_lora_weight = weights
1128
- text_encoder_2_lora_weight = weights
1129
-
1130
- unet_lora_weights.append(unet_lora_weight)
1131
- text_encoder_lora_weights.append(text_encoder_lora_weight)
1132
- text_encoder_2_lora_weights.append(text_encoder_2_lora_weight)
1133
-
1134
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1135
- # Handle the UNET
1136
- unet.set_adapters(adapter_names, unet_lora_weights)
1137
-
1138
- # Handle the Text Encoder
1139
- if hasattr(self, "text_encoder"):
1140
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder, text_encoder_lora_weights)
1141
- if hasattr(self, "text_encoder_2"):
1142
- self.set_adapters_for_text_encoder(adapter_names, self.text_encoder_2, text_encoder_2_lora_weights)
1143
-
1144
- def disable_lora(self):
1145
- if not USE_PEFT_BACKEND:
1146
- raise ValueError("PEFT backend is required for this method.")
1147
-
1148
- # Disable unet adapters
1149
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1150
- unet.disable_lora()
1151
-
1152
- # Disable text encoder adapters
1153
- if hasattr(self, "text_encoder"):
1154
- self.disable_lora_for_text_encoder(self.text_encoder)
1155
- if hasattr(self, "text_encoder_2"):
1156
- self.disable_lora_for_text_encoder(self.text_encoder_2)
1157
-
1158
- def enable_lora(self):
1159
- if not USE_PEFT_BACKEND:
1160
- raise ValueError("PEFT backend is required for this method.")
1161
-
1162
- # Enable unet adapters
1163
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1164
- unet.enable_lora()
1165
-
1166
- # Enable text encoder adapters
1167
- if hasattr(self, "text_encoder"):
1168
- self.enable_lora_for_text_encoder(self.text_encoder)
1169
- if hasattr(self, "text_encoder_2"):
1170
- self.enable_lora_for_text_encoder(self.text_encoder_2)
1171
-
1172
- def delete_adapters(self, adapter_names: Union[List[str], str]):
1173
- """
1174
- Args:
1175
- Deletes the LoRA layers of `adapter_name` for the unet and text-encoder(s).
1176
- adapter_names (`Union[List[str], str]`):
1177
- The names of the adapter to delete. Can be a single string or a list of strings
1178
- """
1179
- if not USE_PEFT_BACKEND:
1180
- raise ValueError("PEFT backend is required for this method.")
1181
-
1182
- if isinstance(adapter_names, str):
1183
- adapter_names = [adapter_names]
1184
-
1185
- # Delete unet adapters
1186
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1187
- unet.delete_adapters(adapter_names)
1188
-
1189
- for adapter_name in adapter_names:
1190
- # Delete text encoder adapters
1191
- if hasattr(self, "text_encoder"):
1192
- delete_adapter_layers(self.text_encoder, adapter_name)
1193
- if hasattr(self, "text_encoder_2"):
1194
- delete_adapter_layers(self.text_encoder_2, adapter_name)
1195
-
1196
- def get_active_adapters(self) -> List[str]:
1197
- """
1198
- Gets the list of the current active adapters.
1199
-
1200
- Example:
1201
-
1202
- ```python
1203
- from diffusers import DiffusionPipeline
1204
-
1205
- pipeline = DiffusionPipeline.from_pretrained(
1206
- "stabilityai/stable-diffusion-xl-base-1.0",
1207
- ).to("cuda")
1208
- pipeline.load_lora_weights("CiroN2022/toy-face", weight_name="toy_face_sdxl.safetensors", adapter_name="toy")
1209
- pipeline.get_active_adapters()
1210
- ```
1211
- """
1212
- if not USE_PEFT_BACKEND:
1213
- raise ValueError(
1214
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1215
- )
1216
-
1217
- from peft.tuners.tuners_utils import BaseTunerLayer
1218
-
1219
- active_adapters = []
1220
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1221
- for module in unet.modules():
1222
- if isinstance(module, BaseTunerLayer):
1223
- active_adapters = module.active_adapters
1224
- break
1225
-
1226
- return active_adapters
1227
-
1228
- def get_list_adapters(self) -> Dict[str, List[str]]:
1229
- """
1230
- Gets the current list of all available adapters in the pipeline.
1231
- """
1232
- if not USE_PEFT_BACKEND:
1233
- raise ValueError(
1234
- "PEFT backend is required for this method. Please install the latest version of PEFT `pip install -U peft`"
1235
- )
1236
-
1237
- set_adapters = {}
1238
-
1239
- if hasattr(self, "text_encoder") and hasattr(self.text_encoder, "peft_config"):
1240
- set_adapters["text_encoder"] = list(self.text_encoder.peft_config.keys())
1241
-
1242
- if hasattr(self, "text_encoder_2") and hasattr(self.text_encoder_2, "peft_config"):
1243
- set_adapters["text_encoder_2"] = list(self.text_encoder_2.peft_config.keys())
1244
-
1245
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1246
- if hasattr(self, self.unet_name) and hasattr(unet, "peft_config"):
1247
- set_adapters[self.unet_name] = list(self.unet.peft_config.keys())
1248
-
1249
- return set_adapters
1250
-
1251
- def set_lora_device(self, adapter_names: List[str], device: Union[torch.device, str, int]) -> None:
1252
- """
1253
- Moves the LoRAs listed in `adapter_names` to a target device. Useful for offloading the LoRA to the CPU in case
1254
- you want to load multiple adapters and free some GPU memory.
1255
-
1256
- Args:
1257
- adapter_names (`List[str]`):
1258
- List of adapters to send device to.
1259
- device (`Union[torch.device, str, int]`):
1260
- Device to send the adapters to. Can be either a torch device, a str or an integer.
1261
- """
1262
- if not USE_PEFT_BACKEND:
1263
- raise ValueError("PEFT backend is required for this method.")
1264
-
1265
- from peft.tuners.tuners_utils import BaseTunerLayer
1266
-
1267
- # Handle the UNET
1268
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
1269
- for unet_module in unet.modules():
1270
- if isinstance(unet_module, BaseTunerLayer):
1271
- for adapter_name in adapter_names:
1272
- unet_module.lora_A[adapter_name].to(device)
1273
- unet_module.lora_B[adapter_name].to(device)
1274
- # this is a param, not a module, so device placement is not in-place -> re-assign
1275
- if hasattr(unet_module, "lora_magnitude_vector") and unet_module.lora_magnitude_vector is not None:
1276
- unet_module.lora_magnitude_vector[adapter_name] = unet_module.lora_magnitude_vector[
1277
- adapter_name
1278
- ].to(device)
1279
-
1280
- # Handle the text encoder
1281
- modules_to_process = []
1282
- if hasattr(self, "text_encoder"):
1283
- modules_to_process.append(self.text_encoder)
1284
-
1285
- if hasattr(self, "text_encoder_2"):
1286
- modules_to_process.append(self.text_encoder_2)
1287
-
1288
- for text_encoder in modules_to_process:
1289
- # loop over submodules
1290
- for text_encoder_module in text_encoder.modules():
1291
- if isinstance(text_encoder_module, BaseTunerLayer):
1292
- for adapter_name in adapter_names:
1293
- text_encoder_module.lora_A[adapter_name].to(device)
1294
- text_encoder_module.lora_B[adapter_name].to(device)
1295
- # this is a param, not a module, so device placement is not in-place -> re-assign
1296
- if (
1297
- hasattr(text_encoder, "lora_magnitude_vector")
1298
- and text_encoder_module.lora_magnitude_vector is not None
1299
- ):
1300
- text_encoder_module.lora_magnitude_vector[
1301
- adapter_name
1302
- ] = text_encoder_module.lora_magnitude_vector[adapter_name].to(device)
1303
-
1304
-
1305
- class StableDiffusionXLLoraLoaderMixin(LoraLoaderMixin):
1306
- """This class overrides `LoraLoaderMixin` with LoRA loading/saving code that's specific to SDXL"""
1307
-
1308
- # Override to properly handle the loading and unloading of the additional text encoder.
1309
- def load_lora_weights(
1310
- self,
1311
- pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]],
1312
- adapter_name: Optional[str] = None,
1313
- **kwargs,
1314
- ):
1315
- """
1316
- Load LoRA weights specified in `pretrained_model_name_or_path_or_dict` into `self.unet` and
1317
- `self.text_encoder`.
1318
-
1319
- All kwargs are forwarded to `self.lora_state_dict`.
1320
-
1321
- See [`~loaders.LoraLoaderMixin.lora_state_dict`] for more details on how the state dict is loaded.
1322
-
1323
- See [`~loaders.LoraLoaderMixin.load_lora_into_unet`] for more details on how the state dict is loaded into
1324
- `self.unet`.
1325
-
1326
- See [`~loaders.LoraLoaderMixin.load_lora_into_text_encoder`] for more details on how the state dict is loaded
1327
- into `self.text_encoder`.
1328
-
1329
- Parameters:
1330
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
1331
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1332
- adapter_name (`str`, *optional*):
1333
- Adapter name to be used for referencing the loaded adapter model. If not specified, it will use
1334
- `default_{i}` where i is the total number of adapters being loaded.
1335
- kwargs (`dict`, *optional*):
1336
- See [`~loaders.LoraLoaderMixin.lora_state_dict`].
1337
- """
1338
- if not USE_PEFT_BACKEND:
1339
- raise ValueError("PEFT backend is required for this method.")
1340
-
1341
- # We could have accessed the unet config from `lora_state_dict()` too. We pass
1342
- # it here explicitly to be able to tell that it's coming from an SDXL
1343
- # pipeline.
1344
-
1345
- # if a dict is passed, copy it instead of modifying it inplace
1346
- if isinstance(pretrained_model_name_or_path_or_dict, dict):
1347
- pretrained_model_name_or_path_or_dict = pretrained_model_name_or_path_or_dict.copy()
1348
-
1349
- # First, ensure that the checkpoint is a compatible one and can be successfully loaded.
1350
- state_dict, network_alphas = self.lora_state_dict(
1351
- pretrained_model_name_or_path_or_dict,
1352
- unet_config=self.unet.config,
1353
- **kwargs,
1354
- )
1355
- is_correct_format = all("lora" in key or "dora_scale" in key for key in state_dict.keys())
1356
- if not is_correct_format:
1357
- raise ValueError("Invalid LoRA checkpoint.")
1358
-
1359
- self.load_lora_into_unet(
1360
- state_dict, network_alphas=network_alphas, unet=self.unet, adapter_name=adapter_name, _pipeline=self
1361
- )
1362
- text_encoder_state_dict = {k: v for k, v in state_dict.items() if "text_encoder." in k}
1363
- if len(text_encoder_state_dict) > 0:
1364
- self.load_lora_into_text_encoder(
1365
- text_encoder_state_dict,
1366
- network_alphas=network_alphas,
1367
- text_encoder=self.text_encoder,
1368
- prefix="text_encoder",
1369
- lora_scale=self.lora_scale,
1370
- adapter_name=adapter_name,
1371
- _pipeline=self,
1372
- )
1373
-
1374
- text_encoder_2_state_dict = {k: v for k, v in state_dict.items() if "text_encoder_2." in k}
1375
- if len(text_encoder_2_state_dict) > 0:
1376
- self.load_lora_into_text_encoder(
1377
- text_encoder_2_state_dict,
1378
- network_alphas=network_alphas,
1379
- text_encoder=self.text_encoder_2,
1380
- prefix="text_encoder_2",
1381
- lora_scale=self.lora_scale,
1382
- adapter_name=adapter_name,
1383
- _pipeline=self,
1384
- )
1385
-
1386
- @classmethod
1387
- def save_lora_weights(
1388
- cls,
1389
- save_directory: Union[str, os.PathLike],
1390
- unet_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1391
- text_encoder_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1392
- text_encoder_2_lora_layers: Dict[str, Union[torch.nn.Module, torch.Tensor]] = None,
1393
- is_main_process: bool = True,
1394
- weight_name: str = None,
1395
- save_function: Callable = None,
1396
- safe_serialization: bool = True,
1397
- ):
1398
- r"""
1399
- Save the LoRA parameters corresponding to the UNet and text encoder.
1400
-
1401
- Arguments:
1402
- save_directory (`str` or `os.PathLike`):
1403
- Directory to save LoRA parameters to. Will be created if it doesn't exist.
1404
- unet_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1405
- State dict of the LoRA layers corresponding to the `unet`.
1406
- text_encoder_lora_layers (`Dict[str, torch.nn.Module]` or `Dict[str, torch.Tensor]`):
1407
- State dict of the LoRA layers corresponding to the `text_encoder`. Must explicitly pass the text
1408
- encoder LoRA state dict because it comes from 🤗 Transformers.
1409
- is_main_process (`bool`, *optional*, defaults to `True`):
1410
- Whether the process calling this is the main process or not. Useful during distributed training and you
1411
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
1412
- process to avoid race conditions.
1413
- save_function (`Callable`):
1414
- The function to use to save the state dictionary. Useful during distributed training when you need to
1415
- replace `torch.save` with another method. Can be configured with the environment variable
1416
- `DIFFUSERS_SAVE_MODE`.
1417
- safe_serialization (`bool`, *optional*, defaults to `True`):
1418
- Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
1419
- """
1420
- state_dict = {}
1421
-
1422
- def pack_weights(layers, prefix):
1423
- layers_weights = layers.state_dict() if isinstance(layers, torch.nn.Module) else layers
1424
- layers_state_dict = {f"{prefix}.{module_name}": param for module_name, param in layers_weights.items()}
1425
- return layers_state_dict
1426
-
1427
- if not (unet_lora_layers or text_encoder_lora_layers or text_encoder_2_lora_layers):
1428
- raise ValueError(
1429
- "You must pass at least one of `unet_lora_layers`, `text_encoder_lora_layers` or `text_encoder_2_lora_layers`."
1430
- )
1431
-
1432
- if unet_lora_layers:
1433
- state_dict.update(pack_weights(unet_lora_layers, "unet"))
1434
-
1435
- if text_encoder_lora_layers and text_encoder_2_lora_layers:
1436
- state_dict.update(pack_weights(text_encoder_lora_layers, "text_encoder"))
1437
- state_dict.update(pack_weights(text_encoder_2_lora_layers, "text_encoder_2"))
1438
-
1439
- cls.write_lora_layers(
1440
- state_dict=state_dict,
1441
- save_directory=save_directory,
1442
- is_main_process=is_main_process,
1443
- weight_name=weight_name,
1444
- save_function=save_function,
1445
- safe_serialization=safe_serialization,
1446
- )
1447
-
1448
- def _remove_text_encoder_monkey_patch(self):
1449
- recurse_remove_peft_layers(self.text_encoder)
1450
- # TODO: @younesbelkada handle this in transformers side
1451
- if getattr(self.text_encoder, "peft_config", None) is not None:
1452
- del self.text_encoder.peft_config
1453
- self.text_encoder._hf_peft_config_loaded = None
1454
-
1455
- recurse_remove_peft_layers(self.text_encoder_2)
1456
- if getattr(self.text_encoder_2, "peft_config", None) is not None:
1457
- del self.text_encoder_2.peft_config
1458
- self.text_encoder_2._hf_peft_config_loaded = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/lora_conversion_utils.py DELETED
@@ -1,287 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import re
16
-
17
- from ..utils import is_peft_version, logging
18
-
19
-
20
- logger = logging.get_logger(__name__)
21
-
22
-
23
- def _maybe_map_sgm_blocks_to_diffusers(state_dict, unet_config, delimiter="_", block_slice_pos=5):
24
- # 1. get all state_dict_keys
25
- all_keys = list(state_dict.keys())
26
- sgm_patterns = ["input_blocks", "middle_block", "output_blocks"]
27
-
28
- # 2. check if needs remapping, if not return original dict
29
- is_in_sgm_format = False
30
- for key in all_keys:
31
- if any(p in key for p in sgm_patterns):
32
- is_in_sgm_format = True
33
- break
34
-
35
- if not is_in_sgm_format:
36
- return state_dict
37
-
38
- # 3. Else remap from SGM patterns
39
- new_state_dict = {}
40
- inner_block_map = ["resnets", "attentions", "upsamplers"]
41
-
42
- # Retrieves # of down, mid and up blocks
43
- input_block_ids, middle_block_ids, output_block_ids = set(), set(), set()
44
-
45
- for layer in all_keys:
46
- if "text" in layer:
47
- new_state_dict[layer] = state_dict.pop(layer)
48
- else:
49
- layer_id = int(layer.split(delimiter)[:block_slice_pos][-1])
50
- if sgm_patterns[0] in layer:
51
- input_block_ids.add(layer_id)
52
- elif sgm_patterns[1] in layer:
53
- middle_block_ids.add(layer_id)
54
- elif sgm_patterns[2] in layer:
55
- output_block_ids.add(layer_id)
56
- else:
57
- raise ValueError(f"Checkpoint not supported because layer {layer} not supported.")
58
-
59
- input_blocks = {
60
- layer_id: [key for key in state_dict if f"input_blocks{delimiter}{layer_id}" in key]
61
- for layer_id in input_block_ids
62
- }
63
- middle_blocks = {
64
- layer_id: [key for key in state_dict if f"middle_block{delimiter}{layer_id}" in key]
65
- for layer_id in middle_block_ids
66
- }
67
- output_blocks = {
68
- layer_id: [key for key in state_dict if f"output_blocks{delimiter}{layer_id}" in key]
69
- for layer_id in output_block_ids
70
- }
71
-
72
- # Rename keys accordingly
73
- for i in input_block_ids:
74
- block_id = (i - 1) // (unet_config.layers_per_block + 1)
75
- layer_in_block_id = (i - 1) % (unet_config.layers_per_block + 1)
76
-
77
- for key in input_blocks[i]:
78
- inner_block_id = int(key.split(delimiter)[block_slice_pos])
79
- inner_block_key = inner_block_map[inner_block_id] if "op" not in key else "downsamplers"
80
- inner_layers_in_block = str(layer_in_block_id) if "op" not in key else "0"
81
- new_key = delimiter.join(
82
- key.split(delimiter)[: block_slice_pos - 1]
83
- + [str(block_id), inner_block_key, inner_layers_in_block]
84
- + key.split(delimiter)[block_slice_pos + 1 :]
85
- )
86
- new_state_dict[new_key] = state_dict.pop(key)
87
-
88
- for i in middle_block_ids:
89
- key_part = None
90
- if i == 0:
91
- key_part = [inner_block_map[0], "0"]
92
- elif i == 1:
93
- key_part = [inner_block_map[1], "0"]
94
- elif i == 2:
95
- key_part = [inner_block_map[0], "1"]
96
- else:
97
- raise ValueError(f"Invalid middle block id {i}.")
98
-
99
- for key in middle_blocks[i]:
100
- new_key = delimiter.join(
101
- key.split(delimiter)[: block_slice_pos - 1] + key_part + key.split(delimiter)[block_slice_pos:]
102
- )
103
- new_state_dict[new_key] = state_dict.pop(key)
104
-
105
- for i in output_block_ids:
106
- block_id = i // (unet_config.layers_per_block + 1)
107
- layer_in_block_id = i % (unet_config.layers_per_block + 1)
108
-
109
- for key in output_blocks[i]:
110
- inner_block_id = int(key.split(delimiter)[block_slice_pos])
111
- inner_block_key = inner_block_map[inner_block_id]
112
- inner_layers_in_block = str(layer_in_block_id) if inner_block_id < 2 else "0"
113
- new_key = delimiter.join(
114
- key.split(delimiter)[: block_slice_pos - 1]
115
- + [str(block_id), inner_block_key, inner_layers_in_block]
116
- + key.split(delimiter)[block_slice_pos + 1 :]
117
- )
118
- new_state_dict[new_key] = state_dict.pop(key)
119
-
120
- if len(state_dict) > 0:
121
- raise ValueError("At this point all state dict entries have to be converted.")
122
-
123
- return new_state_dict
124
-
125
-
126
- def _convert_kohya_lora_to_diffusers(state_dict, unet_name="unet", text_encoder_name="text_encoder"):
127
- unet_state_dict = {}
128
- te_state_dict = {}
129
- te2_state_dict = {}
130
- network_alphas = {}
131
- is_unet_dora_lora = any("dora_scale" in k and "lora_unet_" in k for k in state_dict)
132
- is_te_dora_lora = any("dora_scale" in k and ("lora_te_" in k or "lora_te1_" in k) for k in state_dict)
133
- is_te2_dora_lora = any("dora_scale" in k and "lora_te2_" in k for k in state_dict)
134
-
135
- if is_unet_dora_lora or is_te_dora_lora or is_te2_dora_lora:
136
- if is_peft_version("<", "0.9.0"):
137
- raise ValueError(
138
- "You need `peft` 0.9.0 at least to use DoRA-enabled LoRAs. Please upgrade your installation of `peft`."
139
- )
140
-
141
- # every down weight has a corresponding up weight and potentially an alpha weight
142
- lora_keys = [k for k in state_dict.keys() if k.endswith("lora_down.weight")]
143
- for key in lora_keys:
144
- lora_name = key.split(".")[0]
145
- lora_name_up = lora_name + ".lora_up.weight"
146
- lora_name_alpha = lora_name + ".alpha"
147
-
148
- if lora_name.startswith("lora_unet_"):
149
- diffusers_name = key.replace("lora_unet_", "").replace("_", ".")
150
-
151
- if "input.blocks" in diffusers_name:
152
- diffusers_name = diffusers_name.replace("input.blocks", "down_blocks")
153
- else:
154
- diffusers_name = diffusers_name.replace("down.blocks", "down_blocks")
155
-
156
- if "middle.block" in diffusers_name:
157
- diffusers_name = diffusers_name.replace("middle.block", "mid_block")
158
- else:
159
- diffusers_name = diffusers_name.replace("mid.block", "mid_block")
160
- if "output.blocks" in diffusers_name:
161
- diffusers_name = diffusers_name.replace("output.blocks", "up_blocks")
162
- else:
163
- diffusers_name = diffusers_name.replace("up.blocks", "up_blocks")
164
-
165
- diffusers_name = diffusers_name.replace("transformer.blocks", "transformer_blocks")
166
- diffusers_name = diffusers_name.replace("to.q.lora", "to_q_lora")
167
- diffusers_name = diffusers_name.replace("to.k.lora", "to_k_lora")
168
- diffusers_name = diffusers_name.replace("to.v.lora", "to_v_lora")
169
- diffusers_name = diffusers_name.replace("to.out.0.lora", "to_out_lora")
170
- diffusers_name = diffusers_name.replace("proj.in", "proj_in")
171
- diffusers_name = diffusers_name.replace("proj.out", "proj_out")
172
- diffusers_name = diffusers_name.replace("emb.layers", "time_emb_proj")
173
-
174
- # SDXL specificity.
175
- if "emb" in diffusers_name and "time.emb.proj" not in diffusers_name:
176
- pattern = r"\.\d+(?=\D*$)"
177
- diffusers_name = re.sub(pattern, "", diffusers_name, count=1)
178
- if ".in." in diffusers_name:
179
- diffusers_name = diffusers_name.replace("in.layers.2", "conv1")
180
- if ".out." in diffusers_name:
181
- diffusers_name = diffusers_name.replace("out.layers.3", "conv2")
182
- if "downsamplers" in diffusers_name or "upsamplers" in diffusers_name:
183
- diffusers_name = diffusers_name.replace("op", "conv")
184
- if "skip" in diffusers_name:
185
- diffusers_name = diffusers_name.replace("skip.connection", "conv_shortcut")
186
-
187
- # LyCORIS specificity.
188
- if "time.emb.proj" in diffusers_name:
189
- diffusers_name = diffusers_name.replace("time.emb.proj", "time_emb_proj")
190
- if "conv.shortcut" in diffusers_name:
191
- diffusers_name = diffusers_name.replace("conv.shortcut", "conv_shortcut")
192
-
193
- # General coverage.
194
- if "transformer_blocks" in diffusers_name:
195
- if "attn1" in diffusers_name or "attn2" in diffusers_name:
196
- diffusers_name = diffusers_name.replace("attn1", "attn1.processor")
197
- diffusers_name = diffusers_name.replace("attn2", "attn2.processor")
198
- unet_state_dict[diffusers_name] = state_dict.pop(key)
199
- unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
200
- elif "ff" in diffusers_name:
201
- unet_state_dict[diffusers_name] = state_dict.pop(key)
202
- unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
203
- elif any(key in diffusers_name for key in ("proj_in", "proj_out")):
204
- unet_state_dict[diffusers_name] = state_dict.pop(key)
205
- unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
206
- else:
207
- unet_state_dict[diffusers_name] = state_dict.pop(key)
208
- unet_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
209
-
210
- if is_unet_dora_lora:
211
- dora_scale_key_to_replace = "_lora.down." if "_lora.down." in diffusers_name else ".lora.down."
212
- unet_state_dict[
213
- diffusers_name.replace(dora_scale_key_to_replace, ".lora_magnitude_vector.")
214
- ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
215
-
216
- elif lora_name.startswith(("lora_te_", "lora_te1_", "lora_te2_")):
217
- if lora_name.startswith(("lora_te_", "lora_te1_")):
218
- key_to_replace = "lora_te_" if lora_name.startswith("lora_te_") else "lora_te1_"
219
- else:
220
- key_to_replace = "lora_te2_"
221
-
222
- diffusers_name = key.replace(key_to_replace, "").replace("_", ".")
223
- diffusers_name = diffusers_name.replace("text.model", "text_model")
224
- diffusers_name = diffusers_name.replace("self.attn", "self_attn")
225
- diffusers_name = diffusers_name.replace("q.proj.lora", "to_q_lora")
226
- diffusers_name = diffusers_name.replace("k.proj.lora", "to_k_lora")
227
- diffusers_name = diffusers_name.replace("v.proj.lora", "to_v_lora")
228
- diffusers_name = diffusers_name.replace("out.proj.lora", "to_out_lora")
229
- if "self_attn" in diffusers_name:
230
- if lora_name.startswith(("lora_te_", "lora_te1_")):
231
- te_state_dict[diffusers_name] = state_dict.pop(key)
232
- te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
233
- else:
234
- te2_state_dict[diffusers_name] = state_dict.pop(key)
235
- te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
236
- elif "mlp" in diffusers_name:
237
- # Be aware that this is the new diffusers convention and the rest of the code might
238
- # not utilize it yet.
239
- diffusers_name = diffusers_name.replace(".lora.", ".lora_linear_layer.")
240
- if lora_name.startswith(("lora_te_", "lora_te1_")):
241
- te_state_dict[diffusers_name] = state_dict.pop(key)
242
- te_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
243
- else:
244
- te2_state_dict[diffusers_name] = state_dict.pop(key)
245
- te2_state_dict[diffusers_name.replace(".down.", ".up.")] = state_dict.pop(lora_name_up)
246
-
247
- if (is_te_dora_lora or is_te2_dora_lora) and lora_name.startswith(("lora_te_", "lora_te1_", "lora_te2_")):
248
- dora_scale_key_to_replace_te = (
249
- "_lora.down." if "_lora.down." in diffusers_name else ".lora_linear_layer."
250
- )
251
- if lora_name.startswith(("lora_te_", "lora_te1_")):
252
- te_state_dict[
253
- diffusers_name.replace(dora_scale_key_to_replace_te, ".lora_magnitude_vector.")
254
- ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
255
- elif lora_name.startswith("lora_te2_"):
256
- te2_state_dict[
257
- diffusers_name.replace(dora_scale_key_to_replace_te, ".lora_magnitude_vector.")
258
- ] = state_dict.pop(key.replace("lora_down.weight", "dora_scale"))
259
-
260
- # Rename the alphas so that they can be mapped appropriately.
261
- if lora_name_alpha in state_dict:
262
- alpha = state_dict.pop(lora_name_alpha).item()
263
- if lora_name_alpha.startswith("lora_unet_"):
264
- prefix = "unet."
265
- elif lora_name_alpha.startswith(("lora_te_", "lora_te1_")):
266
- prefix = "text_encoder."
267
- else:
268
- prefix = "text_encoder_2."
269
- new_name = prefix + diffusers_name.split(".lora.")[0] + ".alpha"
270
- network_alphas.update({new_name: alpha})
271
-
272
- if len(state_dict) > 0:
273
- raise ValueError(f"The following keys have not been correctly be renamed: \n\n {', '.join(state_dict.keys())}")
274
-
275
- logger.info("Kohya-style checkpoint detected.")
276
- unet_state_dict = {f"{unet_name}.{module_name}": params for module_name, params in unet_state_dict.items()}
277
- te_state_dict = {f"{text_encoder_name}.{module_name}": params for module_name, params in te_state_dict.items()}
278
- te2_state_dict = (
279
- {f"text_encoder_2.{module_name}": params for module_name, params in te2_state_dict.items()}
280
- if len(te2_state_dict) > 0
281
- else None
282
- )
283
- if te2_state_dict is not None:
284
- te_state_dict.update(te2_state_dict)
285
-
286
- new_state_dict = {**unet_state_dict, **te_state_dict}
287
- return new_state_dict, network_alphas
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/peft.py DELETED
@@ -1,187 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The HuggingFace Inc. team.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- from typing import List, Union
16
-
17
- from ..utils import MIN_PEFT_VERSION, check_peft_version, is_peft_available
18
-
19
-
20
- class PeftAdapterMixin:
21
- """
22
- A class containing all functions for loading and using adapters weights that are supported in PEFT library. For
23
- more details about adapters and injecting them in a transformer-based model, check out the PEFT
24
- [documentation](https://huggingface.co/docs/peft/index).
25
-
26
- Install the latest version of PEFT, and use this mixin to:
27
-
28
- - Attach new adapters in the model.
29
- - Attach multiple adapters and iteratively activate/deactivate them.
30
- - Activate/deactivate all adapters from the model.
31
- - Get a list of the active adapters.
32
- """
33
-
34
- _hf_peft_config_loaded = False
35
-
36
- def add_adapter(self, adapter_config, adapter_name: str = "default") -> None:
37
- r"""
38
- Adds a new adapter to the current model for training. If no adapter name is passed, a default name is assigned
39
- to the adapter to follow the convention of the PEFT library.
40
-
41
- If you are not familiar with adapters and PEFT methods, we invite you to read more about them in the PEFT
42
- [documentation](https://huggingface.co/docs/peft).
43
-
44
- Args:
45
- adapter_config (`[~peft.PeftConfig]`):
46
- The configuration of the adapter to add; supported adapters are non-prefix tuning and adaption prompt
47
- methods.
48
- adapter_name (`str`, *optional*, defaults to `"default"`):
49
- The name of the adapter to add. If no name is passed, a default name is assigned to the adapter.
50
- """
51
- check_peft_version(min_version=MIN_PEFT_VERSION)
52
-
53
- if not is_peft_available():
54
- raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
55
-
56
- from peft import PeftConfig, inject_adapter_in_model
57
-
58
- if not self._hf_peft_config_loaded:
59
- self._hf_peft_config_loaded = True
60
- elif adapter_name in self.peft_config:
61
- raise ValueError(f"Adapter with name {adapter_name} already exists. Please use a different name.")
62
-
63
- if not isinstance(adapter_config, PeftConfig):
64
- raise ValueError(
65
- f"adapter_config should be an instance of PeftConfig. Got {type(adapter_config)} instead."
66
- )
67
-
68
- # Unlike transformers, here we don't need to retrieve the name_or_path of the unet as the loading logic is
69
- # handled by the `load_lora_layers` or `LoraLoaderMixin`. Therefore we set it to `None` here.
70
- adapter_config.base_model_name_or_path = None
71
- inject_adapter_in_model(adapter_config, self, adapter_name)
72
- self.set_adapter(adapter_name)
73
-
74
- def set_adapter(self, adapter_name: Union[str, List[str]]) -> None:
75
- """
76
- Sets a specific adapter by forcing the model to only use that adapter and disables the other adapters.
77
-
78
- If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
79
- [documentation](https://huggingface.co/docs/peft).
80
-
81
- Args:
82
- adapter_name (Union[str, List[str]])):
83
- The list of adapters to set or the adapter name in the case of a single adapter.
84
- """
85
- check_peft_version(min_version=MIN_PEFT_VERSION)
86
-
87
- if not self._hf_peft_config_loaded:
88
- raise ValueError("No adapter loaded. Please load an adapter first.")
89
-
90
- if isinstance(adapter_name, str):
91
- adapter_name = [adapter_name]
92
-
93
- missing = set(adapter_name) - set(self.peft_config)
94
- if len(missing) > 0:
95
- raise ValueError(
96
- f"Following adapter(s) could not be found: {', '.join(missing)}. Make sure you are passing the correct adapter name(s)."
97
- f" current loaded adapters are: {list(self.peft_config.keys())}"
98
- )
99
-
100
- from peft.tuners.tuners_utils import BaseTunerLayer
101
-
102
- _adapters_has_been_set = False
103
-
104
- for _, module in self.named_modules():
105
- if isinstance(module, BaseTunerLayer):
106
- if hasattr(module, "set_adapter"):
107
- module.set_adapter(adapter_name)
108
- # Previous versions of PEFT does not support multi-adapter inference
109
- elif not hasattr(module, "set_adapter") and len(adapter_name) != 1:
110
- raise ValueError(
111
- "You are trying to set multiple adapters and you have a PEFT version that does not support multi-adapter inference. Please upgrade to the latest version of PEFT."
112
- " `pip install -U peft` or `pip install -U git+https://github.com/huggingface/peft.git`"
113
- )
114
- else:
115
- module.active_adapter = adapter_name
116
- _adapters_has_been_set = True
117
-
118
- if not _adapters_has_been_set:
119
- raise ValueError(
120
- "Did not succeeded in setting the adapter. Please make sure you are using a model that supports adapters."
121
- )
122
-
123
- def disable_adapters(self) -> None:
124
- r"""
125
- Disable all adapters attached to the model and fallback to inference with the base model only.
126
-
127
- If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
128
- [documentation](https://huggingface.co/docs/peft).
129
- """
130
- check_peft_version(min_version=MIN_PEFT_VERSION)
131
-
132
- if not self._hf_peft_config_loaded:
133
- raise ValueError("No adapter loaded. Please load an adapter first.")
134
-
135
- from peft.tuners.tuners_utils import BaseTunerLayer
136
-
137
- for _, module in self.named_modules():
138
- if isinstance(module, BaseTunerLayer):
139
- if hasattr(module, "enable_adapters"):
140
- module.enable_adapters(enabled=False)
141
- else:
142
- # support for older PEFT versions
143
- module.disable_adapters = True
144
-
145
- def enable_adapters(self) -> None:
146
- """
147
- Enable adapters that are attached to the model. The model uses `self.active_adapters()` to retrieve the list of
148
- adapters to enable.
149
-
150
- If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
151
- [documentation](https://huggingface.co/docs/peft).
152
- """
153
- check_peft_version(min_version=MIN_PEFT_VERSION)
154
-
155
- if not self._hf_peft_config_loaded:
156
- raise ValueError("No adapter loaded. Please load an adapter first.")
157
-
158
- from peft.tuners.tuners_utils import BaseTunerLayer
159
-
160
- for _, module in self.named_modules():
161
- if isinstance(module, BaseTunerLayer):
162
- if hasattr(module, "enable_adapters"):
163
- module.enable_adapters(enabled=True)
164
- else:
165
- # support for older PEFT versions
166
- module.disable_adapters = False
167
-
168
- def active_adapters(self) -> List[str]:
169
- """
170
- Gets the current list of active adapters of the model.
171
-
172
- If you are not familiar with adapters and PEFT methods, we invite you to read more about them on the PEFT
173
- [documentation](https://huggingface.co/docs/peft).
174
- """
175
- check_peft_version(min_version=MIN_PEFT_VERSION)
176
-
177
- if not is_peft_available():
178
- raise ImportError("PEFT is not available. Please install PEFT to use this function: `pip install peft`.")
179
-
180
- if not self._hf_peft_config_loaded:
181
- raise ValueError("No adapter loaded. Please load an adapter first.")
182
-
183
- from peft.tuners.tuners_utils import BaseTunerLayer
184
-
185
- for _, module in self.named_modules():
186
- if isinstance(module, BaseTunerLayer):
187
- return module.active_adapter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/single_file.py DELETED
@@ -1,323 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from huggingface_hub.utils import validate_hf_hub_args
16
-
17
- from ..utils import is_transformers_available, logging
18
- from .single_file_utils import (
19
- create_diffusers_unet_model_from_ldm,
20
- create_diffusers_vae_model_from_ldm,
21
- create_scheduler_from_ldm,
22
- create_text_encoders_and_tokenizers_from_ldm,
23
- fetch_ldm_config_and_checkpoint,
24
- infer_model_type,
25
- )
26
-
27
-
28
- logger = logging.get_logger(__name__)
29
-
30
- # Pipelines that support the SDXL Refiner checkpoint
31
- REFINER_PIPELINES = [
32
- "StableDiffusionXLImg2ImgPipeline",
33
- "StableDiffusionXLInpaintPipeline",
34
- "StableDiffusionXLControlNetImg2ImgPipeline",
35
- ]
36
-
37
- if is_transformers_available():
38
- from transformers import AutoFeatureExtractor
39
-
40
-
41
- def build_sub_model_components(
42
- pipeline_components,
43
- pipeline_class_name,
44
- component_name,
45
- original_config,
46
- checkpoint,
47
- local_files_only=False,
48
- load_safety_checker=False,
49
- model_type=None,
50
- image_size=None,
51
- torch_dtype=None,
52
- **kwargs,
53
- ):
54
- if component_name in pipeline_components:
55
- return {}
56
-
57
- if component_name == "unet":
58
- num_in_channels = kwargs.pop("num_in_channels", None)
59
- upcast_attention = kwargs.pop("upcast_attention", None)
60
-
61
- unet_components = create_diffusers_unet_model_from_ldm(
62
- pipeline_class_name,
63
- original_config,
64
- checkpoint,
65
- num_in_channels=num_in_channels,
66
- image_size=image_size,
67
- torch_dtype=torch_dtype,
68
- model_type=model_type,
69
- upcast_attention=upcast_attention,
70
- )
71
- return unet_components
72
-
73
- if component_name == "vae":
74
- scaling_factor = kwargs.get("scaling_factor", None)
75
- vae_components = create_diffusers_vae_model_from_ldm(
76
- pipeline_class_name,
77
- original_config,
78
- checkpoint,
79
- image_size,
80
- scaling_factor,
81
- torch_dtype,
82
- model_type=model_type,
83
- )
84
- return vae_components
85
-
86
- if component_name == "scheduler":
87
- scheduler_type = kwargs.get("scheduler_type", "ddim")
88
- prediction_type = kwargs.get("prediction_type", None)
89
-
90
- scheduler_components = create_scheduler_from_ldm(
91
- pipeline_class_name,
92
- original_config,
93
- checkpoint,
94
- scheduler_type=scheduler_type,
95
- prediction_type=prediction_type,
96
- model_type=model_type,
97
- )
98
-
99
- return scheduler_components
100
-
101
- if component_name in ["text_encoder", "text_encoder_2", "tokenizer", "tokenizer_2"]:
102
- text_encoder_components = create_text_encoders_and_tokenizers_from_ldm(
103
- original_config,
104
- checkpoint,
105
- model_type=model_type,
106
- local_files_only=local_files_only,
107
- torch_dtype=torch_dtype,
108
- )
109
- return text_encoder_components
110
-
111
- if component_name == "safety_checker":
112
- if load_safety_checker:
113
- from ..pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
114
-
115
- safety_checker = StableDiffusionSafetyChecker.from_pretrained(
116
- "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only, torch_dtype=torch_dtype
117
- )
118
- else:
119
- safety_checker = None
120
- return {"safety_checker": safety_checker}
121
-
122
- if component_name == "feature_extractor":
123
- if load_safety_checker:
124
- feature_extractor = AutoFeatureExtractor.from_pretrained(
125
- "CompVis/stable-diffusion-safety-checker", local_files_only=local_files_only
126
- )
127
- else:
128
- feature_extractor = None
129
- return {"feature_extractor": feature_extractor}
130
-
131
- return
132
-
133
-
134
- def set_additional_components(
135
- pipeline_class_name,
136
- original_config,
137
- checkpoint=None,
138
- model_type=None,
139
- ):
140
- components = {}
141
- if pipeline_class_name in REFINER_PIPELINES:
142
- model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
143
- is_refiner = model_type == "SDXL-Refiner"
144
- components.update(
145
- {
146
- "requires_aesthetics_score": is_refiner,
147
- "force_zeros_for_empty_prompt": False if is_refiner else True,
148
- }
149
- )
150
-
151
- return components
152
-
153
-
154
- class FromSingleFileMixin:
155
- """
156
- Load model weights saved in the `.ckpt` format into a [`DiffusionPipeline`].
157
- """
158
-
159
- @classmethod
160
- @validate_hf_hub_args
161
- def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
162
- r"""
163
- Instantiate a [`DiffusionPipeline`] from pretrained pipeline weights saved in the `.ckpt` or `.safetensors`
164
- format. The pipeline is set in evaluation mode (`model.eval()`) by default.
165
-
166
- Parameters:
167
- pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
168
- Can be either:
169
- - A link to the `.ckpt` file (for example
170
- `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
171
- - A path to a *file* containing all pipeline weights.
172
- torch_dtype (`str` or `torch.dtype`, *optional*):
173
- Override the default `torch.dtype` and load the model with another dtype.
174
- force_download (`bool`, *optional*, defaults to `False`):
175
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
176
- cached versions if they exist.
177
- cache_dir (`Union[str, os.PathLike]`, *optional*):
178
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
179
- is not used.
180
- resume_download:
181
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
182
- of Diffusers.
183
- proxies (`Dict[str, str]`, *optional*):
184
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
185
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
186
- local_files_only (`bool`, *optional*, defaults to `False`):
187
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
188
- won't be downloaded from the Hub.
189
- token (`str` or *bool*, *optional*):
190
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
191
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
192
- revision (`str`, *optional*, defaults to `"main"`):
193
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
194
- allowed by Git.
195
- original_config_file (`str`, *optional*):
196
- The path to the original config file that was used to train the model. If not provided, the config file
197
- will be inferred from the checkpoint file.
198
- model_type (`str`, *optional*):
199
- The type of model to load. If not provided, the model type will be inferred from the checkpoint file.
200
- image_size (`int`, *optional*):
201
- The size of the image output. It's used to configure the `sample_size` parameter of the UNet and VAE
202
- model.
203
- load_safety_checker (`bool`, *optional*, defaults to `False`):
204
- Whether to load the safety checker model or not. By default, the safety checker is not loaded unless a
205
- `safety_checker` component is passed to the `kwargs`.
206
- num_in_channels (`int`, *optional*):
207
- Specify the number of input channels for the UNet model. Read more about how to configure UNet model
208
- with this parameter
209
- [here](https://huggingface.co/docs/diffusers/training/adapt_a_model#configure-unet2dconditionmodel-parameters).
210
- scaling_factor (`float`, *optional*):
211
- The scaling factor to use for the VAE model. If not provided, it is inferred from the config file
212
- first. If the scaling factor is not found in the config file, the default value 0.18215 is used.
213
- scheduler_type (`str`, *optional*):
214
- The type of scheduler to load. If not provided, the scheduler type will be inferred from the checkpoint
215
- file.
216
- prediction_type (`str`, *optional*):
217
- The type of prediction to load. If not provided, the prediction type will be inferred from the
218
- checkpoint file.
219
- kwargs (remaining dictionary of keyword arguments, *optional*):
220
- Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
221
- class). The overwritten components are passed directly to the pipelines `__init__` method. See example
222
- below for more information.
223
-
224
- Examples:
225
-
226
- ```py
227
- >>> from diffusers import StableDiffusionPipeline
228
-
229
- >>> # Download pipeline from huggingface.co and cache.
230
- >>> pipeline = StableDiffusionPipeline.from_single_file(
231
- ... "https://huggingface.co/WarriorMama777/OrangeMixs/blob/main/Models/AbyssOrangeMix/AbyssOrangeMix.safetensors"
232
- ... )
233
-
234
- >>> # Download pipeline from local file
235
- >>> # file is downloaded under ./v1-5-pruned-emaonly.ckpt
236
- >>> pipeline = StableDiffusionPipeline.from_single_file("./v1-5-pruned-emaonly")
237
-
238
- >>> # Enable float16 and move to GPU
239
- >>> pipeline = StableDiffusionPipeline.from_single_file(
240
- ... "https://huggingface.co/runwayml/stable-diffusion-v1-5/blob/main/v1-5-pruned-emaonly.ckpt",
241
- ... torch_dtype=torch.float16,
242
- ... )
243
- >>> pipeline.to("cuda")
244
- ```
245
- """
246
- original_config_file = kwargs.pop("original_config_file", None)
247
- resume_download = kwargs.pop("resume_download", None)
248
- force_download = kwargs.pop("force_download", False)
249
- proxies = kwargs.pop("proxies", None)
250
- token = kwargs.pop("token", None)
251
- cache_dir = kwargs.pop("cache_dir", None)
252
- local_files_only = kwargs.pop("local_files_only", False)
253
- revision = kwargs.pop("revision", None)
254
- torch_dtype = kwargs.pop("torch_dtype", None)
255
-
256
- class_name = cls.__name__
257
-
258
- original_config, checkpoint = fetch_ldm_config_and_checkpoint(
259
- pretrained_model_link_or_path=pretrained_model_link_or_path,
260
- class_name=class_name,
261
- original_config_file=original_config_file,
262
- resume_download=resume_download,
263
- force_download=force_download,
264
- proxies=proxies,
265
- token=token,
266
- revision=revision,
267
- local_files_only=local_files_only,
268
- cache_dir=cache_dir,
269
- )
270
-
271
- from ..pipelines.pipeline_utils import _get_pipeline_class
272
-
273
- pipeline_class = _get_pipeline_class(
274
- cls,
275
- config=None,
276
- cache_dir=cache_dir,
277
- )
278
-
279
- expected_modules, optional_kwargs = cls._get_signature_keys(pipeline_class)
280
- passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
281
- passed_pipe_kwargs = {k: kwargs.pop(k) for k in optional_kwargs if k in kwargs}
282
-
283
- model_type = kwargs.pop("model_type", None)
284
- image_size = kwargs.pop("image_size", None)
285
- load_safety_checker = (kwargs.pop("load_safety_checker", False)) or (
286
- passed_class_obj.get("safety_checker", None) is not None
287
- )
288
-
289
- init_kwargs = {}
290
- for name in expected_modules:
291
- if name in passed_class_obj:
292
- init_kwargs[name] = passed_class_obj[name]
293
- else:
294
- components = build_sub_model_components(
295
- init_kwargs,
296
- class_name,
297
- name,
298
- original_config,
299
- checkpoint,
300
- model_type=model_type,
301
- image_size=image_size,
302
- load_safety_checker=load_safety_checker,
303
- local_files_only=local_files_only,
304
- torch_dtype=torch_dtype,
305
- **kwargs,
306
- )
307
- if not components:
308
- continue
309
- init_kwargs.update(components)
310
-
311
- additional_components = set_additional_components(
312
- class_name, original_config, checkpoint=checkpoint, model_type=model_type
313
- )
314
- if additional_components:
315
- init_kwargs.update(additional_components)
316
-
317
- init_kwargs.update(passed_pipe_kwargs)
318
- pipe = pipeline_class(**init_kwargs)
319
-
320
- if torch_dtype is not None:
321
- pipe.to(dtype=torch_dtype)
322
-
323
- return pipe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/single_file_utils.py DELETED
@@ -1,1609 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The HuggingFace Inc. team.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """Conversion script for the Stable Diffusion checkpoints."""
16
-
17
- import os
18
- import re
19
- from contextlib import nullcontext
20
- from io import BytesIO
21
- from urllib.parse import urlparse
22
-
23
- import requests
24
- import yaml
25
-
26
- from ..models.modeling_utils import load_state_dict
27
- from ..schedulers import (
28
- DDIMScheduler,
29
- DDPMScheduler,
30
- DPMSolverMultistepScheduler,
31
- EDMDPMSolverMultistepScheduler,
32
- EulerAncestralDiscreteScheduler,
33
- EulerDiscreteScheduler,
34
- HeunDiscreteScheduler,
35
- LMSDiscreteScheduler,
36
- PNDMScheduler,
37
- )
38
- from ..utils import is_accelerate_available, is_transformers_available, logging
39
- from ..utils.hub_utils import _get_model_file
40
-
41
-
42
- if is_transformers_available():
43
- from transformers import (
44
- CLIPTextConfig,
45
- CLIPTextModel,
46
- CLIPTextModelWithProjection,
47
- CLIPTokenizer,
48
- )
49
-
50
- if is_accelerate_available():
51
- from accelerate import init_empty_weights
52
-
53
- from ..models.modeling_utils import load_model_dict_into_meta
54
-
55
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
-
57
- CONFIG_URLS = {
58
- "v1": "https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml",
59
- "v2": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/v2-inference-v.yaml",
60
- "xl": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_base.yaml",
61
- "xl_refiner": "https://raw.githubusercontent.com/Stability-AI/generative-models/main/configs/inference/sd_xl_refiner.yaml",
62
- "upscale": "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml",
63
- "controlnet": "https://raw.githubusercontent.com/lllyasviel/ControlNet/main/models/cldm_v15.yaml",
64
- }
65
-
66
- CHECKPOINT_KEY_NAMES = {
67
- "v2": "model.diffusion_model.input_blocks.2.1.transformer_blocks.0.attn2.to_k.weight",
68
- "xl_base": "conditioner.embedders.1.model.transformer.resblocks.9.mlp.c_proj.bias",
69
- "xl_refiner": "conditioner.embedders.0.model.transformer.resblocks.9.mlp.c_proj.bias",
70
- }
71
-
72
- SCHEDULER_DEFAULT_CONFIG = {
73
- "beta_schedule": "scaled_linear",
74
- "beta_start": 0.00085,
75
- "beta_end": 0.012,
76
- "interpolation_type": "linear",
77
- "num_train_timesteps": 1000,
78
- "prediction_type": "epsilon",
79
- "sample_max_value": 1.0,
80
- "set_alpha_to_one": False,
81
- "skip_prk_steps": True,
82
- "steps_offset": 1,
83
- "timestep_spacing": "leading",
84
- }
85
-
86
-
87
- STABLE_CASCADE_DEFAULT_CONFIGS = {
88
- "stage_c": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior"},
89
- "stage_c_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "prior_lite"},
90
- "stage_b": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder"},
91
- "stage_b_lite": {"pretrained_model_name_or_path": "diffusers/stable-cascade-configs", "subfolder": "decoder_lite"},
92
- }
93
-
94
-
95
- def convert_stable_cascade_unet_single_file_to_diffusers(original_state_dict):
96
- is_stage_c = "clip_txt_mapper.weight" in original_state_dict
97
-
98
- if is_stage_c:
99
- state_dict = {}
100
- for key in original_state_dict.keys():
101
- if key.endswith("in_proj_weight"):
102
- weights = original_state_dict[key].chunk(3, 0)
103
- state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
104
- state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
105
- state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
106
- elif key.endswith("in_proj_bias"):
107
- weights = original_state_dict[key].chunk(3, 0)
108
- state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
109
- state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
110
- state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
111
- elif key.endswith("out_proj.weight"):
112
- weights = original_state_dict[key]
113
- state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
114
- elif key.endswith("out_proj.bias"):
115
- weights = original_state_dict[key]
116
- state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
117
- else:
118
- state_dict[key] = original_state_dict[key]
119
- else:
120
- state_dict = {}
121
- for key in original_state_dict.keys():
122
- if key.endswith("in_proj_weight"):
123
- weights = original_state_dict[key].chunk(3, 0)
124
- state_dict[key.replace("attn.in_proj_weight", "to_q.weight")] = weights[0]
125
- state_dict[key.replace("attn.in_proj_weight", "to_k.weight")] = weights[1]
126
- state_dict[key.replace("attn.in_proj_weight", "to_v.weight")] = weights[2]
127
- elif key.endswith("in_proj_bias"):
128
- weights = original_state_dict[key].chunk(3, 0)
129
- state_dict[key.replace("attn.in_proj_bias", "to_q.bias")] = weights[0]
130
- state_dict[key.replace("attn.in_proj_bias", "to_k.bias")] = weights[1]
131
- state_dict[key.replace("attn.in_proj_bias", "to_v.bias")] = weights[2]
132
- elif key.endswith("out_proj.weight"):
133
- weights = original_state_dict[key]
134
- state_dict[key.replace("attn.out_proj.weight", "to_out.0.weight")] = weights
135
- elif key.endswith("out_proj.bias"):
136
- weights = original_state_dict[key]
137
- state_dict[key.replace("attn.out_proj.bias", "to_out.0.bias")] = weights
138
- # rename clip_mapper to clip_txt_pooled_mapper
139
- elif key.endswith("clip_mapper.weight"):
140
- weights = original_state_dict[key]
141
- state_dict[key.replace("clip_mapper.weight", "clip_txt_pooled_mapper.weight")] = weights
142
- elif key.endswith("clip_mapper.bias"):
143
- weights = original_state_dict[key]
144
- state_dict[key.replace("clip_mapper.bias", "clip_txt_pooled_mapper.bias")] = weights
145
- else:
146
- state_dict[key] = original_state_dict[key]
147
-
148
- return state_dict
149
-
150
-
151
- def infer_stable_cascade_single_file_config(checkpoint):
152
- is_stage_c = "clip_txt_mapper.weight" in checkpoint
153
- is_stage_b = "down_blocks.1.0.channelwise.0.weight" in checkpoint
154
-
155
- if is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 1536):
156
- config_type = "stage_c_lite"
157
- elif is_stage_c and (checkpoint["clip_txt_mapper.weight"].shape[0] == 2048):
158
- config_type = "stage_c"
159
- elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 576:
160
- config_type = "stage_b_lite"
161
- elif is_stage_b and checkpoint["down_blocks.1.0.channelwise.0.weight"].shape[-1] == 640:
162
- config_type = "stage_b"
163
-
164
- return STABLE_CASCADE_DEFAULT_CONFIGS[config_type]
165
-
166
-
167
- DIFFUSERS_TO_LDM_MAPPING = {
168
- "unet": {
169
- "layers": {
170
- "time_embedding.linear_1.weight": "time_embed.0.weight",
171
- "time_embedding.linear_1.bias": "time_embed.0.bias",
172
- "time_embedding.linear_2.weight": "time_embed.2.weight",
173
- "time_embedding.linear_2.bias": "time_embed.2.bias",
174
- "conv_in.weight": "input_blocks.0.0.weight",
175
- "conv_in.bias": "input_blocks.0.0.bias",
176
- "conv_norm_out.weight": "out.0.weight",
177
- "conv_norm_out.bias": "out.0.bias",
178
- "conv_out.weight": "out.2.weight",
179
- "conv_out.bias": "out.2.bias",
180
- },
181
- "class_embed_type": {
182
- "class_embedding.linear_1.weight": "label_emb.0.0.weight",
183
- "class_embedding.linear_1.bias": "label_emb.0.0.bias",
184
- "class_embedding.linear_2.weight": "label_emb.0.2.weight",
185
- "class_embedding.linear_2.bias": "label_emb.0.2.bias",
186
- },
187
- "addition_embed_type": {
188
- "add_embedding.linear_1.weight": "label_emb.0.0.weight",
189
- "add_embedding.linear_1.bias": "label_emb.0.0.bias",
190
- "add_embedding.linear_2.weight": "label_emb.0.2.weight",
191
- "add_embedding.linear_2.bias": "label_emb.0.2.bias",
192
- },
193
- },
194
- "controlnet": {
195
- "layers": {
196
- "time_embedding.linear_1.weight": "time_embed.0.weight",
197
- "time_embedding.linear_1.bias": "time_embed.0.bias",
198
- "time_embedding.linear_2.weight": "time_embed.2.weight",
199
- "time_embedding.linear_2.bias": "time_embed.2.bias",
200
- "conv_in.weight": "input_blocks.0.0.weight",
201
- "conv_in.bias": "input_blocks.0.0.bias",
202
- "controlnet_cond_embedding.conv_in.weight": "input_hint_block.0.weight",
203
- "controlnet_cond_embedding.conv_in.bias": "input_hint_block.0.bias",
204
- "controlnet_cond_embedding.conv_out.weight": "input_hint_block.14.weight",
205
- "controlnet_cond_embedding.conv_out.bias": "input_hint_block.14.bias",
206
- },
207
- "class_embed_type": {
208
- "class_embedding.linear_1.weight": "label_emb.0.0.weight",
209
- "class_embedding.linear_1.bias": "label_emb.0.0.bias",
210
- "class_embedding.linear_2.weight": "label_emb.0.2.weight",
211
- "class_embedding.linear_2.bias": "label_emb.0.2.bias",
212
- },
213
- "addition_embed_type": {
214
- "add_embedding.linear_1.weight": "label_emb.0.0.weight",
215
- "add_embedding.linear_1.bias": "label_emb.0.0.bias",
216
- "add_embedding.linear_2.weight": "label_emb.0.2.weight",
217
- "add_embedding.linear_2.bias": "label_emb.0.2.bias",
218
- },
219
- },
220
- "vae": {
221
- "encoder.conv_in.weight": "encoder.conv_in.weight",
222
- "encoder.conv_in.bias": "encoder.conv_in.bias",
223
- "encoder.conv_out.weight": "encoder.conv_out.weight",
224
- "encoder.conv_out.bias": "encoder.conv_out.bias",
225
- "encoder.conv_norm_out.weight": "encoder.norm_out.weight",
226
- "encoder.conv_norm_out.bias": "encoder.norm_out.bias",
227
- "decoder.conv_in.weight": "decoder.conv_in.weight",
228
- "decoder.conv_in.bias": "decoder.conv_in.bias",
229
- "decoder.conv_out.weight": "decoder.conv_out.weight",
230
- "decoder.conv_out.bias": "decoder.conv_out.bias",
231
- "decoder.conv_norm_out.weight": "decoder.norm_out.weight",
232
- "decoder.conv_norm_out.bias": "decoder.norm_out.bias",
233
- "quant_conv.weight": "quant_conv.weight",
234
- "quant_conv.bias": "quant_conv.bias",
235
- "post_quant_conv.weight": "post_quant_conv.weight",
236
- "post_quant_conv.bias": "post_quant_conv.bias",
237
- },
238
- "openclip": {
239
- "layers": {
240
- "text_model.embeddings.position_embedding.weight": "positional_embedding",
241
- "text_model.embeddings.token_embedding.weight": "token_embedding.weight",
242
- "text_model.final_layer_norm.weight": "ln_final.weight",
243
- "text_model.final_layer_norm.bias": "ln_final.bias",
244
- "text_projection.weight": "text_projection",
245
- },
246
- "transformer": {
247
- "text_model.encoder.layers.": "resblocks.",
248
- "layer_norm1": "ln_1",
249
- "layer_norm2": "ln_2",
250
- ".fc1.": ".c_fc.",
251
- ".fc2.": ".c_proj.",
252
- ".self_attn": ".attn",
253
- "transformer.text_model.final_layer_norm.": "ln_final.",
254
- "transformer.text_model.embeddings.token_embedding.weight": "token_embedding.weight",
255
- "transformer.text_model.embeddings.position_embedding.weight": "positional_embedding",
256
- },
257
- },
258
- }
259
-
260
- LDM_VAE_KEY = "first_stage_model."
261
- LDM_VAE_DEFAULT_SCALING_FACTOR = 0.18215
262
- PLAYGROUND_VAE_SCALING_FACTOR = 0.5
263
- LDM_UNET_KEY = "model.diffusion_model."
264
- LDM_CONTROLNET_KEY = "control_model."
265
- LDM_CLIP_PREFIX_TO_REMOVE = ["cond_stage_model.transformer.", "conditioner.embedders.0.transformer."]
266
- LDM_OPEN_CLIP_TEXT_PROJECTION_DIM = 1024
267
-
268
- SD_2_TEXT_ENCODER_KEYS_TO_IGNORE = [
269
- "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_bias",
270
- "cond_stage_model.model.transformer.resblocks.23.attn.in_proj_weight",
271
- "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.bias",
272
- "cond_stage_model.model.transformer.resblocks.23.attn.out_proj.weight",
273
- "cond_stage_model.model.transformer.resblocks.23.ln_1.bias",
274
- "cond_stage_model.model.transformer.resblocks.23.ln_1.weight",
275
- "cond_stage_model.model.transformer.resblocks.23.ln_2.bias",
276
- "cond_stage_model.model.transformer.resblocks.23.ln_2.weight",
277
- "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.bias",
278
- "cond_stage_model.model.transformer.resblocks.23.mlp.c_fc.weight",
279
- "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.bias",
280
- "cond_stage_model.model.transformer.resblocks.23.mlp.c_proj.weight",
281
- "cond_stage_model.model.text_projection",
282
- ]
283
-
284
-
285
- VALID_URL_PREFIXES = ["https://huggingface.co/", "huggingface.co/", "hf.co/", "https://hf.co/"]
286
-
287
-
288
- def _extract_repo_id_and_weights_name(pretrained_model_name_or_path):
289
- pattern = r"([^/]+)/([^/]+)/(?:blob/main/)?(.+)"
290
- weights_name = None
291
- repo_id = (None,)
292
- for prefix in VALID_URL_PREFIXES:
293
- pretrained_model_name_or_path = pretrained_model_name_or_path.replace(prefix, "")
294
- match = re.match(pattern, pretrained_model_name_or_path)
295
- if not match:
296
- return repo_id, weights_name
297
-
298
- repo_id = f"{match.group(1)}/{match.group(2)}"
299
- weights_name = match.group(3)
300
-
301
- return repo_id, weights_name
302
-
303
-
304
- def fetch_ldm_config_and_checkpoint(
305
- pretrained_model_link_or_path,
306
- class_name,
307
- original_config_file=None,
308
- resume_download=None,
309
- force_download=False,
310
- proxies=None,
311
- token=None,
312
- cache_dir=None,
313
- local_files_only=None,
314
- revision=None,
315
- ):
316
- checkpoint = load_single_file_model_checkpoint(
317
- pretrained_model_link_or_path,
318
- resume_download=resume_download,
319
- force_download=force_download,
320
- proxies=proxies,
321
- token=token,
322
- cache_dir=cache_dir,
323
- local_files_only=local_files_only,
324
- revision=revision,
325
- )
326
- original_config = fetch_original_config(class_name, checkpoint, original_config_file)
327
-
328
- return original_config, checkpoint
329
-
330
-
331
- def load_single_file_model_checkpoint(
332
- pretrained_model_link_or_path,
333
- resume_download=False,
334
- force_download=False,
335
- proxies=None,
336
- token=None,
337
- cache_dir=None,
338
- local_files_only=None,
339
- revision=None,
340
- ):
341
- if os.path.isfile(pretrained_model_link_or_path):
342
- checkpoint = load_state_dict(pretrained_model_link_or_path)
343
- else:
344
- repo_id, weights_name = _extract_repo_id_and_weights_name(pretrained_model_link_or_path)
345
- checkpoint_path = _get_model_file(
346
- repo_id,
347
- weights_name=weights_name,
348
- force_download=force_download,
349
- cache_dir=cache_dir,
350
- resume_download=resume_download,
351
- proxies=proxies,
352
- local_files_only=local_files_only,
353
- token=token,
354
- revision=revision,
355
- )
356
- checkpoint = load_state_dict(checkpoint_path)
357
-
358
- # some checkpoints contain the model state dict under a "state_dict" key
359
- while "state_dict" in checkpoint:
360
- checkpoint = checkpoint["state_dict"]
361
-
362
- return checkpoint
363
-
364
-
365
- def infer_original_config_file(class_name, checkpoint):
366
- if CHECKPOINT_KEY_NAMES["v2"] in checkpoint and checkpoint[CHECKPOINT_KEY_NAMES["v2"]].shape[-1] == 1024:
367
- config_url = CONFIG_URLS["v2"]
368
-
369
- elif CHECKPOINT_KEY_NAMES["xl_base"] in checkpoint:
370
- config_url = CONFIG_URLS["xl"]
371
-
372
- elif CHECKPOINT_KEY_NAMES["xl_refiner"] in checkpoint:
373
- config_url = CONFIG_URLS["xl_refiner"]
374
-
375
- elif class_name == "StableDiffusionUpscalePipeline":
376
- config_url = CONFIG_URLS["upscale"]
377
-
378
- elif class_name == "ControlNetModel":
379
- config_url = CONFIG_URLS["controlnet"]
380
-
381
- else:
382
- config_url = CONFIG_URLS["v1"]
383
-
384
- original_config_file = BytesIO(requests.get(config_url).content)
385
-
386
- return original_config_file
387
-
388
-
389
- def fetch_original_config(pipeline_class_name, checkpoint, original_config_file=None):
390
- def is_valid_url(url):
391
- result = urlparse(url)
392
- if result.scheme and result.netloc:
393
- return True
394
-
395
- return False
396
-
397
- if original_config_file is None:
398
- original_config_file = infer_original_config_file(pipeline_class_name, checkpoint)
399
-
400
- elif os.path.isfile(original_config_file):
401
- with open(original_config_file, "r") as fp:
402
- original_config_file = fp.read()
403
-
404
- elif is_valid_url(original_config_file):
405
- original_config_file = BytesIO(requests.get(original_config_file).content)
406
-
407
- else:
408
- raise ValueError("Invalid `original_config_file` provided. Please set it to a valid file path or URL.")
409
-
410
- original_config = yaml.safe_load(original_config_file)
411
-
412
- return original_config
413
-
414
-
415
- def infer_model_type(original_config, checkpoint, model_type=None):
416
- if model_type is not None:
417
- return model_type
418
-
419
- has_cond_stage_config = (
420
- "cond_stage_config" in original_config["model"]["params"]
421
- and original_config["model"]["params"]["cond_stage_config"] is not None
422
- )
423
- has_network_config = (
424
- "network_config" in original_config["model"]["params"]
425
- and original_config["model"]["params"]["network_config"] is not None
426
- )
427
-
428
- if has_cond_stage_config:
429
- model_type = original_config["model"]["params"]["cond_stage_config"]["target"].split(".")[-1]
430
-
431
- elif has_network_config:
432
- context_dim = original_config["model"]["params"]["network_config"]["params"]["context_dim"]
433
- if "edm_mean" in checkpoint and "edm_std" in checkpoint:
434
- model_type = "Playground"
435
- elif context_dim == 2048:
436
- model_type = "SDXL"
437
- else:
438
- model_type = "SDXL-Refiner"
439
- else:
440
- raise ValueError("Unable to infer model type from config")
441
-
442
- logger.debug(f"No `model_type` given, `model_type` inferred as: {model_type}")
443
-
444
- return model_type
445
-
446
-
447
- def get_default_scheduler_config():
448
- return SCHEDULER_DEFAULT_CONFIG
449
-
450
-
451
- def set_image_size(pipeline_class_name, original_config, checkpoint, image_size=None, model_type=None):
452
- if image_size:
453
- return image_size
454
-
455
- global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
456
- model_type = infer_model_type(original_config, checkpoint, model_type)
457
-
458
- if pipeline_class_name == "StableDiffusionUpscalePipeline":
459
- image_size = original_config["model"]["params"]["unet_config"]["params"]["image_size"]
460
- return image_size
461
-
462
- elif model_type in ["SDXL", "SDXL-Refiner", "Playground"]:
463
- image_size = 1024
464
- return image_size
465
-
466
- elif (
467
- "parameterization" in original_config["model"]["params"]
468
- and original_config["model"]["params"]["parameterization"] == "v"
469
- ):
470
- # NOTE: For stable diffusion 2 base one has to pass `image_size==512`
471
- # as it relies on a brittle global step parameter here
472
- image_size = 512 if global_step == 875000 else 768
473
- return image_size
474
-
475
- else:
476
- image_size = 512
477
- return image_size
478
-
479
-
480
- # Copied from diffusers.pipelines.stable_diffusion.convert_from_ckpt.conv_attn_to_linear
481
- def conv_attn_to_linear(checkpoint):
482
- keys = list(checkpoint.keys())
483
- attn_keys = ["query.weight", "key.weight", "value.weight"]
484
- for key in keys:
485
- if ".".join(key.split(".")[-2:]) in attn_keys:
486
- if checkpoint[key].ndim > 2:
487
- checkpoint[key] = checkpoint[key][:, :, 0, 0]
488
- elif "proj_attn.weight" in key:
489
- if checkpoint[key].ndim > 2:
490
- checkpoint[key] = checkpoint[key][:, :, 0]
491
-
492
-
493
- def create_unet_diffusers_config(original_config, image_size: int):
494
- """
495
- Creates a config for the diffusers based on the config of the LDM model.
496
- """
497
- if (
498
- "unet_config" in original_config["model"]["params"]
499
- and original_config["model"]["params"]["unet_config"] is not None
500
- ):
501
- unet_params = original_config["model"]["params"]["unet_config"]["params"]
502
- else:
503
- unet_params = original_config["model"]["params"]["network_config"]["params"]
504
-
505
- vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
506
- block_out_channels = [unet_params["model_channels"] * mult for mult in unet_params["channel_mult"]]
507
-
508
- down_block_types = []
509
- resolution = 1
510
- for i in range(len(block_out_channels)):
511
- block_type = "CrossAttnDownBlock2D" if resolution in unet_params["attention_resolutions"] else "DownBlock2D"
512
- down_block_types.append(block_type)
513
- if i != len(block_out_channels) - 1:
514
- resolution *= 2
515
-
516
- up_block_types = []
517
- for i in range(len(block_out_channels)):
518
- block_type = "CrossAttnUpBlock2D" if resolution in unet_params["attention_resolutions"] else "UpBlock2D"
519
- up_block_types.append(block_type)
520
- resolution //= 2
521
-
522
- if unet_params["transformer_depth"] is not None:
523
- transformer_layers_per_block = (
524
- unet_params["transformer_depth"]
525
- if isinstance(unet_params["transformer_depth"], int)
526
- else list(unet_params["transformer_depth"])
527
- )
528
- else:
529
- transformer_layers_per_block = 1
530
-
531
- vae_scale_factor = 2 ** (len(vae_params["ch_mult"]) - 1)
532
-
533
- head_dim = unet_params["num_heads"] if "num_heads" in unet_params else None
534
- use_linear_projection = (
535
- unet_params["use_linear_in_transformer"] if "use_linear_in_transformer" in unet_params else False
536
- )
537
- if use_linear_projection:
538
- # stable diffusion 2-base-512 and 2-768
539
- if head_dim is None:
540
- head_dim_mult = unet_params["model_channels"] // unet_params["num_head_channels"]
541
- head_dim = [head_dim_mult * c for c in list(unet_params["channel_mult"])]
542
-
543
- class_embed_type = None
544
- addition_embed_type = None
545
- addition_time_embed_dim = None
546
- projection_class_embeddings_input_dim = None
547
- context_dim = None
548
-
549
- if unet_params["context_dim"] is not None:
550
- context_dim = (
551
- unet_params["context_dim"]
552
- if isinstance(unet_params["context_dim"], int)
553
- else unet_params["context_dim"][0]
554
- )
555
-
556
- if "num_classes" in unet_params:
557
- if unet_params["num_classes"] == "sequential":
558
- if context_dim in [2048, 1280]:
559
- # SDXL
560
- addition_embed_type = "text_time"
561
- addition_time_embed_dim = 256
562
- else:
563
- class_embed_type = "projection"
564
- assert "adm_in_channels" in unet_params
565
- projection_class_embeddings_input_dim = unet_params["adm_in_channels"]
566
-
567
- config = {
568
- "sample_size": image_size // vae_scale_factor,
569
- "in_channels": unet_params["in_channels"],
570
- "down_block_types": down_block_types,
571
- "block_out_channels": block_out_channels,
572
- "layers_per_block": unet_params["num_res_blocks"],
573
- "cross_attention_dim": context_dim,
574
- "attention_head_dim": head_dim,
575
- "use_linear_projection": use_linear_projection,
576
- "class_embed_type": class_embed_type,
577
- "addition_embed_type": addition_embed_type,
578
- "addition_time_embed_dim": addition_time_embed_dim,
579
- "projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
580
- "transformer_layers_per_block": transformer_layers_per_block,
581
- }
582
-
583
- if "disable_self_attentions" in unet_params:
584
- config["only_cross_attention"] = unet_params["disable_self_attentions"]
585
-
586
- if "num_classes" in unet_params and isinstance(unet_params["num_classes"], int):
587
- config["num_class_embeds"] = unet_params["num_classes"]
588
-
589
- config["out_channels"] = unet_params["out_channels"]
590
- config["up_block_types"] = up_block_types
591
-
592
- return config
593
-
594
-
595
- def create_controlnet_diffusers_config(original_config, image_size: int):
596
- unet_params = original_config["model"]["params"]["control_stage_config"]["params"]
597
- diffusers_unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
598
-
599
- controlnet_config = {
600
- "conditioning_channels": unet_params["hint_channels"],
601
- "in_channels": diffusers_unet_config["in_channels"],
602
- "down_block_types": diffusers_unet_config["down_block_types"],
603
- "block_out_channels": diffusers_unet_config["block_out_channels"],
604
- "layers_per_block": diffusers_unet_config["layers_per_block"],
605
- "cross_attention_dim": diffusers_unet_config["cross_attention_dim"],
606
- "attention_head_dim": diffusers_unet_config["attention_head_dim"],
607
- "use_linear_projection": diffusers_unet_config["use_linear_projection"],
608
- "class_embed_type": diffusers_unet_config["class_embed_type"],
609
- "addition_embed_type": diffusers_unet_config["addition_embed_type"],
610
- "addition_time_embed_dim": diffusers_unet_config["addition_time_embed_dim"],
611
- "projection_class_embeddings_input_dim": diffusers_unet_config["projection_class_embeddings_input_dim"],
612
- "transformer_layers_per_block": diffusers_unet_config["transformer_layers_per_block"],
613
- }
614
-
615
- return controlnet_config
616
-
617
-
618
- def create_vae_diffusers_config(original_config, image_size, scaling_factor=None, latents_mean=None, latents_std=None):
619
- """
620
- Creates a config for the diffusers based on the config of the LDM model.
621
- """
622
- vae_params = original_config["model"]["params"]["first_stage_config"]["params"]["ddconfig"]
623
- if (scaling_factor is None) and (latents_mean is not None) and (latents_std is not None):
624
- scaling_factor = PLAYGROUND_VAE_SCALING_FACTOR
625
- elif (scaling_factor is None) and ("scale_factor" in original_config["model"]["params"]):
626
- scaling_factor = original_config["model"]["params"]["scale_factor"]
627
- elif scaling_factor is None:
628
- scaling_factor = LDM_VAE_DEFAULT_SCALING_FACTOR
629
-
630
- block_out_channels = [vae_params["ch"] * mult for mult in vae_params["ch_mult"]]
631
- down_block_types = ["DownEncoderBlock2D"] * len(block_out_channels)
632
- up_block_types = ["UpDecoderBlock2D"] * len(block_out_channels)
633
-
634
- config = {
635
- "sample_size": image_size,
636
- "in_channels": vae_params["in_channels"],
637
- "out_channels": vae_params["out_ch"],
638
- "down_block_types": down_block_types,
639
- "up_block_types": up_block_types,
640
- "block_out_channels": block_out_channels,
641
- "latent_channels": vae_params["z_channels"],
642
- "layers_per_block": vae_params["num_res_blocks"],
643
- "scaling_factor": scaling_factor,
644
- }
645
- if latents_mean is not None and latents_std is not None:
646
- config.update({"latents_mean": latents_mean, "latents_std": latents_std})
647
-
648
- return config
649
-
650
-
651
- def update_unet_resnet_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping=None):
652
- for ldm_key in ldm_keys:
653
- diffusers_key = (
654
- ldm_key.replace("in_layers.0", "norm1")
655
- .replace("in_layers.2", "conv1")
656
- .replace("out_layers.0", "norm2")
657
- .replace("out_layers.3", "conv2")
658
- .replace("emb_layers.1", "time_emb_proj")
659
- .replace("skip_connection", "conv_shortcut")
660
- )
661
- if mapping:
662
- diffusers_key = diffusers_key.replace(mapping["old"], mapping["new"])
663
- new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
664
-
665
-
666
- def update_unet_attention_ldm_to_diffusers(ldm_keys, new_checkpoint, checkpoint, mapping):
667
- for ldm_key in ldm_keys:
668
- diffusers_key = ldm_key.replace(mapping["old"], mapping["new"])
669
- new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
670
-
671
-
672
- def convert_ldm_unet_checkpoint(checkpoint, config, extract_ema=False):
673
- """
674
- Takes a state dict and a config, and returns a converted checkpoint.
675
- """
676
- # extract state_dict for UNet
677
- unet_state_dict = {}
678
- keys = list(checkpoint.keys())
679
- unet_key = LDM_UNET_KEY
680
-
681
- # at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
682
- if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
683
- logger.warning("Checkpoint has both EMA and non-EMA weights.")
684
- logger.warning(
685
- "In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
686
- " weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
687
- )
688
- for key in keys:
689
- if key.startswith("model.diffusion_model"):
690
- flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
691
- unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
692
- else:
693
- if sum(k.startswith("model_ema") for k in keys) > 100:
694
- logger.warning(
695
- "In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
696
- " weights (usually better for inference), please make sure to add the `--extract_ema` flag."
697
- )
698
- for key in keys:
699
- if key.startswith(unet_key):
700
- unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
701
-
702
- new_checkpoint = {}
703
- ldm_unet_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["layers"]
704
- for diffusers_key, ldm_key in ldm_unet_keys.items():
705
- if ldm_key not in unet_state_dict:
706
- continue
707
- new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
708
-
709
- if ("class_embed_type" in config) and (config["class_embed_type"] in ["timestep", "projection"]):
710
- class_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["class_embed_type"]
711
- for diffusers_key, ldm_key in class_embed_keys.items():
712
- new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
713
-
714
- if ("addition_embed_type" in config) and (config["addition_embed_type"] == "text_time"):
715
- addition_embed_keys = DIFFUSERS_TO_LDM_MAPPING["unet"]["addition_embed_type"]
716
- for diffusers_key, ldm_key in addition_embed_keys.items():
717
- new_checkpoint[diffusers_key] = unet_state_dict[ldm_key]
718
-
719
- # Relevant to StableDiffusionUpscalePipeline
720
- if "num_class_embeds" in config:
721
- if (config["num_class_embeds"] is not None) and ("label_emb.weight" in unet_state_dict):
722
- new_checkpoint["class_embedding.weight"] = unet_state_dict["label_emb.weight"]
723
-
724
- # Retrieves the keys for the input blocks only
725
- num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
726
- input_blocks = {
727
- layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
728
- for layer_id in range(num_input_blocks)
729
- }
730
-
731
- # Retrieves the keys for the middle blocks only
732
- num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
733
- middle_blocks = {
734
- layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
735
- for layer_id in range(num_middle_blocks)
736
- }
737
-
738
- # Retrieves the keys for the output blocks only
739
- num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
740
- output_blocks = {
741
- layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
742
- for layer_id in range(num_output_blocks)
743
- }
744
-
745
- # Down blocks
746
- for i in range(1, num_input_blocks):
747
- block_id = (i - 1) // (config["layers_per_block"] + 1)
748
- layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
749
-
750
- resnets = [
751
- key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
752
- ]
753
- update_unet_resnet_ldm_to_diffusers(
754
- resnets,
755
- new_checkpoint,
756
- unet_state_dict,
757
- {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
758
- )
759
-
760
- if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
761
- new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
762
- f"input_blocks.{i}.0.op.weight"
763
- )
764
- new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
765
- f"input_blocks.{i}.0.op.bias"
766
- )
767
-
768
- attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
769
- if attentions:
770
- update_unet_attention_ldm_to_diffusers(
771
- attentions,
772
- new_checkpoint,
773
- unet_state_dict,
774
- {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
775
- )
776
-
777
- # Mid blocks
778
- resnet_0 = middle_blocks[0]
779
- attentions = middle_blocks[1]
780
- resnet_1 = middle_blocks[2]
781
-
782
- update_unet_resnet_ldm_to_diffusers(
783
- resnet_0, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"}
784
- )
785
- update_unet_resnet_ldm_to_diffusers(
786
- resnet_1, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"}
787
- )
788
- update_unet_attention_ldm_to_diffusers(
789
- attentions, new_checkpoint, unet_state_dict, mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"}
790
- )
791
-
792
- # Up Blocks
793
- for i in range(num_output_blocks):
794
- block_id = i // (config["layers_per_block"] + 1)
795
- layer_in_block_id = i % (config["layers_per_block"] + 1)
796
-
797
- resnets = [
798
- key for key in output_blocks[i] if f"output_blocks.{i}.0" in key and f"output_blocks.{i}.0.op" not in key
799
- ]
800
- update_unet_resnet_ldm_to_diffusers(
801
- resnets,
802
- new_checkpoint,
803
- unet_state_dict,
804
- {"old": f"output_blocks.{i}.0", "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}"},
805
- )
806
-
807
- attentions = [
808
- key for key in output_blocks[i] if f"output_blocks.{i}.1" in key and f"output_blocks.{i}.1.conv" not in key
809
- ]
810
- if attentions:
811
- update_unet_attention_ldm_to_diffusers(
812
- attentions,
813
- new_checkpoint,
814
- unet_state_dict,
815
- {"old": f"output_blocks.{i}.1", "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}"},
816
- )
817
-
818
- if f"output_blocks.{i}.1.conv.weight" in unet_state_dict:
819
- new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
820
- f"output_blocks.{i}.1.conv.weight"
821
- ]
822
- new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
823
- f"output_blocks.{i}.1.conv.bias"
824
- ]
825
- if f"output_blocks.{i}.2.conv.weight" in unet_state_dict:
826
- new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
827
- f"output_blocks.{i}.2.conv.weight"
828
- ]
829
- new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
830
- f"output_blocks.{i}.2.conv.bias"
831
- ]
832
-
833
- return new_checkpoint
834
-
835
-
836
- def convert_controlnet_checkpoint(
837
- checkpoint,
838
- config,
839
- ):
840
- # Some controlnet ckpt files are distributed independently from the rest of the
841
- # model components i.e. https://huggingface.co/thibaud/controlnet-sd21/
842
- if "time_embed.0.weight" in checkpoint:
843
- controlnet_state_dict = checkpoint
844
-
845
- else:
846
- controlnet_state_dict = {}
847
- keys = list(checkpoint.keys())
848
- controlnet_key = LDM_CONTROLNET_KEY
849
- for key in keys:
850
- if key.startswith(controlnet_key):
851
- controlnet_state_dict[key.replace(controlnet_key, "")] = checkpoint.pop(key)
852
-
853
- new_checkpoint = {}
854
- ldm_controlnet_keys = DIFFUSERS_TO_LDM_MAPPING["controlnet"]["layers"]
855
- for diffusers_key, ldm_key in ldm_controlnet_keys.items():
856
- if ldm_key not in controlnet_state_dict:
857
- continue
858
- new_checkpoint[diffusers_key] = controlnet_state_dict[ldm_key]
859
-
860
- # Retrieves the keys for the input blocks only
861
- num_input_blocks = len(
862
- {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "input_blocks" in layer}
863
- )
864
- input_blocks = {
865
- layer_id: [key for key in controlnet_state_dict if f"input_blocks.{layer_id}" in key]
866
- for layer_id in range(num_input_blocks)
867
- }
868
-
869
- # Down blocks
870
- for i in range(1, num_input_blocks):
871
- block_id = (i - 1) // (config["layers_per_block"] + 1)
872
- layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
873
-
874
- resnets = [
875
- key for key in input_blocks[i] if f"input_blocks.{i}.0" in key and f"input_blocks.{i}.0.op" not in key
876
- ]
877
- update_unet_resnet_ldm_to_diffusers(
878
- resnets,
879
- new_checkpoint,
880
- controlnet_state_dict,
881
- {"old": f"input_blocks.{i}.0", "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}"},
882
- )
883
-
884
- if f"input_blocks.{i}.0.op.weight" in controlnet_state_dict:
885
- new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = controlnet_state_dict.pop(
886
- f"input_blocks.{i}.0.op.weight"
887
- )
888
- new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = controlnet_state_dict.pop(
889
- f"input_blocks.{i}.0.op.bias"
890
- )
891
-
892
- attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
893
- if attentions:
894
- update_unet_attention_ldm_to_diffusers(
895
- attentions,
896
- new_checkpoint,
897
- controlnet_state_dict,
898
- {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"},
899
- )
900
-
901
- # controlnet down blocks
902
- for i in range(num_input_blocks):
903
- new_checkpoint[f"controlnet_down_blocks.{i}.weight"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.weight")
904
- new_checkpoint[f"controlnet_down_blocks.{i}.bias"] = controlnet_state_dict.pop(f"zero_convs.{i}.0.bias")
905
-
906
- # Retrieves the keys for the middle blocks only
907
- num_middle_blocks = len(
908
- {".".join(layer.split(".")[:2]) for layer in controlnet_state_dict if "middle_block" in layer}
909
- )
910
- middle_blocks = {
911
- layer_id: [key for key in controlnet_state_dict if f"middle_block.{layer_id}" in key]
912
- for layer_id in range(num_middle_blocks)
913
- }
914
- if middle_blocks:
915
- resnet_0 = middle_blocks[0]
916
- attentions = middle_blocks[1]
917
- resnet_1 = middle_blocks[2]
918
-
919
- update_unet_resnet_ldm_to_diffusers(
920
- resnet_0,
921
- new_checkpoint,
922
- controlnet_state_dict,
923
- mapping={"old": "middle_block.0", "new": "mid_block.resnets.0"},
924
- )
925
- update_unet_resnet_ldm_to_diffusers(
926
- resnet_1,
927
- new_checkpoint,
928
- controlnet_state_dict,
929
- mapping={"old": "middle_block.2", "new": "mid_block.resnets.1"},
930
- )
931
- update_unet_attention_ldm_to_diffusers(
932
- attentions,
933
- new_checkpoint,
934
- controlnet_state_dict,
935
- mapping={"old": "middle_block.1", "new": "mid_block.attentions.0"},
936
- )
937
-
938
- # mid block
939
- new_checkpoint["controlnet_mid_block.weight"] = controlnet_state_dict.pop("middle_block_out.0.weight")
940
- new_checkpoint["controlnet_mid_block.bias"] = controlnet_state_dict.pop("middle_block_out.0.bias")
941
-
942
- # controlnet cond embedding blocks
943
- cond_embedding_blocks = {
944
- ".".join(layer.split(".")[:2])
945
- for layer in controlnet_state_dict
946
- if "input_hint_block" in layer and ("input_hint_block.0" not in layer) and ("input_hint_block.14" not in layer)
947
- }
948
- num_cond_embedding_blocks = len(cond_embedding_blocks)
949
-
950
- for idx in range(1, num_cond_embedding_blocks + 1):
951
- diffusers_idx = idx - 1
952
- cond_block_id = 2 * idx
953
-
954
- new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.weight"] = controlnet_state_dict.pop(
955
- f"input_hint_block.{cond_block_id}.weight"
956
- )
957
- new_checkpoint[f"controlnet_cond_embedding.blocks.{diffusers_idx}.bias"] = controlnet_state_dict.pop(
958
- f"input_hint_block.{cond_block_id}.bias"
959
- )
960
-
961
- return new_checkpoint
962
-
963
-
964
- def create_diffusers_controlnet_model_from_ldm(
965
- pipeline_class_name, original_config, checkpoint, upcast_attention=False, image_size=None, torch_dtype=None
966
- ):
967
- # import here to avoid circular imports
968
- from ..models import ControlNetModel
969
-
970
- image_size = set_image_size(pipeline_class_name, original_config, checkpoint, image_size=image_size)
971
-
972
- diffusers_config = create_controlnet_diffusers_config(original_config, image_size=image_size)
973
- diffusers_config["upcast_attention"] = upcast_attention
974
-
975
- diffusers_format_controlnet_checkpoint = convert_controlnet_checkpoint(checkpoint, diffusers_config)
976
-
977
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
978
- with ctx():
979
- controlnet = ControlNetModel(**diffusers_config)
980
-
981
- if is_accelerate_available():
982
- unexpected_keys = load_model_dict_into_meta(
983
- controlnet, diffusers_format_controlnet_checkpoint, dtype=torch_dtype
984
- )
985
- if controlnet._keys_to_ignore_on_load_unexpected is not None:
986
- for pat in controlnet._keys_to_ignore_on_load_unexpected:
987
- unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
988
-
989
- if len(unexpected_keys) > 0:
990
- logger.warning(
991
- f"Some weights of the model checkpoint were not used when initializing {controlnet.__name__}: \n {[', '.join(unexpected_keys)]}"
992
- )
993
- else:
994
- controlnet.load_state_dict(diffusers_format_controlnet_checkpoint)
995
-
996
- if torch_dtype is not None:
997
- controlnet = controlnet.to(torch_dtype)
998
-
999
- return {"controlnet": controlnet}
1000
-
1001
-
1002
- def update_vae_resnet_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1003
- for ldm_key in keys:
1004
- diffusers_key = ldm_key.replace(mapping["old"], mapping["new"]).replace("nin_shortcut", "conv_shortcut")
1005
- new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1006
-
1007
-
1008
- def update_vae_attentions_ldm_to_diffusers(keys, new_checkpoint, checkpoint, mapping):
1009
- for ldm_key in keys:
1010
- diffusers_key = (
1011
- ldm_key.replace(mapping["old"], mapping["new"])
1012
- .replace("norm.weight", "group_norm.weight")
1013
- .replace("norm.bias", "group_norm.bias")
1014
- .replace("q.weight", "to_q.weight")
1015
- .replace("q.bias", "to_q.bias")
1016
- .replace("k.weight", "to_k.weight")
1017
- .replace("k.bias", "to_k.bias")
1018
- .replace("v.weight", "to_v.weight")
1019
- .replace("v.bias", "to_v.bias")
1020
- .replace("proj_out.weight", "to_out.0.weight")
1021
- .replace("proj_out.bias", "to_out.0.bias")
1022
- )
1023
- new_checkpoint[diffusers_key] = checkpoint.pop(ldm_key)
1024
-
1025
- # proj_attn.weight has to be converted from conv 1D to linear
1026
- shape = new_checkpoint[diffusers_key].shape
1027
-
1028
- if len(shape) == 3:
1029
- new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0]
1030
- elif len(shape) == 4:
1031
- new_checkpoint[diffusers_key] = new_checkpoint[diffusers_key][:, :, 0, 0]
1032
-
1033
-
1034
- def convert_ldm_vae_checkpoint(checkpoint, config):
1035
- # extract state dict for VAE
1036
- # remove the LDM_VAE_KEY prefix from the ldm checkpoint keys so that it is easier to map them to diffusers keys
1037
- vae_state_dict = {}
1038
- keys = list(checkpoint.keys())
1039
- vae_key = LDM_VAE_KEY if any(k.startswith(LDM_VAE_KEY) for k in keys) else ""
1040
- for key in keys:
1041
- if key.startswith(vae_key):
1042
- vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
1043
-
1044
- new_checkpoint = {}
1045
- vae_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["vae"]
1046
- for diffusers_key, ldm_key in vae_diffusers_ldm_map.items():
1047
- if ldm_key not in vae_state_dict:
1048
- continue
1049
- new_checkpoint[diffusers_key] = vae_state_dict[ldm_key]
1050
-
1051
- # Retrieves the keys for the encoder down blocks only
1052
- num_down_blocks = len(config["down_block_types"])
1053
- down_blocks = {
1054
- layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
1055
- }
1056
-
1057
- for i in range(num_down_blocks):
1058
- resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
1059
- update_vae_resnet_ldm_to_diffusers(
1060
- resnets,
1061
- new_checkpoint,
1062
- vae_state_dict,
1063
- mapping={"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"},
1064
- )
1065
- if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
1066
- new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
1067
- f"encoder.down.{i}.downsample.conv.weight"
1068
- )
1069
- new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
1070
- f"encoder.down.{i}.downsample.conv.bias"
1071
- )
1072
-
1073
- mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
1074
- num_mid_res_blocks = 2
1075
- for i in range(1, num_mid_res_blocks + 1):
1076
- resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
1077
- update_vae_resnet_ldm_to_diffusers(
1078
- resnets,
1079
- new_checkpoint,
1080
- vae_state_dict,
1081
- mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1082
- )
1083
-
1084
- mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
1085
- update_vae_attentions_ldm_to_diffusers(
1086
- mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1087
- )
1088
-
1089
- # Retrieves the keys for the decoder up blocks only
1090
- num_up_blocks = len(config["up_block_types"])
1091
- up_blocks = {
1092
- layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
1093
- }
1094
-
1095
- for i in range(num_up_blocks):
1096
- block_id = num_up_blocks - 1 - i
1097
- resnets = [
1098
- key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
1099
- ]
1100
- update_vae_resnet_ldm_to_diffusers(
1101
- resnets,
1102
- new_checkpoint,
1103
- vae_state_dict,
1104
- mapping={"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"},
1105
- )
1106
- if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
1107
- new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
1108
- f"decoder.up.{block_id}.upsample.conv.weight"
1109
- ]
1110
- new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
1111
- f"decoder.up.{block_id}.upsample.conv.bias"
1112
- ]
1113
-
1114
- mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
1115
- num_mid_res_blocks = 2
1116
- for i in range(1, num_mid_res_blocks + 1):
1117
- resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
1118
- update_vae_resnet_ldm_to_diffusers(
1119
- resnets,
1120
- new_checkpoint,
1121
- vae_state_dict,
1122
- mapping={"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"},
1123
- )
1124
-
1125
- mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
1126
- update_vae_attentions_ldm_to_diffusers(
1127
- mid_attentions, new_checkpoint, vae_state_dict, mapping={"old": "mid.attn_1", "new": "mid_block.attentions.0"}
1128
- )
1129
- conv_attn_to_linear(new_checkpoint)
1130
-
1131
- return new_checkpoint
1132
-
1133
-
1134
- def create_text_encoder_from_ldm_clip_checkpoint(config_name, checkpoint, local_files_only=False, torch_dtype=None):
1135
- try:
1136
- config = CLIPTextConfig.from_pretrained(config_name, local_files_only=local_files_only)
1137
- except Exception:
1138
- raise ValueError(
1139
- f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: 'openai/clip-vit-large-patch14'."
1140
- )
1141
-
1142
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
1143
- with ctx():
1144
- text_model = CLIPTextModel(config)
1145
-
1146
- keys = list(checkpoint.keys())
1147
- text_model_dict = {}
1148
-
1149
- remove_prefixes = LDM_CLIP_PREFIX_TO_REMOVE
1150
-
1151
- for key in keys:
1152
- for prefix in remove_prefixes:
1153
- if key.startswith(prefix):
1154
- diffusers_key = key.replace(prefix, "")
1155
- text_model_dict[diffusers_key] = checkpoint[key]
1156
-
1157
- if is_accelerate_available():
1158
- unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1159
- if text_model._keys_to_ignore_on_load_unexpected is not None:
1160
- for pat in text_model._keys_to_ignore_on_load_unexpected:
1161
- unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1162
-
1163
- if len(unexpected_keys) > 0:
1164
- logger.warning(
1165
- f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1166
- )
1167
- else:
1168
- if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1169
- text_model_dict.pop("text_model.embeddings.position_ids", None)
1170
-
1171
- text_model.load_state_dict(text_model_dict)
1172
-
1173
- if torch_dtype is not None:
1174
- text_model = text_model.to(torch_dtype)
1175
-
1176
- return text_model
1177
-
1178
-
1179
- def create_text_encoder_from_open_clip_checkpoint(
1180
- config_name,
1181
- checkpoint,
1182
- prefix="cond_stage_model.model.",
1183
- has_projection=False,
1184
- local_files_only=False,
1185
- torch_dtype=None,
1186
- **config_kwargs,
1187
- ):
1188
- try:
1189
- config = CLIPTextConfig.from_pretrained(config_name, **config_kwargs, local_files_only=local_files_only)
1190
- except Exception:
1191
- raise ValueError(
1192
- f"With local_files_only set to {local_files_only}, you must first locally save the configuration in the following path: '{config_name}'."
1193
- )
1194
-
1195
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
1196
- with ctx():
1197
- text_model = CLIPTextModelWithProjection(config) if has_projection else CLIPTextModel(config)
1198
-
1199
- text_model_dict = {}
1200
- text_proj_key = prefix + "text_projection"
1201
- text_proj_dim = (
1202
- int(checkpoint[text_proj_key].shape[0]) if text_proj_key in checkpoint else LDM_OPEN_CLIP_TEXT_PROJECTION_DIM
1203
- )
1204
- text_model_dict["text_model.embeddings.position_ids"] = text_model.text_model.embeddings.get_buffer("position_ids")
1205
-
1206
- keys = list(checkpoint.keys())
1207
- keys_to_ignore = SD_2_TEXT_ENCODER_KEYS_TO_IGNORE
1208
-
1209
- openclip_diffusers_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["layers"]
1210
- for diffusers_key, ldm_key in openclip_diffusers_ldm_map.items():
1211
- ldm_key = prefix + ldm_key
1212
- if ldm_key not in checkpoint:
1213
- continue
1214
- if ldm_key in keys_to_ignore:
1215
- continue
1216
- if ldm_key.endswith("text_projection"):
1217
- text_model_dict[diffusers_key] = checkpoint[ldm_key].T.contiguous()
1218
- else:
1219
- text_model_dict[diffusers_key] = checkpoint[ldm_key]
1220
-
1221
- for key in keys:
1222
- if key in keys_to_ignore:
1223
- continue
1224
-
1225
- if not key.startswith(prefix + "transformer."):
1226
- continue
1227
-
1228
- diffusers_key = key.replace(prefix + "transformer.", "")
1229
- transformer_diffusers_to_ldm_map = DIFFUSERS_TO_LDM_MAPPING["openclip"]["transformer"]
1230
- for new_key, old_key in transformer_diffusers_to_ldm_map.items():
1231
- diffusers_key = (
1232
- diffusers_key.replace(old_key, new_key).replace(".in_proj_weight", "").replace(".in_proj_bias", "")
1233
- )
1234
-
1235
- if key.endswith(".in_proj_weight"):
1236
- weight_value = checkpoint[key]
1237
-
1238
- text_model_dict[diffusers_key + ".q_proj.weight"] = weight_value[:text_proj_dim, :]
1239
- text_model_dict[diffusers_key + ".k_proj.weight"] = weight_value[text_proj_dim : text_proj_dim * 2, :]
1240
- text_model_dict[diffusers_key + ".v_proj.weight"] = weight_value[text_proj_dim * 2 :, :]
1241
-
1242
- elif key.endswith(".in_proj_bias"):
1243
- weight_value = checkpoint[key]
1244
- text_model_dict[diffusers_key + ".q_proj.bias"] = weight_value[:text_proj_dim]
1245
- text_model_dict[diffusers_key + ".k_proj.bias"] = weight_value[text_proj_dim : text_proj_dim * 2]
1246
- text_model_dict[diffusers_key + ".v_proj.bias"] = weight_value[text_proj_dim * 2 :]
1247
- else:
1248
- text_model_dict[diffusers_key] = checkpoint[key]
1249
-
1250
- if is_accelerate_available():
1251
- unexpected_keys = load_model_dict_into_meta(text_model, text_model_dict, dtype=torch_dtype)
1252
- if text_model._keys_to_ignore_on_load_unexpected is not None:
1253
- for pat in text_model._keys_to_ignore_on_load_unexpected:
1254
- unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1255
-
1256
- if len(unexpected_keys) > 0:
1257
- logger.warning(
1258
- f"Some weights of the model checkpoint were not used when initializing {text_model.__class__.__name__}: \n {[', '.join(unexpected_keys)]}"
1259
- )
1260
-
1261
- else:
1262
- if not (hasattr(text_model, "embeddings") and hasattr(text_model.embeddings.position_ids)):
1263
- text_model_dict.pop("text_model.embeddings.position_ids", None)
1264
-
1265
- text_model.load_state_dict(text_model_dict)
1266
-
1267
- if torch_dtype is not None:
1268
- text_model = text_model.to(torch_dtype)
1269
-
1270
- return text_model
1271
-
1272
-
1273
- def create_diffusers_unet_model_from_ldm(
1274
- pipeline_class_name,
1275
- original_config,
1276
- checkpoint,
1277
- num_in_channels=None,
1278
- upcast_attention=None,
1279
- extract_ema=False,
1280
- image_size=None,
1281
- torch_dtype=None,
1282
- model_type=None,
1283
- ):
1284
- from ..models import UNet2DConditionModel
1285
-
1286
- if num_in_channels is None:
1287
- if pipeline_class_name in [
1288
- "StableDiffusionInpaintPipeline",
1289
- "StableDiffusionControlNetInpaintPipeline",
1290
- "StableDiffusionXLInpaintPipeline",
1291
- "StableDiffusionXLControlNetInpaintPipeline",
1292
- ]:
1293
- num_in_channels = 9
1294
-
1295
- elif pipeline_class_name == "StableDiffusionUpscalePipeline":
1296
- num_in_channels = 7
1297
-
1298
- else:
1299
- num_in_channels = 4
1300
-
1301
- image_size = set_image_size(
1302
- pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1303
- )
1304
- unet_config = create_unet_diffusers_config(original_config, image_size=image_size)
1305
- unet_config["in_channels"] = num_in_channels
1306
- if upcast_attention is not None:
1307
- unet_config["upcast_attention"] = upcast_attention
1308
-
1309
- diffusers_format_unet_checkpoint = convert_ldm_unet_checkpoint(checkpoint, unet_config, extract_ema=extract_ema)
1310
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
1311
-
1312
- with ctx():
1313
- unet = UNet2DConditionModel(**unet_config)
1314
-
1315
- if is_accelerate_available():
1316
- unexpected_keys = load_model_dict_into_meta(unet, diffusers_format_unet_checkpoint, dtype=torch_dtype)
1317
- if unet._keys_to_ignore_on_load_unexpected is not None:
1318
- for pat in unet._keys_to_ignore_on_load_unexpected:
1319
- unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1320
-
1321
- if len(unexpected_keys) > 0:
1322
- logger.warning(
1323
- f"Some weights of the model checkpoint were not used when initializing {unet.__name__}: \n {[', '.join(unexpected_keys)]}"
1324
- )
1325
- else:
1326
- unet.load_state_dict(diffusers_format_unet_checkpoint)
1327
-
1328
- if torch_dtype is not None:
1329
- unet = unet.to(torch_dtype)
1330
-
1331
- return {"unet": unet}
1332
-
1333
-
1334
- def create_diffusers_vae_model_from_ldm(
1335
- pipeline_class_name,
1336
- original_config,
1337
- checkpoint,
1338
- image_size=None,
1339
- scaling_factor=None,
1340
- torch_dtype=None,
1341
- model_type=None,
1342
- ):
1343
- # import here to avoid circular imports
1344
- from ..models import AutoencoderKL
1345
-
1346
- image_size = set_image_size(
1347
- pipeline_class_name, original_config, checkpoint, image_size=image_size, model_type=model_type
1348
- )
1349
- model_type = infer_model_type(original_config, checkpoint, model_type)
1350
-
1351
- if model_type == "Playground":
1352
- edm_mean = (
1353
- checkpoint["edm_mean"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_mean"].tolist()
1354
- )
1355
- edm_std = (
1356
- checkpoint["edm_std"].to(dtype=torch_dtype).tolist() if torch_dtype else checkpoint["edm_std"].tolist()
1357
- )
1358
- else:
1359
- edm_mean = None
1360
- edm_std = None
1361
-
1362
- vae_config = create_vae_diffusers_config(
1363
- original_config,
1364
- image_size=image_size,
1365
- scaling_factor=scaling_factor,
1366
- latents_mean=edm_mean,
1367
- latents_std=edm_std,
1368
- )
1369
- diffusers_format_vae_checkpoint = convert_ldm_vae_checkpoint(checkpoint, vae_config)
1370
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
1371
-
1372
- with ctx():
1373
- vae = AutoencoderKL(**vae_config)
1374
-
1375
- if is_accelerate_available():
1376
- unexpected_keys = load_model_dict_into_meta(vae, diffusers_format_vae_checkpoint, dtype=torch_dtype)
1377
- if vae._keys_to_ignore_on_load_unexpected is not None:
1378
- for pat in vae._keys_to_ignore_on_load_unexpected:
1379
- unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1380
-
1381
- if len(unexpected_keys) > 0:
1382
- logger.warning(
1383
- f"Some weights of the model checkpoint were not used when initializing {vae.__name__}: \n {[', '.join(unexpected_keys)]}"
1384
- )
1385
- else:
1386
- vae.load_state_dict(diffusers_format_vae_checkpoint)
1387
-
1388
- if torch_dtype is not None:
1389
- vae = vae.to(torch_dtype)
1390
-
1391
- return {"vae": vae}
1392
-
1393
-
1394
- def create_text_encoders_and_tokenizers_from_ldm(
1395
- original_config,
1396
- checkpoint,
1397
- model_type=None,
1398
- local_files_only=False,
1399
- torch_dtype=None,
1400
- ):
1401
- model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1402
-
1403
- if model_type == "FrozenOpenCLIPEmbedder":
1404
- config_name = "stabilityai/stable-diffusion-2"
1405
- config_kwargs = {"subfolder": "text_encoder"}
1406
-
1407
- try:
1408
- text_encoder = create_text_encoder_from_open_clip_checkpoint(
1409
- config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype, **config_kwargs
1410
- )
1411
- tokenizer = CLIPTokenizer.from_pretrained(
1412
- config_name, subfolder="tokenizer", local_files_only=local_files_only
1413
- )
1414
- except Exception:
1415
- raise ValueError(
1416
- f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder in the following path: '{config_name}'."
1417
- )
1418
- else:
1419
- return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1420
-
1421
- elif model_type == "FrozenCLIPEmbedder":
1422
- try:
1423
- config_name = "openai/clip-vit-large-patch14"
1424
- text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1425
- config_name,
1426
- checkpoint,
1427
- local_files_only=local_files_only,
1428
- torch_dtype=torch_dtype,
1429
- )
1430
- tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1431
-
1432
- except Exception:
1433
- raise ValueError(
1434
- f"With local_files_only set to {local_files_only}, you must first locally save the tokenizer in the following path: '{config_name}'."
1435
- )
1436
- else:
1437
- return {"text_encoder": text_encoder, "tokenizer": tokenizer}
1438
-
1439
- elif model_type == "SDXL-Refiner":
1440
- config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1441
- config_kwargs = {"projection_dim": 1280}
1442
- prefix = "conditioner.embedders.0.model."
1443
-
1444
- try:
1445
- tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1446
- text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1447
- config_name,
1448
- checkpoint,
1449
- prefix=prefix,
1450
- has_projection=True,
1451
- local_files_only=local_files_only,
1452
- torch_dtype=torch_dtype,
1453
- **config_kwargs,
1454
- )
1455
- except Exception:
1456
- raise ValueError(
1457
- f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1458
- )
1459
-
1460
- else:
1461
- return {
1462
- "text_encoder": None,
1463
- "tokenizer": None,
1464
- "tokenizer_2": tokenizer_2,
1465
- "text_encoder_2": text_encoder_2,
1466
- }
1467
-
1468
- elif model_type in ["SDXL", "Playground"]:
1469
- try:
1470
- config_name = "openai/clip-vit-large-patch14"
1471
- tokenizer = CLIPTokenizer.from_pretrained(config_name, local_files_only=local_files_only)
1472
- text_encoder = create_text_encoder_from_ldm_clip_checkpoint(
1473
- config_name, checkpoint, local_files_only=local_files_only, torch_dtype=torch_dtype
1474
- )
1475
-
1476
- except Exception:
1477
- raise ValueError(
1478
- f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder and tokenizer in the following path: 'openai/clip-vit-large-patch14'."
1479
- )
1480
-
1481
- try:
1482
- config_name = "laion/CLIP-ViT-bigG-14-laion2B-39B-b160k"
1483
- config_kwargs = {"projection_dim": 1280}
1484
- prefix = "conditioner.embedders.1.model."
1485
- tokenizer_2 = CLIPTokenizer.from_pretrained(config_name, pad_token="!", local_files_only=local_files_only)
1486
- text_encoder_2 = create_text_encoder_from_open_clip_checkpoint(
1487
- config_name,
1488
- checkpoint,
1489
- prefix=prefix,
1490
- has_projection=True,
1491
- local_files_only=local_files_only,
1492
- torch_dtype=torch_dtype,
1493
- **config_kwargs,
1494
- )
1495
- except Exception:
1496
- raise ValueError(
1497
- f"With local_files_only set to {local_files_only}, you must first locally save the text_encoder_2 and tokenizer_2 in the following path: {config_name} with `pad_token` set to '!'."
1498
- )
1499
-
1500
- return {
1501
- "tokenizer": tokenizer,
1502
- "text_encoder": text_encoder,
1503
- "tokenizer_2": tokenizer_2,
1504
- "text_encoder_2": text_encoder_2,
1505
- }
1506
-
1507
- return
1508
-
1509
-
1510
- def create_scheduler_from_ldm(
1511
- pipeline_class_name,
1512
- original_config,
1513
- checkpoint,
1514
- prediction_type=None,
1515
- scheduler_type="ddim",
1516
- model_type=None,
1517
- ):
1518
- scheduler_config = get_default_scheduler_config()
1519
- model_type = infer_model_type(original_config, checkpoint=checkpoint, model_type=model_type)
1520
-
1521
- global_step = checkpoint["global_step"] if "global_step" in checkpoint else None
1522
-
1523
- num_train_timesteps = getattr(original_config["model"]["params"], "timesteps", None) or 1000
1524
- scheduler_config["num_train_timesteps"] = num_train_timesteps
1525
-
1526
- if (
1527
- "parameterization" in original_config["model"]["params"]
1528
- and original_config["model"]["params"]["parameterization"] == "v"
1529
- ):
1530
- if prediction_type is None:
1531
- # NOTE: For stable diffusion 2 base it is recommended to pass `prediction_type=="epsilon"`
1532
- # as it relies on a brittle global step parameter here
1533
- prediction_type = "epsilon" if global_step == 875000 else "v_prediction"
1534
-
1535
- else:
1536
- prediction_type = prediction_type or "epsilon"
1537
-
1538
- scheduler_config["prediction_type"] = prediction_type
1539
-
1540
- if model_type in ["SDXL", "SDXL-Refiner"]:
1541
- scheduler_type = "euler"
1542
- elif model_type == "Playground":
1543
- scheduler_type = "edm_dpm_solver_multistep"
1544
- else:
1545
- beta_start = original_config["model"]["params"].get("linear_start", 0.02)
1546
- beta_end = original_config["model"]["params"].get("linear_end", 0.085)
1547
- scheduler_config["beta_start"] = beta_start
1548
- scheduler_config["beta_end"] = beta_end
1549
- scheduler_config["beta_schedule"] = "scaled_linear"
1550
- scheduler_config["clip_sample"] = False
1551
- scheduler_config["set_alpha_to_one"] = False
1552
-
1553
- if scheduler_type == "pndm":
1554
- scheduler_config["skip_prk_steps"] = True
1555
- scheduler = PNDMScheduler.from_config(scheduler_config)
1556
-
1557
- elif scheduler_type == "lms":
1558
- scheduler = LMSDiscreteScheduler.from_config(scheduler_config)
1559
-
1560
- elif scheduler_type == "heun":
1561
- scheduler = HeunDiscreteScheduler.from_config(scheduler_config)
1562
-
1563
- elif scheduler_type == "euler":
1564
- scheduler = EulerDiscreteScheduler.from_config(scheduler_config)
1565
-
1566
- elif scheduler_type == "euler-ancestral":
1567
- scheduler = EulerAncestralDiscreteScheduler.from_config(scheduler_config)
1568
-
1569
- elif scheduler_type == "dpm":
1570
- scheduler = DPMSolverMultistepScheduler.from_config(scheduler_config)
1571
-
1572
- elif scheduler_type == "ddim":
1573
- scheduler = DDIMScheduler.from_config(scheduler_config)
1574
-
1575
- elif scheduler_type == "edm_dpm_solver_multistep":
1576
- scheduler_config = {
1577
- "algorithm_type": "dpmsolver++",
1578
- "dynamic_thresholding_ratio": 0.995,
1579
- "euler_at_final": False,
1580
- "final_sigmas_type": "zero",
1581
- "lower_order_final": True,
1582
- "num_train_timesteps": 1000,
1583
- "prediction_type": "epsilon",
1584
- "rho": 7.0,
1585
- "sample_max_value": 1.0,
1586
- "sigma_data": 0.5,
1587
- "sigma_max": 80.0,
1588
- "sigma_min": 0.002,
1589
- "solver_order": 2,
1590
- "solver_type": "midpoint",
1591
- "thresholding": False,
1592
- }
1593
- scheduler = EDMDPMSolverMultistepScheduler(**scheduler_config)
1594
-
1595
- else:
1596
- raise ValueError(f"Scheduler of type {scheduler_type} doesn't exist!")
1597
-
1598
- if pipeline_class_name == "StableDiffusionUpscalePipeline":
1599
- scheduler = DDIMScheduler.from_pretrained("stabilityai/stable-diffusion-x4-upscaler", subfolder="scheduler")
1600
- low_res_scheduler = DDPMScheduler.from_pretrained(
1601
- "stabilityai/stable-diffusion-x4-upscaler", subfolder="low_res_scheduler"
1602
- )
1603
-
1604
- return {
1605
- "scheduler": scheduler,
1606
- "low_res_scheduler": low_res_scheduler,
1607
- }
1608
-
1609
- return {"scheduler": scheduler}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/textual_inversion.py DELETED
@@ -1,582 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Dict, List, Optional, Union
15
-
16
- import safetensors
17
- import torch
18
- from huggingface_hub.utils import validate_hf_hub_args
19
- from torch import nn
20
-
21
- from ..models.modeling_utils import load_state_dict
22
- from ..utils import _get_model_file, is_accelerate_available, is_transformers_available, logging
23
-
24
-
25
- if is_transformers_available():
26
- from transformers import PreTrainedModel, PreTrainedTokenizer
27
-
28
- if is_accelerate_available():
29
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
30
-
31
- logger = logging.get_logger(__name__)
32
-
33
- TEXT_INVERSION_NAME = "learned_embeds.bin"
34
- TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
35
-
36
-
37
- @validate_hf_hub_args
38
- def load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs):
39
- cache_dir = kwargs.pop("cache_dir", None)
40
- force_download = kwargs.pop("force_download", False)
41
- resume_download = kwargs.pop("resume_download", None)
42
- proxies = kwargs.pop("proxies", None)
43
- local_files_only = kwargs.pop("local_files_only", None)
44
- token = kwargs.pop("token", None)
45
- revision = kwargs.pop("revision", None)
46
- subfolder = kwargs.pop("subfolder", None)
47
- weight_name = kwargs.pop("weight_name", None)
48
- use_safetensors = kwargs.pop("use_safetensors", None)
49
-
50
- allow_pickle = False
51
- if use_safetensors is None:
52
- use_safetensors = True
53
- allow_pickle = True
54
-
55
- user_agent = {
56
- "file_type": "text_inversion",
57
- "framework": "pytorch",
58
- }
59
- state_dicts = []
60
- for pretrained_model_name_or_path in pretrained_model_name_or_paths:
61
- if not isinstance(pretrained_model_name_or_path, (dict, torch.Tensor)):
62
- # 3.1. Load textual inversion file
63
- model_file = None
64
-
65
- # Let's first try to load .safetensors weights
66
- if (use_safetensors and weight_name is None) or (
67
- weight_name is not None and weight_name.endswith(".safetensors")
68
- ):
69
- try:
70
- model_file = _get_model_file(
71
- pretrained_model_name_or_path,
72
- weights_name=weight_name or TEXT_INVERSION_NAME_SAFE,
73
- cache_dir=cache_dir,
74
- force_download=force_download,
75
- resume_download=resume_download,
76
- proxies=proxies,
77
- local_files_only=local_files_only,
78
- token=token,
79
- revision=revision,
80
- subfolder=subfolder,
81
- user_agent=user_agent,
82
- )
83
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
84
- except Exception as e:
85
- if not allow_pickle:
86
- raise e
87
-
88
- model_file = None
89
-
90
- if model_file is None:
91
- model_file = _get_model_file(
92
- pretrained_model_name_or_path,
93
- weights_name=weight_name or TEXT_INVERSION_NAME,
94
- cache_dir=cache_dir,
95
- force_download=force_download,
96
- resume_download=resume_download,
97
- proxies=proxies,
98
- local_files_only=local_files_only,
99
- token=token,
100
- revision=revision,
101
- subfolder=subfolder,
102
- user_agent=user_agent,
103
- )
104
- state_dict = load_state_dict(model_file)
105
- else:
106
- state_dict = pretrained_model_name_or_path
107
-
108
- state_dicts.append(state_dict)
109
-
110
- return state_dicts
111
-
112
-
113
- class TextualInversionLoaderMixin:
114
- r"""
115
- Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
116
- """
117
-
118
- def maybe_convert_prompt(self, prompt: Union[str, List[str]], tokenizer: "PreTrainedTokenizer"): # noqa: F821
119
- r"""
120
- Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
121
- be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
122
- inversion token or if the textual inversion token is a single vector, the input prompt is returned.
123
-
124
- Parameters:
125
- prompt (`str` or list of `str`):
126
- The prompt or prompts to guide the image generation.
127
- tokenizer (`PreTrainedTokenizer`):
128
- The tokenizer responsible for encoding the prompt into input tokens.
129
-
130
- Returns:
131
- `str` or list of `str`: The converted prompt
132
- """
133
- if not isinstance(prompt, List):
134
- prompts = [prompt]
135
- else:
136
- prompts = prompt
137
-
138
- prompts = [self._maybe_convert_prompt(p, tokenizer) for p in prompts]
139
-
140
- if not isinstance(prompt, List):
141
- return prompts[0]
142
-
143
- return prompts
144
-
145
- def _maybe_convert_prompt(self, prompt: str, tokenizer: "PreTrainedTokenizer"): # noqa: F821
146
- r"""
147
- Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
148
- to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
149
- is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
150
- inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.
151
-
152
- Parameters:
153
- prompt (`str`):
154
- The prompt to guide the image generation.
155
- tokenizer (`PreTrainedTokenizer`):
156
- The tokenizer responsible for encoding the prompt into input tokens.
157
-
158
- Returns:
159
- `str`: The converted prompt
160
- """
161
- tokens = tokenizer.tokenize(prompt)
162
- unique_tokens = set(tokens)
163
- for token in unique_tokens:
164
- if token in tokenizer.added_tokens_encoder:
165
- replacement = token
166
- i = 1
167
- while f"{token}_{i}" in tokenizer.added_tokens_encoder:
168
- replacement += f" {token}_{i}"
169
- i += 1
170
-
171
- prompt = prompt.replace(token, replacement)
172
-
173
- return prompt
174
-
175
- def _check_text_inv_inputs(self, tokenizer, text_encoder, pretrained_model_name_or_paths, tokens):
176
- if tokenizer is None:
177
- raise ValueError(
178
- f"{self.__class__.__name__} requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling"
179
- f" `{self.load_textual_inversion.__name__}`"
180
- )
181
-
182
- if text_encoder is None:
183
- raise ValueError(
184
- f"{self.__class__.__name__} requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling"
185
- f" `{self.load_textual_inversion.__name__}`"
186
- )
187
-
188
- if len(pretrained_model_name_or_paths) > 1 and len(pretrained_model_name_or_paths) != len(tokens):
189
- raise ValueError(
190
- f"You have passed a list of models of length {len(pretrained_model_name_or_paths)}, and list of tokens of length {len(tokens)} "
191
- f"Make sure both lists have the same length."
192
- )
193
-
194
- valid_tokens = [t for t in tokens if t is not None]
195
- if len(set(valid_tokens)) < len(valid_tokens):
196
- raise ValueError(f"You have passed a list of tokens that contains duplicates: {tokens}")
197
-
198
- @staticmethod
199
- def _retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer):
200
- all_tokens = []
201
- all_embeddings = []
202
- for state_dict, token in zip(state_dicts, tokens):
203
- if isinstance(state_dict, torch.Tensor):
204
- if token is None:
205
- raise ValueError(
206
- "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=...`."
207
- )
208
- loaded_token = token
209
- embedding = state_dict
210
- elif len(state_dict) == 1:
211
- # diffusers
212
- loaded_token, embedding = next(iter(state_dict.items()))
213
- elif "string_to_param" in state_dict:
214
- # A1111
215
- loaded_token = state_dict["name"]
216
- embedding = state_dict["string_to_param"]["*"]
217
- else:
218
- raise ValueError(
219
- f"Loaded state dictionary is incorrect: {state_dict}. \n\n"
220
- "Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param`"
221
- " input key."
222
- )
223
-
224
- if token is not None and loaded_token != token:
225
- logger.info(f"The loaded token: {loaded_token} is overwritten by the passed token {token}.")
226
- else:
227
- token = loaded_token
228
-
229
- if token in tokenizer.get_vocab():
230
- raise ValueError(
231
- f"Token {token} already in tokenizer vocabulary. Please choose a different token name or remove {token} and embedding from the tokenizer and text encoder."
232
- )
233
-
234
- all_tokens.append(token)
235
- all_embeddings.append(embedding)
236
-
237
- return all_tokens, all_embeddings
238
-
239
- @staticmethod
240
- def _extend_tokens_and_embeddings(tokens, embeddings, tokenizer):
241
- all_tokens = []
242
- all_embeddings = []
243
-
244
- for embedding, token in zip(embeddings, tokens):
245
- if f"{token}_1" in tokenizer.get_vocab():
246
- multi_vector_tokens = [token]
247
- i = 1
248
- while f"{token}_{i}" in tokenizer.added_tokens_encoder:
249
- multi_vector_tokens.append(f"{token}_{i}")
250
- i += 1
251
-
252
- raise ValueError(
253
- 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."
254
- )
255
-
256
- is_multi_vector = len(embedding.shape) > 1 and embedding.shape[0] > 1
257
- if is_multi_vector:
258
- all_tokens += [token] + [f"{token}_{i}" for i in range(1, embedding.shape[0])]
259
- all_embeddings += [e for e in embedding] # noqa: C416
260
- else:
261
- all_tokens += [token]
262
- all_embeddings += [embedding[0]] if len(embedding.shape) > 1 else [embedding]
263
-
264
- return all_tokens, all_embeddings
265
-
266
- @validate_hf_hub_args
267
- def load_textual_inversion(
268
- self,
269
- pretrained_model_name_or_path: Union[str, List[str], Dict[str, torch.Tensor], List[Dict[str, torch.Tensor]]],
270
- token: Optional[Union[str, List[str]]] = None,
271
- tokenizer: Optional["PreTrainedTokenizer"] = None, # noqa: F821
272
- text_encoder: Optional["PreTrainedModel"] = None, # noqa: F821
273
- **kwargs,
274
- ):
275
- r"""
276
- Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
277
- Automatic1111 formats are supported).
278
-
279
- Parameters:
280
- pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
281
- Can be either one of the following or a list of them:
282
-
283
- - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
284
- pretrained model hosted on the Hub.
285
- - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
286
- inversion weights.
287
- - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
288
- - A [torch state
289
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
290
-
291
- token (`str` or `List[str]`, *optional*):
292
- Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
293
- list, then `token` must also be a list of equal length.
294
- text_encoder ([`~transformers.CLIPTextModel`], *optional*):
295
- Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
296
- If not specified, function will take self.tokenizer.
297
- tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
298
- A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
299
- weight_name (`str`, *optional*):
300
- Name of a custom weight file. This should be used when:
301
-
302
- - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
303
- name such as `text_inv.bin`.
304
- - The saved textual inversion file is in the Automatic1111 format.
305
- cache_dir (`Union[str, os.PathLike]`, *optional*):
306
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
307
- is not used.
308
- force_download (`bool`, *optional*, defaults to `False`):
309
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
310
- cached versions if they exist.
311
- resume_download:
312
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
313
- of Diffusers.
314
- proxies (`Dict[str, str]`, *optional*):
315
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
316
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
317
- local_files_only (`bool`, *optional*, defaults to `False`):
318
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
319
- won't be downloaded from the Hub.
320
- token (`str` or *bool*, *optional*):
321
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
322
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
323
- revision (`str`, *optional*, defaults to `"main"`):
324
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
325
- allowed by Git.
326
- subfolder (`str`, *optional*, defaults to `""`):
327
- The subfolder location of a model file within a larger model repository on the Hub or locally.
328
- mirror (`str`, *optional*):
329
- Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
330
- guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
331
- information.
332
-
333
- Example:
334
-
335
- To load a Textual Inversion embedding vector in 🤗 Diffusers format:
336
-
337
- ```py
338
- from diffusers import StableDiffusionPipeline
339
- import torch
340
-
341
- model_id = "runwayml/stable-diffusion-v1-5"
342
- pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
343
-
344
- pipe.load_textual_inversion("sd-concepts-library/cat-toy")
345
-
346
- prompt = "A <cat-toy> backpack"
347
-
348
- image = pipe(prompt, num_inference_steps=50).images[0]
349
- image.save("cat-backpack.png")
350
- ```
351
-
352
- To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
353
- (for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
354
- locally:
355
-
356
- ```py
357
- from diffusers import StableDiffusionPipeline
358
- import torch
359
-
360
- model_id = "runwayml/stable-diffusion-v1-5"
361
- pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
362
-
363
- pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")
364
-
365
- 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."
366
-
367
- image = pipe(prompt, num_inference_steps=50).images[0]
368
- image.save("character.png")
369
- ```
370
-
371
- """
372
- # 1. Set correct tokenizer and text encoder
373
- tokenizer = tokenizer or getattr(self, "tokenizer", None)
374
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
375
-
376
- # 2. Normalize inputs
377
- pretrained_model_name_or_paths = (
378
- [pretrained_model_name_or_path]
379
- if not isinstance(pretrained_model_name_or_path, list)
380
- else pretrained_model_name_or_path
381
- )
382
- tokens = [token] if not isinstance(token, list) else token
383
- if tokens[0] is None:
384
- tokens = tokens * len(pretrained_model_name_or_paths)
385
-
386
- # 3. Check inputs
387
- self._check_text_inv_inputs(tokenizer, text_encoder, pretrained_model_name_or_paths, tokens)
388
-
389
- # 4. Load state dicts of textual embeddings
390
- state_dicts = load_textual_inversion_state_dicts(pretrained_model_name_or_paths, **kwargs)
391
-
392
- # 4.1 Handle the special case when state_dict is a tensor that contains n embeddings for n tokens
393
- if len(tokens) > 1 and len(state_dicts) == 1:
394
- if isinstance(state_dicts[0], torch.Tensor):
395
- state_dicts = list(state_dicts[0])
396
- if len(tokens) != len(state_dicts):
397
- raise ValueError(
398
- f"You have passed a state_dict contains {len(state_dicts)} embeddings, and list of tokens of length {len(tokens)} "
399
- f"Make sure both have the same length."
400
- )
401
-
402
- # 4. Retrieve tokens and embeddings
403
- tokens, embeddings = self._retrieve_tokens_and_embeddings(tokens, state_dicts, tokenizer)
404
-
405
- # 5. Extend tokens and embeddings for multi vector
406
- tokens, embeddings = self._extend_tokens_and_embeddings(tokens, embeddings, tokenizer)
407
-
408
- # 6. Make sure all embeddings have the correct size
409
- expected_emb_dim = text_encoder.get_input_embeddings().weight.shape[-1]
410
- if any(expected_emb_dim != emb.shape[-1] for emb in embeddings):
411
- raise ValueError(
412
- "Loaded embeddings are of incorrect shape. Expected each textual inversion embedding "
413
- "to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} "
414
- )
415
-
416
- # 7. Now we can be sure that loading the embedding matrix works
417
- # < Unsafe code:
418
-
419
- # 7.1 Offload all hooks in case the pipeline was cpu offloaded before make sure, we offload and onload again
420
- is_model_cpu_offload = False
421
- is_sequential_cpu_offload = False
422
- for _, component in self.components.items():
423
- if isinstance(component, nn.Module):
424
- if hasattr(component, "_hf_hook"):
425
- is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
426
- is_sequential_cpu_offload = (
427
- isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
428
- or hasattr(component._hf_hook, "hooks")
429
- and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
430
- )
431
- logger.info(
432
- "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."
433
- )
434
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
435
-
436
- # 7.2 save expected device and dtype
437
- device = text_encoder.device
438
- dtype = text_encoder.dtype
439
-
440
- # 7.3 Increase token embedding matrix
441
- text_encoder.resize_token_embeddings(len(tokenizer) + len(tokens))
442
- input_embeddings = text_encoder.get_input_embeddings().weight
443
-
444
- # 7.4 Load token and embedding
445
- for token, embedding in zip(tokens, embeddings):
446
- # add tokens and get ids
447
- tokenizer.add_tokens(token)
448
- token_id = tokenizer.convert_tokens_to_ids(token)
449
- input_embeddings.data[token_id] = embedding
450
- logger.info(f"Loaded textual inversion embedding for {token}.")
451
-
452
- input_embeddings.to(dtype=dtype, device=device)
453
-
454
- # 7.5 Offload the model again
455
- if is_model_cpu_offload:
456
- self.enable_model_cpu_offload()
457
- elif is_sequential_cpu_offload:
458
- self.enable_sequential_cpu_offload()
459
-
460
- # / Unsafe Code >
461
-
462
- def unload_textual_inversion(
463
- self,
464
- tokens: Optional[Union[str, List[str]]] = None,
465
- tokenizer: Optional["PreTrainedTokenizer"] = None,
466
- text_encoder: Optional["PreTrainedModel"] = None,
467
- ):
468
- r"""
469
- Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]
470
-
471
- Example:
472
- ```py
473
- from diffusers import AutoPipelineForText2Image
474
- import torch
475
-
476
- pipeline = AutoPipelineForText2Image.from_pretrained("runwayml/stable-diffusion-v1-5")
477
-
478
- # Example 1
479
- pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
480
- pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
481
-
482
- # Remove all token embeddings
483
- pipeline.unload_textual_inversion()
484
-
485
- # Example 2
486
- pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
487
- pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
488
-
489
- # Remove just one token
490
- pipeline.unload_textual_inversion("<moe-bius>")
491
-
492
- # Example 3: unload from SDXL
493
- pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
494
- embedding_path = hf_hub_download(
495
- repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model"
496
- )
497
-
498
- # load embeddings to the text encoders
499
- state_dict = load_file(embedding_path)
500
-
501
- # load embeddings of text_encoder 1 (CLIP ViT-L/14)
502
- pipeline.load_textual_inversion(
503
- state_dict["clip_l"],
504
- token=["<s0>", "<s1>"],
505
- text_encoder=pipeline.text_encoder,
506
- tokenizer=pipeline.tokenizer,
507
- )
508
- # load embeddings of text_encoder 2 (CLIP ViT-G/14)
509
- pipeline.load_textual_inversion(
510
- state_dict["clip_g"],
511
- token=["<s0>", "<s1>"],
512
- text_encoder=pipeline.text_encoder_2,
513
- tokenizer=pipeline.tokenizer_2,
514
- )
515
-
516
- # Unload explicitly from both text encoders abd tokenizers
517
- pipeline.unload_textual_inversion(
518
- tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer
519
- )
520
- pipeline.unload_textual_inversion(
521
- tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2
522
- )
523
- ```
524
- """
525
-
526
- tokenizer = tokenizer or getattr(self, "tokenizer", None)
527
- text_encoder = text_encoder or getattr(self, "text_encoder", None)
528
-
529
- # Get textual inversion tokens and ids
530
- token_ids = []
531
- last_special_token_id = None
532
-
533
- if tokens:
534
- if isinstance(tokens, str):
535
- tokens = [tokens]
536
- for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
537
- if not added_token.special:
538
- if added_token.content in tokens:
539
- token_ids.append(added_token_id)
540
- else:
541
- last_special_token_id = added_token_id
542
- if len(token_ids) == 0:
543
- raise ValueError("No tokens to remove found")
544
- else:
545
- tokens = []
546
- for added_token_id, added_token in tokenizer.added_tokens_decoder.items():
547
- if not added_token.special:
548
- token_ids.append(added_token_id)
549
- tokens.append(added_token.content)
550
- else:
551
- last_special_token_id = added_token_id
552
-
553
- # Delete from tokenizer
554
- for token_id, token_to_remove in zip(token_ids, tokens):
555
- del tokenizer._added_tokens_decoder[token_id]
556
- del tokenizer._added_tokens_encoder[token_to_remove]
557
-
558
- # Make all token ids sequential in tokenizer
559
- key_id = 1
560
- for token_id in tokenizer.added_tokens_decoder:
561
- if token_id > last_special_token_id and token_id > last_special_token_id + key_id:
562
- token = tokenizer._added_tokens_decoder[token_id]
563
- tokenizer._added_tokens_decoder[last_special_token_id + key_id] = token
564
- del tokenizer._added_tokens_decoder[token_id]
565
- tokenizer._added_tokens_encoder[token.content] = last_special_token_id + key_id
566
- key_id += 1
567
- tokenizer._update_trie()
568
-
569
- # Delete from text encoder
570
- text_embedding_dim = text_encoder.get_input_embeddings().embedding_dim
571
- temp_text_embedding_weights = text_encoder.get_input_embeddings().weight
572
- text_embedding_weights = temp_text_embedding_weights[: last_special_token_id + 1]
573
- to_append = []
574
- for i in range(last_special_token_id + 1, temp_text_embedding_weights.shape[0]):
575
- if i not in token_ids:
576
- to_append.append(temp_text_embedding_weights[i].unsqueeze(0))
577
- if len(to_append) > 0:
578
- to_append = torch.cat(to_append, dim=0)
579
- text_embedding_weights = torch.cat([text_embedding_weights, to_append], dim=0)
580
- text_embeddings_filtered = nn.Embedding(text_embedding_weights.shape[0], text_embedding_dim)
581
- text_embeddings_filtered.weight.data = text_embedding_weights
582
- text_encoder.set_input_embeddings(text_embeddings_filtered)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/unet.py DELETED
@@ -1,1161 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import inspect
15
- import os
16
- from collections import defaultdict
17
- from contextlib import nullcontext
18
- from functools import partial
19
- from pathlib import Path
20
- from typing import Callable, Dict, List, Optional, Union
21
-
22
- import safetensors
23
- import torch
24
- import torch.nn.functional as F
25
- from huggingface_hub.utils import validate_hf_hub_args
26
- from torch import nn
27
-
28
- from ..models.embeddings import (
29
- ImageProjection,
30
- IPAdapterFaceIDImageProjection,
31
- IPAdapterFaceIDPlusImageProjection,
32
- IPAdapterFullImageProjection,
33
- IPAdapterPlusImageProjection,
34
- MultiIPAdapterImageProjection,
35
- )
36
- from ..models.modeling_utils import _LOW_CPU_MEM_USAGE_DEFAULT, load_model_dict_into_meta, load_state_dict
37
- from ..utils import (
38
- USE_PEFT_BACKEND,
39
- _get_model_file,
40
- delete_adapter_layers,
41
- is_accelerate_available,
42
- is_torch_version,
43
- logging,
44
- set_adapter_layers,
45
- set_weights_and_activate_adapters,
46
- )
47
- from .single_file_utils import (
48
- convert_stable_cascade_unet_single_file_to_diffusers,
49
- infer_stable_cascade_single_file_config,
50
- load_single_file_model_checkpoint,
51
- )
52
- from .unet_loader_utils import _maybe_expand_lora_scales
53
- from .utils import AttnProcsLayers
54
-
55
-
56
- if is_accelerate_available():
57
- from accelerate import init_empty_weights
58
- from accelerate.hooks import AlignDevicesHook, CpuOffload, remove_hook_from_module
59
-
60
- logger = logging.get_logger(__name__)
61
-
62
-
63
- TEXT_ENCODER_NAME = "text_encoder"
64
- UNET_NAME = "unet"
65
-
66
- LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
67
- LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
68
-
69
- CUSTOM_DIFFUSION_WEIGHT_NAME = "pytorch_custom_diffusion_weights.bin"
70
- CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE = "pytorch_custom_diffusion_weights.safetensors"
71
-
72
-
73
- class UNet2DConditionLoadersMixin:
74
- """
75
- Load LoRA layers into a [`UNet2DCondtionModel`].
76
- """
77
-
78
- text_encoder_name = TEXT_ENCODER_NAME
79
- unet_name = UNET_NAME
80
-
81
- @validate_hf_hub_args
82
- def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
83
- r"""
84
- Load pretrained attention processor layers into [`UNet2DConditionModel`]. Attention processor layers have to be
85
- defined in
86
- [`attention_processor.py`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py)
87
- and be a `torch.nn.Module` class.
88
-
89
- Parameters:
90
- pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
91
- Can be either:
92
-
93
- - A string, the model id (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
94
- the Hub.
95
- - A path to a directory (for example `./my_model_directory`) containing the model weights saved
96
- with [`ModelMixin.save_pretrained`].
97
- - A [torch state
98
- dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
99
-
100
- cache_dir (`Union[str, os.PathLike]`, *optional*):
101
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
102
- is not used.
103
- force_download (`bool`, *optional*, defaults to `False`):
104
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
105
- cached versions if they exist.
106
- resume_download:
107
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
108
- of Diffusers.
109
- proxies (`Dict[str, str]`, *optional*):
110
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
111
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
112
- local_files_only (`bool`, *optional*, defaults to `False`):
113
- Whether to only load local model weights and configuration files or not. If set to `True`, the model
114
- won't be downloaded from the Hub.
115
- token (`str` or *bool*, *optional*):
116
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
117
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
118
- low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
119
- Speed up model loading only loading the pretrained weights and not initializing the weights. This also
120
- tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
121
- Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
122
- argument to `True` will raise an error.
123
- revision (`str`, *optional*, defaults to `"main"`):
124
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
125
- allowed by Git.
126
- subfolder (`str`, *optional*, defaults to `""`):
127
- The subfolder location of a model file within a larger model repository on the Hub or locally.
128
- mirror (`str`, *optional*):
129
- Mirror source to resolve accessibility issues if you’re downloading a model in China. We do not
130
- guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
131
- information.
132
-
133
- Example:
134
-
135
- ```py
136
- from diffusers import AutoPipelineForText2Image
137
- import torch
138
-
139
- pipeline = AutoPipelineForText2Image.from_pretrained(
140
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
141
- ).to("cuda")
142
- pipeline.unet.load_attn_procs(
143
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
144
- )
145
- ```
146
- """
147
- from ..models.attention_processor import CustomDiffusionAttnProcessor
148
- from ..models.lora import LoRACompatibleConv, LoRACompatibleLinear, LoRAConv2dLayer, LoRALinearLayer
149
-
150
- cache_dir = kwargs.pop("cache_dir", None)
151
- force_download = kwargs.pop("force_download", False)
152
- resume_download = kwargs.pop("resume_download", None)
153
- proxies = kwargs.pop("proxies", None)
154
- local_files_only = kwargs.pop("local_files_only", None)
155
- token = kwargs.pop("token", None)
156
- revision = kwargs.pop("revision", None)
157
- subfolder = kwargs.pop("subfolder", None)
158
- weight_name = kwargs.pop("weight_name", None)
159
- use_safetensors = kwargs.pop("use_safetensors", None)
160
- low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
161
- # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
162
- # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
163
- network_alphas = kwargs.pop("network_alphas", None)
164
-
165
- _pipeline = kwargs.pop("_pipeline", None)
166
-
167
- is_network_alphas_none = network_alphas is None
168
-
169
- allow_pickle = False
170
-
171
- if use_safetensors is None:
172
- use_safetensors = True
173
- allow_pickle = True
174
-
175
- user_agent = {
176
- "file_type": "attn_procs_weights",
177
- "framework": "pytorch",
178
- }
179
-
180
- model_file = None
181
- if not isinstance(pretrained_model_name_or_path_or_dict, dict):
182
- # Let's first try to load .safetensors weights
183
- if (use_safetensors and weight_name is None) or (
184
- weight_name is not None and weight_name.endswith(".safetensors")
185
- ):
186
- try:
187
- model_file = _get_model_file(
188
- pretrained_model_name_or_path_or_dict,
189
- weights_name=weight_name or LORA_WEIGHT_NAME_SAFE,
190
- cache_dir=cache_dir,
191
- force_download=force_download,
192
- resume_download=resume_download,
193
- proxies=proxies,
194
- local_files_only=local_files_only,
195
- token=token,
196
- revision=revision,
197
- subfolder=subfolder,
198
- user_agent=user_agent,
199
- )
200
- state_dict = safetensors.torch.load_file(model_file, device="cpu")
201
- except IOError as e:
202
- if not allow_pickle:
203
- raise e
204
- # try loading non-safetensors weights
205
- pass
206
- if model_file is None:
207
- model_file = _get_model_file(
208
- pretrained_model_name_or_path_or_dict,
209
- weights_name=weight_name or LORA_WEIGHT_NAME,
210
- cache_dir=cache_dir,
211
- force_download=force_download,
212
- resume_download=resume_download,
213
- proxies=proxies,
214
- local_files_only=local_files_only,
215
- token=token,
216
- revision=revision,
217
- subfolder=subfolder,
218
- user_agent=user_agent,
219
- )
220
- state_dict = load_state_dict(model_file)
221
- else:
222
- state_dict = pretrained_model_name_or_path_or_dict
223
-
224
- # fill attn processors
225
- lora_layers_list = []
226
-
227
- is_lora = all(("lora" in k or k.endswith(".alpha")) for k in state_dict.keys()) and not USE_PEFT_BACKEND
228
- is_custom_diffusion = any("custom_diffusion" in k for k in state_dict.keys())
229
-
230
- if is_lora:
231
- # correct keys
232
- state_dict, network_alphas = self.convert_state_dict_legacy_attn_format(state_dict, network_alphas)
233
-
234
- if network_alphas is not None:
235
- network_alphas_keys = list(network_alphas.keys())
236
- used_network_alphas_keys = set()
237
-
238
- lora_grouped_dict = defaultdict(dict)
239
- mapped_network_alphas = {}
240
-
241
- all_keys = list(state_dict.keys())
242
- for key in all_keys:
243
- value = state_dict.pop(key)
244
- attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
245
- lora_grouped_dict[attn_processor_key][sub_key] = value
246
-
247
- # Create another `mapped_network_alphas` dictionary so that we can properly map them.
248
- if network_alphas is not None:
249
- for k in network_alphas_keys:
250
- if k.replace(".alpha", "") in key:
251
- mapped_network_alphas.update({attn_processor_key: network_alphas.get(k)})
252
- used_network_alphas_keys.add(k)
253
-
254
- if not is_network_alphas_none:
255
- if len(set(network_alphas_keys) - used_network_alphas_keys) > 0:
256
- raise ValueError(
257
- f"The `network_alphas` has to be empty at this point but has the following keys \n\n {', '.join(network_alphas.keys())}"
258
- )
259
-
260
- if len(state_dict) > 0:
261
- raise ValueError(
262
- f"The `state_dict` has to be empty at this point but has the following keys \n\n {', '.join(state_dict.keys())}"
263
- )
264
-
265
- for key, value_dict in lora_grouped_dict.items():
266
- attn_processor = self
267
- for sub_key in key.split("."):
268
- attn_processor = getattr(attn_processor, sub_key)
269
-
270
- # Process non-attention layers, which don't have to_{k,v,q,out_proj}_lora layers
271
- # or add_{k,v,q,out_proj}_proj_lora layers.
272
- rank = value_dict["lora.down.weight"].shape[0]
273
-
274
- if isinstance(attn_processor, LoRACompatibleConv):
275
- in_features = attn_processor.in_channels
276
- out_features = attn_processor.out_channels
277
- kernel_size = attn_processor.kernel_size
278
-
279
- ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
280
- with ctx():
281
- lora = LoRAConv2dLayer(
282
- in_features=in_features,
283
- out_features=out_features,
284
- rank=rank,
285
- kernel_size=kernel_size,
286
- stride=attn_processor.stride,
287
- padding=attn_processor.padding,
288
- network_alpha=mapped_network_alphas.get(key),
289
- )
290
- elif isinstance(attn_processor, LoRACompatibleLinear):
291
- ctx = init_empty_weights if low_cpu_mem_usage else nullcontext
292
- with ctx():
293
- lora = LoRALinearLayer(
294
- attn_processor.in_features,
295
- attn_processor.out_features,
296
- rank,
297
- mapped_network_alphas.get(key),
298
- )
299
- else:
300
- raise ValueError(f"Module {key} is not a LoRACompatibleConv or LoRACompatibleLinear module.")
301
-
302
- value_dict = {k.replace("lora.", ""): v for k, v in value_dict.items()}
303
- lora_layers_list.append((attn_processor, lora))
304
-
305
- if low_cpu_mem_usage:
306
- device = next(iter(value_dict.values())).device
307
- dtype = next(iter(value_dict.values())).dtype
308
- load_model_dict_into_meta(lora, value_dict, device=device, dtype=dtype)
309
- else:
310
- lora.load_state_dict(value_dict)
311
-
312
- elif is_custom_diffusion:
313
- attn_processors = {}
314
- custom_diffusion_grouped_dict = defaultdict(dict)
315
- for key, value in state_dict.items():
316
- if len(value) == 0:
317
- custom_diffusion_grouped_dict[key] = {}
318
- else:
319
- if "to_out" in key:
320
- attn_processor_key, sub_key = ".".join(key.split(".")[:-3]), ".".join(key.split(".")[-3:])
321
- else:
322
- attn_processor_key, sub_key = ".".join(key.split(".")[:-2]), ".".join(key.split(".")[-2:])
323
- custom_diffusion_grouped_dict[attn_processor_key][sub_key] = value
324
-
325
- for key, value_dict in custom_diffusion_grouped_dict.items():
326
- if len(value_dict) == 0:
327
- attn_processors[key] = CustomDiffusionAttnProcessor(
328
- train_kv=False, train_q_out=False, hidden_size=None, cross_attention_dim=None
329
- )
330
- else:
331
- cross_attention_dim = value_dict["to_k_custom_diffusion.weight"].shape[1]
332
- hidden_size = value_dict["to_k_custom_diffusion.weight"].shape[0]
333
- train_q_out = True if "to_q_custom_diffusion.weight" in value_dict else False
334
- attn_processors[key] = CustomDiffusionAttnProcessor(
335
- train_kv=True,
336
- train_q_out=train_q_out,
337
- hidden_size=hidden_size,
338
- cross_attention_dim=cross_attention_dim,
339
- )
340
- attn_processors[key].load_state_dict(value_dict)
341
- elif USE_PEFT_BACKEND:
342
- # In that case we have nothing to do as loading the adapter weights is already handled above by `set_peft_model_state_dict`
343
- # on the Unet
344
- pass
345
- else:
346
- raise ValueError(
347
- f"{model_file} does not seem to be in the correct format expected by LoRA or Custom Diffusion training."
348
- )
349
-
350
- # <Unsafe code
351
- # We can be sure that the following works as it just sets attention processors, lora layers and puts all in the same dtype
352
- # Now we remove any existing hooks to
353
- is_model_cpu_offload = False
354
- is_sequential_cpu_offload = False
355
-
356
- # For PEFT backend the Unet is already offloaded at this stage as it is handled inside `load_lora_weights_into_unet`
357
- if not USE_PEFT_BACKEND:
358
- if _pipeline is not None:
359
- for _, component in _pipeline.components.items():
360
- if isinstance(component, nn.Module) and hasattr(component, "_hf_hook"):
361
- is_model_cpu_offload = isinstance(getattr(component, "_hf_hook"), CpuOffload)
362
- is_sequential_cpu_offload = (
363
- isinstance(getattr(component, "_hf_hook"), AlignDevicesHook)
364
- or hasattr(component._hf_hook, "hooks")
365
- and isinstance(component._hf_hook.hooks[0], AlignDevicesHook)
366
- )
367
-
368
- logger.info(
369
- "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."
370
- )
371
- remove_hook_from_module(component, recurse=is_sequential_cpu_offload)
372
-
373
- # only custom diffusion needs to set attn processors
374
- if is_custom_diffusion:
375
- self.set_attn_processor(attn_processors)
376
-
377
- # set lora layers
378
- for target_module, lora_layer in lora_layers_list:
379
- target_module.set_lora_layer(lora_layer)
380
-
381
- self.to(dtype=self.dtype, device=self.device)
382
-
383
- # Offload back.
384
- if is_model_cpu_offload:
385
- _pipeline.enable_model_cpu_offload()
386
- elif is_sequential_cpu_offload:
387
- _pipeline.enable_sequential_cpu_offload()
388
- # Unsafe code />
389
-
390
- def convert_state_dict_legacy_attn_format(self, state_dict, network_alphas):
391
- is_new_lora_format = all(
392
- key.startswith(self.unet_name) or key.startswith(self.text_encoder_name) for key in state_dict.keys()
393
- )
394
- if is_new_lora_format:
395
- # Strip the `"unet"` prefix.
396
- is_text_encoder_present = any(key.startswith(self.text_encoder_name) for key in state_dict.keys())
397
- if is_text_encoder_present:
398
- 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)."
399
- logger.warning(warn_message)
400
- unet_keys = [k for k in state_dict.keys() if k.startswith(self.unet_name)]
401
- state_dict = {k.replace(f"{self.unet_name}.", ""): v for k, v in state_dict.items() if k in unet_keys}
402
-
403
- # change processor format to 'pure' LoRACompatibleLinear format
404
- if any("processor" in k.split(".") for k in state_dict.keys()):
405
-
406
- def format_to_lora_compatible(key):
407
- if "processor" not in key.split("."):
408
- return key
409
- return key.replace(".processor", "").replace("to_out_lora", "to_out.0.lora").replace("_lora", ".lora")
410
-
411
- state_dict = {format_to_lora_compatible(k): v for k, v in state_dict.items()}
412
-
413
- if network_alphas is not None:
414
- network_alphas = {format_to_lora_compatible(k): v for k, v in network_alphas.items()}
415
- return state_dict, network_alphas
416
-
417
- def save_attn_procs(
418
- self,
419
- save_directory: Union[str, os.PathLike],
420
- is_main_process: bool = True,
421
- weight_name: str = None,
422
- save_function: Callable = None,
423
- safe_serialization: bool = True,
424
- **kwargs,
425
- ):
426
- r"""
427
- Save attention processor layers to a directory so that it can be reloaded with the
428
- [`~loaders.UNet2DConditionLoadersMixin.load_attn_procs`] method.
429
-
430
- Arguments:
431
- save_directory (`str` or `os.PathLike`):
432
- Directory to save an attention processor to (will be created if it doesn't exist).
433
- is_main_process (`bool`, *optional*, defaults to `True`):
434
- Whether the process calling this is the main process or not. Useful during distributed training and you
435
- need to call this function on all processes. In this case, set `is_main_process=True` only on the main
436
- process to avoid race conditions.
437
- save_function (`Callable`):
438
- The function to use to save the state dictionary. Useful during distributed training when you need to
439
- replace `torch.save` with another method. Can be configured with the environment variable
440
- `DIFFUSERS_SAVE_MODE`.
441
- safe_serialization (`bool`, *optional*, defaults to `True`):
442
- Whether to save the model using `safetensors` or with `pickle`.
443
-
444
- Example:
445
-
446
- ```py
447
- import torch
448
- from diffusers import DiffusionPipeline
449
-
450
- pipeline = DiffusionPipeline.from_pretrained(
451
- "CompVis/stable-diffusion-v1-4",
452
- torch_dtype=torch.float16,
453
- ).to("cuda")
454
- pipeline.unet.load_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
455
- pipeline.unet.save_attn_procs("path-to-save-model", weight_name="pytorch_custom_diffusion_weights.bin")
456
- ```
457
- """
458
- from ..models.attention_processor import (
459
- CustomDiffusionAttnProcessor,
460
- CustomDiffusionAttnProcessor2_0,
461
- CustomDiffusionXFormersAttnProcessor,
462
- )
463
-
464
- if os.path.isfile(save_directory):
465
- logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
466
- return
467
-
468
- if save_function is None:
469
- if safe_serialization:
470
-
471
- def save_function(weights, filename):
472
- return safetensors.torch.save_file(weights, filename, metadata={"format": "pt"})
473
-
474
- else:
475
- save_function = torch.save
476
-
477
- os.makedirs(save_directory, exist_ok=True)
478
-
479
- is_custom_diffusion = any(
480
- isinstance(
481
- x,
482
- (CustomDiffusionAttnProcessor, CustomDiffusionAttnProcessor2_0, CustomDiffusionXFormersAttnProcessor),
483
- )
484
- for (_, x) in self.attn_processors.items()
485
- )
486
- if is_custom_diffusion:
487
- model_to_save = AttnProcsLayers(
488
- {
489
- y: x
490
- for (y, x) in self.attn_processors.items()
491
- if isinstance(
492
- x,
493
- (
494
- CustomDiffusionAttnProcessor,
495
- CustomDiffusionAttnProcessor2_0,
496
- CustomDiffusionXFormersAttnProcessor,
497
- ),
498
- )
499
- }
500
- )
501
- state_dict = model_to_save.state_dict()
502
- for name, attn in self.attn_processors.items():
503
- if len(attn.state_dict()) == 0:
504
- state_dict[name] = {}
505
- else:
506
- model_to_save = AttnProcsLayers(self.attn_processors)
507
- state_dict = model_to_save.state_dict()
508
-
509
- if weight_name is None:
510
- if safe_serialization:
511
- weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME_SAFE if is_custom_diffusion else LORA_WEIGHT_NAME_SAFE
512
- else:
513
- weight_name = CUSTOM_DIFFUSION_WEIGHT_NAME if is_custom_diffusion else LORA_WEIGHT_NAME
514
-
515
- # Save the model
516
- save_path = Path(save_directory, weight_name).as_posix()
517
- save_function(state_dict, save_path)
518
- logger.info(f"Model weights saved in {save_path}")
519
-
520
- def fuse_lora(self, lora_scale=1.0, safe_fusing=False, adapter_names=None):
521
- self.lora_scale = lora_scale
522
- self._safe_fusing = safe_fusing
523
- self.apply(partial(self._fuse_lora_apply, adapter_names=adapter_names))
524
-
525
- def _fuse_lora_apply(self, module, adapter_names=None):
526
- if not USE_PEFT_BACKEND:
527
- if hasattr(module, "_fuse_lora"):
528
- module._fuse_lora(self.lora_scale, self._safe_fusing)
529
-
530
- if adapter_names is not None:
531
- raise ValueError(
532
- "The `adapter_names` argument is not supported in your environment. Please switch"
533
- " to PEFT backend to use this argument by installing latest PEFT and transformers."
534
- " `pip install -U peft transformers`"
535
- )
536
- else:
537
- from peft.tuners.tuners_utils import BaseTunerLayer
538
-
539
- merge_kwargs = {"safe_merge": self._safe_fusing}
540
-
541
- if isinstance(module, BaseTunerLayer):
542
- if self.lora_scale != 1.0:
543
- module.scale_layer(self.lora_scale)
544
-
545
- # For BC with prevous PEFT versions, we need to check the signature
546
- # of the `merge` method to see if it supports the `adapter_names` argument.
547
- supported_merge_kwargs = list(inspect.signature(module.merge).parameters)
548
- if "adapter_names" in supported_merge_kwargs:
549
- merge_kwargs["adapter_names"] = adapter_names
550
- elif "adapter_names" not in supported_merge_kwargs and adapter_names is not None:
551
- raise ValueError(
552
- "The `adapter_names` argument is not supported with your PEFT version. Please upgrade"
553
- " to the latest version of PEFT. `pip install -U peft`"
554
- )
555
-
556
- module.merge(**merge_kwargs)
557
-
558
- def unfuse_lora(self):
559
- self.apply(self._unfuse_lora_apply)
560
-
561
- def _unfuse_lora_apply(self, module):
562
- if not USE_PEFT_BACKEND:
563
- if hasattr(module, "_unfuse_lora"):
564
- module._unfuse_lora()
565
- else:
566
- from peft.tuners.tuners_utils import BaseTunerLayer
567
-
568
- if isinstance(module, BaseTunerLayer):
569
- module.unmerge()
570
-
571
- def set_adapters(
572
- self,
573
- adapter_names: Union[List[str], str],
574
- weights: Optional[Union[float, Dict, List[float], List[Dict], List[None]]] = None,
575
- ):
576
- """
577
- Set the currently active adapters for use in the UNet.
578
-
579
- Args:
580
- adapter_names (`List[str]` or `str`):
581
- The names of the adapters to use.
582
- adapter_weights (`Union[List[float], float]`, *optional*):
583
- The adapter(s) weights to use with the UNet. If `None`, the weights are set to `1.0` for all the
584
- adapters.
585
-
586
- Example:
587
-
588
- ```py
589
- from diffusers import AutoPipelineForText2Image
590
- import torch
591
-
592
- pipeline = AutoPipelineForText2Image.from_pretrained(
593
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
594
- ).to("cuda")
595
- pipeline.load_lora_weights(
596
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
597
- )
598
- pipeline.load_lora_weights("nerijs/pixel-art-xl", weight_name="pixel-art-xl.safetensors", adapter_name="pixel")
599
- pipeline.set_adapters(["cinematic", "pixel"], adapter_weights=[0.5, 0.5])
600
- ```
601
- """
602
- if not USE_PEFT_BACKEND:
603
- raise ValueError("PEFT backend is required for `set_adapters()`.")
604
-
605
- adapter_names = [adapter_names] if isinstance(adapter_names, str) else adapter_names
606
-
607
- # Expand weights into a list, one entry per adapter
608
- # examples for e.g. 2 adapters: [{...}, 7] -> [7,7] ; None -> [None, None]
609
- if not isinstance(weights, list):
610
- weights = [weights] * len(adapter_names)
611
-
612
- if len(adapter_names) != len(weights):
613
- raise ValueError(
614
- f"Length of adapter names {len(adapter_names)} is not equal to the length of their weights {len(weights)}."
615
- )
616
-
617
- # Set None values to default of 1.0
618
- # e.g. [{...}, 7] -> [{...}, 7] ; [None, None] -> [1.0, 1.0]
619
- weights = [w if w is not None else 1.0 for w in weights]
620
-
621
- # e.g. [{...}, 7] -> [{expanded dict...}, 7]
622
- weights = _maybe_expand_lora_scales(self, weights)
623
-
624
- set_weights_and_activate_adapters(self, adapter_names, weights)
625
-
626
- def disable_lora(self):
627
- """
628
- Disable the UNet's active LoRA layers.
629
-
630
- Example:
631
-
632
- ```py
633
- from diffusers import AutoPipelineForText2Image
634
- import torch
635
-
636
- pipeline = AutoPipelineForText2Image.from_pretrained(
637
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
638
- ).to("cuda")
639
- pipeline.load_lora_weights(
640
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
641
- )
642
- pipeline.disable_lora()
643
- ```
644
- """
645
- if not USE_PEFT_BACKEND:
646
- raise ValueError("PEFT backend is required for this method.")
647
- set_adapter_layers(self, enabled=False)
648
-
649
- def enable_lora(self):
650
- """
651
- Enable the UNet's active LoRA layers.
652
-
653
- Example:
654
-
655
- ```py
656
- from diffusers import AutoPipelineForText2Image
657
- import torch
658
-
659
- pipeline = AutoPipelineForText2Image.from_pretrained(
660
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
661
- ).to("cuda")
662
- pipeline.load_lora_weights(
663
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_name="cinematic"
664
- )
665
- pipeline.enable_lora()
666
- ```
667
- """
668
- if not USE_PEFT_BACKEND:
669
- raise ValueError("PEFT backend is required for this method.")
670
- set_adapter_layers(self, enabled=True)
671
-
672
- def delete_adapters(self, adapter_names: Union[List[str], str]):
673
- """
674
- Delete an adapter's LoRA layers from the UNet.
675
-
676
- Args:
677
- adapter_names (`Union[List[str], str]`):
678
- The names (single string or list of strings) of the adapter to delete.
679
-
680
- Example:
681
-
682
- ```py
683
- from diffusers import AutoPipelineForText2Image
684
- import torch
685
-
686
- pipeline = AutoPipelineForText2Image.from_pretrained(
687
- "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
688
- ).to("cuda")
689
- pipeline.load_lora_weights(
690
- "jbilcke-hf/sdxl-cinematic-1", weight_name="pytorch_lora_weights.safetensors", adapter_names="cinematic"
691
- )
692
- pipeline.delete_adapters("cinematic")
693
- ```
694
- """
695
- if not USE_PEFT_BACKEND:
696
- raise ValueError("PEFT backend is required for this method.")
697
-
698
- if isinstance(adapter_names, str):
699
- adapter_names = [adapter_names]
700
-
701
- for adapter_name in adapter_names:
702
- delete_adapter_layers(self, adapter_name)
703
-
704
- # Pop also the corresponding adapter from the config
705
- if hasattr(self, "peft_config"):
706
- self.peft_config.pop(adapter_name, None)
707
-
708
- def _convert_ip_adapter_image_proj_to_diffusers(self, state_dict, low_cpu_mem_usage=False):
709
- if low_cpu_mem_usage:
710
- if is_accelerate_available():
711
- from accelerate import init_empty_weights
712
-
713
- else:
714
- low_cpu_mem_usage = False
715
- logger.warning(
716
- "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
717
- " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
718
- " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
719
- " install accelerate\n```\n."
720
- )
721
-
722
- if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
723
- raise NotImplementedError(
724
- "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
725
- " `low_cpu_mem_usage=False`."
726
- )
727
-
728
- updated_state_dict = {}
729
- image_projection = None
730
- init_context = init_empty_weights if low_cpu_mem_usage else nullcontext
731
-
732
- if "proj.weight" in state_dict:
733
- # IP-Adapter
734
- num_image_text_embeds = 4
735
- clip_embeddings_dim = state_dict["proj.weight"].shape[-1]
736
- cross_attention_dim = state_dict["proj.weight"].shape[0] // 4
737
-
738
- with init_context():
739
- image_projection = ImageProjection(
740
- cross_attention_dim=cross_attention_dim,
741
- image_embed_dim=clip_embeddings_dim,
742
- num_image_text_embeds=num_image_text_embeds,
743
- )
744
-
745
- for key, value in state_dict.items():
746
- diffusers_name = key.replace("proj", "image_embeds")
747
- updated_state_dict[diffusers_name] = value
748
-
749
- elif "proj.3.weight" in state_dict:
750
- # IP-Adapter Full
751
- clip_embeddings_dim = state_dict["proj.0.weight"].shape[0]
752
- cross_attention_dim = state_dict["proj.3.weight"].shape[0]
753
-
754
- with init_context():
755
- image_projection = IPAdapterFullImageProjection(
756
- cross_attention_dim=cross_attention_dim, image_embed_dim=clip_embeddings_dim
757
- )
758
-
759
- for key, value in state_dict.items():
760
- diffusers_name = key.replace("proj.0", "ff.net.0.proj")
761
- diffusers_name = diffusers_name.replace("proj.2", "ff.net.2")
762
- diffusers_name = diffusers_name.replace("proj.3", "norm")
763
- updated_state_dict[diffusers_name] = value
764
-
765
- elif "perceiver_resampler.proj_in.weight" in state_dict:
766
- # IP-Adapter Face ID Plus
767
- id_embeddings_dim = state_dict["proj.0.weight"].shape[1]
768
- embed_dims = state_dict["perceiver_resampler.proj_in.weight"].shape[0]
769
- hidden_dims = state_dict["perceiver_resampler.proj_in.weight"].shape[1]
770
- output_dims = state_dict["perceiver_resampler.proj_out.weight"].shape[0]
771
- heads = state_dict["perceiver_resampler.layers.0.0.to_q.weight"].shape[0] // 64
772
-
773
- with init_context():
774
- image_projection = IPAdapterFaceIDPlusImageProjection(
775
- embed_dims=embed_dims,
776
- output_dims=output_dims,
777
- hidden_dims=hidden_dims,
778
- heads=heads,
779
- id_embeddings_dim=id_embeddings_dim,
780
- )
781
-
782
- for key, value in state_dict.items():
783
- diffusers_name = key.replace("perceiver_resampler.", "")
784
- diffusers_name = diffusers_name.replace("0.to", "attn.to")
785
- diffusers_name = diffusers_name.replace("0.1.0.", "0.ff.0.")
786
- diffusers_name = diffusers_name.replace("0.1.1.weight", "0.ff.1.net.0.proj.weight")
787
- diffusers_name = diffusers_name.replace("0.1.3.weight", "0.ff.1.net.2.weight")
788
- diffusers_name = diffusers_name.replace("1.1.0.", "1.ff.0.")
789
- diffusers_name = diffusers_name.replace("1.1.1.weight", "1.ff.1.net.0.proj.weight")
790
- diffusers_name = diffusers_name.replace("1.1.3.weight", "1.ff.1.net.2.weight")
791
- diffusers_name = diffusers_name.replace("2.1.0.", "2.ff.0.")
792
- diffusers_name = diffusers_name.replace("2.1.1.weight", "2.ff.1.net.0.proj.weight")
793
- diffusers_name = diffusers_name.replace("2.1.3.weight", "2.ff.1.net.2.weight")
794
- diffusers_name = diffusers_name.replace("3.1.0.", "3.ff.0.")
795
- diffusers_name = diffusers_name.replace("3.1.1.weight", "3.ff.1.net.0.proj.weight")
796
- diffusers_name = diffusers_name.replace("3.1.3.weight", "3.ff.1.net.2.weight")
797
- diffusers_name = diffusers_name.replace("layers.0.0", "layers.0.ln0")
798
- diffusers_name = diffusers_name.replace("layers.0.1", "layers.0.ln1")
799
- diffusers_name = diffusers_name.replace("layers.1.0", "layers.1.ln0")
800
- diffusers_name = diffusers_name.replace("layers.1.1", "layers.1.ln1")
801
- diffusers_name = diffusers_name.replace("layers.2.0", "layers.2.ln0")
802
- diffusers_name = diffusers_name.replace("layers.2.1", "layers.2.ln1")
803
- diffusers_name = diffusers_name.replace("layers.3.0", "layers.3.ln0")
804
- diffusers_name = diffusers_name.replace("layers.3.1", "layers.3.ln1")
805
-
806
- if "norm1" in diffusers_name:
807
- updated_state_dict[diffusers_name.replace("0.norm1", "0")] = value
808
- elif "norm2" in diffusers_name:
809
- updated_state_dict[diffusers_name.replace("0.norm2", "1")] = value
810
- elif "to_kv" in diffusers_name:
811
- v_chunk = value.chunk(2, dim=0)
812
- updated_state_dict[diffusers_name.replace("to_kv", "to_k")] = v_chunk[0]
813
- updated_state_dict[diffusers_name.replace("to_kv", "to_v")] = v_chunk[1]
814
- elif "to_out" in diffusers_name:
815
- updated_state_dict[diffusers_name.replace("to_out", "to_out.0")] = value
816
- elif "proj.0.weight" == diffusers_name:
817
- updated_state_dict["proj.net.0.proj.weight"] = value
818
- elif "proj.0.bias" == diffusers_name:
819
- updated_state_dict["proj.net.0.proj.bias"] = value
820
- elif "proj.2.weight" == diffusers_name:
821
- updated_state_dict["proj.net.2.weight"] = value
822
- elif "proj.2.bias" == diffusers_name:
823
- updated_state_dict["proj.net.2.bias"] = value
824
- else:
825
- updated_state_dict[diffusers_name] = value
826
-
827
- elif "norm.weight" in state_dict:
828
- # IP-Adapter Face ID
829
- id_embeddings_dim_in = state_dict["proj.0.weight"].shape[1]
830
- id_embeddings_dim_out = state_dict["proj.0.weight"].shape[0]
831
- multiplier = id_embeddings_dim_out // id_embeddings_dim_in
832
- norm_layer = "norm.weight"
833
- cross_attention_dim = state_dict[norm_layer].shape[0]
834
- num_tokens = state_dict["proj.2.weight"].shape[0] // cross_attention_dim
835
-
836
- with init_context():
837
- image_projection = IPAdapterFaceIDImageProjection(
838
- cross_attention_dim=cross_attention_dim,
839
- image_embed_dim=id_embeddings_dim_in,
840
- mult=multiplier,
841
- num_tokens=num_tokens,
842
- )
843
-
844
- for key, value in state_dict.items():
845
- diffusers_name = key.replace("proj.0", "ff.net.0.proj")
846
- diffusers_name = diffusers_name.replace("proj.2", "ff.net.2")
847
- updated_state_dict[diffusers_name] = value
848
-
849
- else:
850
- # IP-Adapter Plus
851
- num_image_text_embeds = state_dict["latents"].shape[1]
852
- embed_dims = state_dict["proj_in.weight"].shape[1]
853
- output_dims = state_dict["proj_out.weight"].shape[0]
854
- hidden_dims = state_dict["latents"].shape[2]
855
- heads = state_dict["layers.0.0.to_q.weight"].shape[0] // 64
856
-
857
- with init_context():
858
- image_projection = IPAdapterPlusImageProjection(
859
- embed_dims=embed_dims,
860
- output_dims=output_dims,
861
- hidden_dims=hidden_dims,
862
- heads=heads,
863
- num_queries=num_image_text_embeds,
864
- )
865
-
866
- for key, value in state_dict.items():
867
- diffusers_name = key.replace("0.to", "2.to")
868
- diffusers_name = diffusers_name.replace("1.0.weight", "3.0.weight")
869
- diffusers_name = diffusers_name.replace("1.0.bias", "3.0.bias")
870
- diffusers_name = diffusers_name.replace("1.1.weight", "3.1.net.0.proj.weight")
871
- diffusers_name = diffusers_name.replace("1.3.weight", "3.1.net.2.weight")
872
-
873
- if "norm1" in diffusers_name:
874
- updated_state_dict[diffusers_name.replace("0.norm1", "0")] = value
875
- elif "norm2" in diffusers_name:
876
- updated_state_dict[diffusers_name.replace("0.norm2", "1")] = value
877
- elif "to_kv" in diffusers_name:
878
- v_chunk = value.chunk(2, dim=0)
879
- updated_state_dict[diffusers_name.replace("to_kv", "to_k")] = v_chunk[0]
880
- updated_state_dict[diffusers_name.replace("to_kv", "to_v")] = v_chunk[1]
881
- elif "to_out" in diffusers_name:
882
- updated_state_dict[diffusers_name.replace("to_out", "to_out.0")] = value
883
- else:
884
- updated_state_dict[diffusers_name] = value
885
-
886
- if not low_cpu_mem_usage:
887
- image_projection.load_state_dict(updated_state_dict)
888
- else:
889
- load_model_dict_into_meta(image_projection, updated_state_dict, device=self.device, dtype=self.dtype)
890
-
891
- return image_projection
892
-
893
- def _convert_ip_adapter_attn_to_diffusers(self, state_dicts, low_cpu_mem_usage=False):
894
- from ..models.attention_processor import (
895
- AttnProcessor,
896
- AttnProcessor2_0,
897
- IPAdapterAttnProcessor,
898
- IPAdapterAttnProcessor2_0,
899
- )
900
-
901
- if low_cpu_mem_usage:
902
- if is_accelerate_available():
903
- from accelerate import init_empty_weights
904
-
905
- else:
906
- low_cpu_mem_usage = False
907
- logger.warning(
908
- "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
909
- " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
910
- " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
911
- " install accelerate\n```\n."
912
- )
913
-
914
- if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
915
- raise NotImplementedError(
916
- "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
917
- " `low_cpu_mem_usage=False`."
918
- )
919
-
920
- # set ip-adapter cross-attention processors & load state_dict
921
- attn_procs = {}
922
- key_id = 1
923
- init_context = init_empty_weights if low_cpu_mem_usage else nullcontext
924
- for name in self.attn_processors.keys():
925
- cross_attention_dim = None if name.endswith("attn1.processor") else self.config.cross_attention_dim
926
- if name.startswith("mid_block"):
927
- hidden_size = self.config.block_out_channels[-1]
928
- elif name.startswith("up_blocks"):
929
- block_id = int(name[len("up_blocks.")])
930
- hidden_size = list(reversed(self.config.block_out_channels))[block_id]
931
- elif name.startswith("down_blocks"):
932
- block_id = int(name[len("down_blocks.")])
933
- hidden_size = self.config.block_out_channels[block_id]
934
-
935
- if cross_attention_dim is None or "motion_modules" in name:
936
- attn_processor_class = (
937
- AttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else AttnProcessor
938
- )
939
- attn_procs[name] = attn_processor_class()
940
-
941
- else:
942
- attn_processor_class = (
943
- IPAdapterAttnProcessor2_0 if hasattr(F, "scaled_dot_product_attention") else IPAdapterAttnProcessor
944
- )
945
- num_image_text_embeds = []
946
- for state_dict in state_dicts:
947
- if "proj.weight" in state_dict["image_proj"]:
948
- # IP-Adapter
949
- num_image_text_embeds += [4]
950
- elif "proj.3.weight" in state_dict["image_proj"]:
951
- # IP-Adapter Full Face
952
- num_image_text_embeds += [257] # 256 CLIP tokens + 1 CLS token
953
- elif "perceiver_resampler.proj_in.weight" in state_dict["image_proj"]:
954
- # IP-Adapter Face ID Plus
955
- num_image_text_embeds += [4]
956
- elif "norm.weight" in state_dict["image_proj"]:
957
- # IP-Adapter Face ID
958
- num_image_text_embeds += [4]
959
- else:
960
- # IP-Adapter Plus
961
- num_image_text_embeds += [state_dict["image_proj"]["latents"].shape[1]]
962
-
963
- with init_context():
964
- attn_procs[name] = attn_processor_class(
965
- hidden_size=hidden_size,
966
- cross_attention_dim=cross_attention_dim,
967
- scale=1.0,
968
- num_tokens=num_image_text_embeds,
969
- )
970
-
971
- value_dict = {}
972
- for i, state_dict in enumerate(state_dicts):
973
- value_dict.update({f"to_k_ip.{i}.weight": state_dict["ip_adapter"][f"{key_id}.to_k_ip.weight"]})
974
- value_dict.update({f"to_v_ip.{i}.weight": state_dict["ip_adapter"][f"{key_id}.to_v_ip.weight"]})
975
-
976
- if not low_cpu_mem_usage:
977
- attn_procs[name].load_state_dict(value_dict)
978
- else:
979
- device = next(iter(value_dict.values())).device
980
- dtype = next(iter(value_dict.values())).dtype
981
- load_model_dict_into_meta(attn_procs[name], value_dict, device=device, dtype=dtype)
982
-
983
- key_id += 2
984
-
985
- return attn_procs
986
-
987
- def _load_ip_adapter_weights(self, state_dicts, low_cpu_mem_usage=False):
988
- if not isinstance(state_dicts, list):
989
- state_dicts = [state_dicts]
990
- # Set encoder_hid_proj after loading ip_adapter weights,
991
- # because `IPAdapterPlusImageProjection` also has `attn_processors`.
992
- self.encoder_hid_proj = None
993
-
994
- attn_procs = self._convert_ip_adapter_attn_to_diffusers(state_dicts, low_cpu_mem_usage=low_cpu_mem_usage)
995
- self.set_attn_processor(attn_procs)
996
-
997
- # convert IP-Adapter Image Projection layers to diffusers
998
- image_projection_layers = []
999
- for state_dict in state_dicts:
1000
- image_projection_layer = self._convert_ip_adapter_image_proj_to_diffusers(
1001
- state_dict["image_proj"], low_cpu_mem_usage=low_cpu_mem_usage
1002
- )
1003
- image_projection_layers.append(image_projection_layer)
1004
-
1005
- self.encoder_hid_proj = MultiIPAdapterImageProjection(image_projection_layers)
1006
- self.config.encoder_hid_dim_type = "ip_image_proj"
1007
-
1008
- self.to(dtype=self.dtype, device=self.device)
1009
-
1010
- def _load_ip_adapter_loras(self, state_dicts):
1011
- lora_dicts = {}
1012
- for key_id, name in enumerate(self.attn_processors.keys()):
1013
- for i, state_dict in enumerate(state_dicts):
1014
- if f"{key_id}.to_k_lora.down.weight" in state_dict["ip_adapter"]:
1015
- if i not in lora_dicts:
1016
- lora_dicts[i] = {}
1017
- lora_dicts[i].update(
1018
- {
1019
- f"unet.{name}.to_k_lora.down.weight": state_dict["ip_adapter"][
1020
- f"{key_id}.to_k_lora.down.weight"
1021
- ]
1022
- }
1023
- )
1024
- lora_dicts[i].update(
1025
- {
1026
- f"unet.{name}.to_q_lora.down.weight": state_dict["ip_adapter"][
1027
- f"{key_id}.to_q_lora.down.weight"
1028
- ]
1029
- }
1030
- )
1031
- lora_dicts[i].update(
1032
- {
1033
- f"unet.{name}.to_v_lora.down.weight": state_dict["ip_adapter"][
1034
- f"{key_id}.to_v_lora.down.weight"
1035
- ]
1036
- }
1037
- )
1038
- lora_dicts[i].update(
1039
- {
1040
- f"unet.{name}.to_out_lora.down.weight": state_dict["ip_adapter"][
1041
- f"{key_id}.to_out_lora.down.weight"
1042
- ]
1043
- }
1044
- )
1045
- lora_dicts[i].update(
1046
- {f"unet.{name}.to_k_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_k_lora.up.weight"]}
1047
- )
1048
- lora_dicts[i].update(
1049
- {f"unet.{name}.to_q_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_q_lora.up.weight"]}
1050
- )
1051
- lora_dicts[i].update(
1052
- {f"unet.{name}.to_v_lora.up.weight": state_dict["ip_adapter"][f"{key_id}.to_v_lora.up.weight"]}
1053
- )
1054
- lora_dicts[i].update(
1055
- {
1056
- f"unet.{name}.to_out_lora.up.weight": state_dict["ip_adapter"][
1057
- f"{key_id}.to_out_lora.up.weight"
1058
- ]
1059
- }
1060
- )
1061
- return lora_dicts
1062
-
1063
-
1064
- class FromOriginalUNetMixin:
1065
- """
1066
- Load pretrained UNet model weights saved in the `.ckpt` or `.safetensors` format into a [`StableCascadeUNet`].
1067
- """
1068
-
1069
- @classmethod
1070
- @validate_hf_hub_args
1071
- def from_single_file(cls, pretrained_model_link_or_path, **kwargs):
1072
- r"""
1073
- Instantiate a [`StableCascadeUNet`] from pretrained StableCascadeUNet weights saved in the original `.ckpt` or
1074
- `.safetensors` format. The pipeline is set in evaluation mode (`model.eval()`) by default.
1075
-
1076
- Parameters:
1077
- pretrained_model_link_or_path (`str` or `os.PathLike`, *optional*):
1078
- Can be either:
1079
- - A link to the `.ckpt` file (for example
1080
- `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.ckpt"`) on the Hub.
1081
- - A path to a *file* containing all pipeline weights.
1082
- config: (`dict`, *optional*):
1083
- Dictionary containing the configuration of the model:
1084
- torch_dtype (`str` or `torch.dtype`, *optional*):
1085
- Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
1086
- dtype is automatically derived from the model's weights.
1087
- force_download (`bool`, *optional*, defaults to `False`):
1088
- Whether or not to force the (re-)download of the model weights and configuration files, overriding the
1089
- cached versions if they exist.
1090
- cache_dir (`Union[str, os.PathLike]`, *optional*):
1091
- Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
1092
- is not used.
1093
- resume_download:
1094
- Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
1095
- of Diffusers.
1096
- proxies (`Dict[str, str]`, *optional*):
1097
- A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
1098
- 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
1099
- local_files_only (`bool`, *optional*, defaults to `False`):
1100
- Whether to only load local model weights and configuration files or not. If set to True, the model
1101
- won't be downloaded from the Hub.
1102
- token (`str` or *bool*, *optional*):
1103
- The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
1104
- `diffusers-cli login` (stored in `~/.huggingface`) is used.
1105
- revision (`str`, *optional*, defaults to `"main"`):
1106
- The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
1107
- allowed by Git.
1108
- kwargs (remaining dictionary of keyword arguments, *optional*):
1109
- Can be used to overwrite load and saveable variables of the model.
1110
-
1111
- """
1112
- class_name = cls.__name__
1113
- if class_name != "StableCascadeUNet":
1114
- raise ValueError("FromOriginalUNetMixin is currently only compatible with StableCascadeUNet")
1115
-
1116
- config = kwargs.pop("config", None)
1117
- resume_download = kwargs.pop("resume_download", None)
1118
- force_download = kwargs.pop("force_download", False)
1119
- proxies = kwargs.pop("proxies", None)
1120
- token = kwargs.pop("token", None)
1121
- cache_dir = kwargs.pop("cache_dir", None)
1122
- local_files_only = kwargs.pop("local_files_only", None)
1123
- revision = kwargs.pop("revision", None)
1124
- torch_dtype = kwargs.pop("torch_dtype", None)
1125
-
1126
- checkpoint = load_single_file_model_checkpoint(
1127
- pretrained_model_link_or_path,
1128
- resume_download=resume_download,
1129
- force_download=force_download,
1130
- proxies=proxies,
1131
- token=token,
1132
- cache_dir=cache_dir,
1133
- local_files_only=local_files_only,
1134
- revision=revision,
1135
- )
1136
-
1137
- if config is None:
1138
- config = infer_stable_cascade_single_file_config(checkpoint)
1139
- model_config = cls.load_config(**config, **kwargs)
1140
- else:
1141
- model_config = config
1142
-
1143
- ctx = init_empty_weights if is_accelerate_available() else nullcontext
1144
- with ctx():
1145
- model = cls.from_config(model_config, **kwargs)
1146
-
1147
- diffusers_format_checkpoint = convert_stable_cascade_unet_single_file_to_diffusers(checkpoint)
1148
- if is_accelerate_available():
1149
- unexpected_keys = load_model_dict_into_meta(model, diffusers_format_checkpoint, dtype=torch_dtype)
1150
- if len(unexpected_keys) > 0:
1151
- logger.warning(
1152
- f"Some weights of the model checkpoint were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
1153
- )
1154
-
1155
- else:
1156
- model.load_state_dict(diffusers_format_checkpoint)
1157
-
1158
- if torch_dtype is not None:
1159
- model.to(torch_dtype)
1160
-
1161
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/unet_loader_utils.py DELETED
@@ -1,163 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import copy
15
- from typing import TYPE_CHECKING, Dict, List, Union
16
-
17
- from ..utils import logging
18
-
19
-
20
- if TYPE_CHECKING:
21
- # import here to avoid circular imports
22
- from ..models import UNet2DConditionModel
23
-
24
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
25
-
26
-
27
- def _translate_into_actual_layer_name(name):
28
- """Translate user-friendly name (e.g. 'mid') into actual layer name (e.g. 'mid_block.attentions.0')"""
29
- if name == "mid":
30
- return "mid_block.attentions.0"
31
-
32
- updown, block, attn = name.split(".")
33
-
34
- updown = updown.replace("down", "down_blocks").replace("up", "up_blocks")
35
- block = block.replace("block_", "")
36
- attn = "attentions." + attn
37
-
38
- return ".".join((updown, block, attn))
39
-
40
-
41
- def _maybe_expand_lora_scales(
42
- unet: "UNet2DConditionModel", weight_scales: List[Union[float, Dict]], default_scale=1.0
43
- ):
44
- blocks_with_transformer = {
45
- "down": [i for i, block in enumerate(unet.down_blocks) if hasattr(block, "attentions")],
46
- "up": [i for i, block in enumerate(unet.up_blocks) if hasattr(block, "attentions")],
47
- }
48
- transformer_per_block = {"down": unet.config.layers_per_block, "up": unet.config.layers_per_block + 1}
49
-
50
- expanded_weight_scales = [
51
- _maybe_expand_lora_scales_for_one_adapter(
52
- weight_for_adapter,
53
- blocks_with_transformer,
54
- transformer_per_block,
55
- unet.state_dict(),
56
- default_scale=default_scale,
57
- )
58
- for weight_for_adapter in weight_scales
59
- ]
60
-
61
- return expanded_weight_scales
62
-
63
-
64
- def _maybe_expand_lora_scales_for_one_adapter(
65
- scales: Union[float, Dict],
66
- blocks_with_transformer: Dict[str, int],
67
- transformer_per_block: Dict[str, int],
68
- state_dict: None,
69
- default_scale: float = 1.0,
70
- ):
71
- """
72
- Expands the inputs into a more granular dictionary. See the example below for more details.
73
-
74
- Parameters:
75
- scales (`Union[float, Dict]`):
76
- Scales dict to expand.
77
- blocks_with_transformer (`Dict[str, int]`):
78
- Dict with keys 'up' and 'down', showing which blocks have transformer layers
79
- transformer_per_block (`Dict[str, int]`):
80
- Dict with keys 'up' and 'down', showing how many transformer layers each block has
81
-
82
- E.g. turns
83
- ```python
84
- scales = {"down": 2, "mid": 3, "up": {"block_0": 4, "block_1": [5, 6, 7]}}
85
- blocks_with_transformer = {"down": [1, 2], "up": [0, 1]}
86
- transformer_per_block = {"down": 2, "up": 3}
87
- ```
88
- into
89
- ```python
90
- {
91
- "down.block_1.0": 2,
92
- "down.block_1.1": 2,
93
- "down.block_2.0": 2,
94
- "down.block_2.1": 2,
95
- "mid": 3,
96
- "up.block_0.0": 4,
97
- "up.block_0.1": 4,
98
- "up.block_0.2": 4,
99
- "up.block_1.0": 5,
100
- "up.block_1.1": 6,
101
- "up.block_1.2": 7,
102
- }
103
- ```
104
- """
105
- if sorted(blocks_with_transformer.keys()) != ["down", "up"]:
106
- raise ValueError("blocks_with_transformer needs to be a dict with keys `'down' and `'up'`")
107
-
108
- if sorted(transformer_per_block.keys()) != ["down", "up"]:
109
- raise ValueError("transformer_per_block needs to be a dict with keys `'down' and `'up'`")
110
-
111
- if not isinstance(scales, dict):
112
- # don't expand if scales is a single number
113
- return scales
114
-
115
- scales = copy.deepcopy(scales)
116
-
117
- if "mid" not in scales:
118
- scales["mid"] = default_scale
119
- elif isinstance(scales["mid"], list):
120
- if len(scales["mid"]) == 1:
121
- scales["mid"] = scales["mid"][0]
122
- else:
123
- raise ValueError(f"Expected 1 scales for mid, got {len(scales['mid'])}.")
124
-
125
- for updown in ["up", "down"]:
126
- if updown not in scales:
127
- scales[updown] = default_scale
128
-
129
- # eg {"down": 1} to {"down": {"block_1": 1, "block_2": 1}}}
130
- if not isinstance(scales[updown], dict):
131
- scales[updown] = {f"block_{i}": copy.deepcopy(scales[updown]) for i in blocks_with_transformer[updown]}
132
-
133
- # eg {"down": {"block_1": 1}} to {"down": {"block_1": [1, 1]}}
134
- for i in blocks_with_transformer[updown]:
135
- block = f"block_{i}"
136
- # set not assigned blocks to default scale
137
- if block not in scales[updown]:
138
- scales[updown][block] = default_scale
139
- if not isinstance(scales[updown][block], list):
140
- scales[updown][block] = [scales[updown][block] for _ in range(transformer_per_block[updown])]
141
- elif len(scales[updown][block]) == 1:
142
- # a list specifying scale to each masked IP input
143
- scales[updown][block] = scales[updown][block] * transformer_per_block[updown]
144
- elif len(scales[updown][block]) != transformer_per_block[updown]:
145
- raise ValueError(
146
- f"Expected {transformer_per_block[updown]} scales for {updown}.{block}, got {len(scales[updown][block])}."
147
- )
148
-
149
- # eg {"down": "block_1": [1, 1]}} to {"down.block_1.0": 1, "down.block_1.1": 1}
150
- for i in blocks_with_transformer[updown]:
151
- block = f"block_{i}"
152
- for tf_idx, value in enumerate(scales[updown][block]):
153
- scales[f"{updown}.{block}.{tf_idx}"] = value
154
-
155
- del scales[updown]
156
-
157
- for layer in scales.keys():
158
- if not any(_translate_into_actual_layer_name(layer) in module for module in state_dict.keys()):
159
- raise ValueError(
160
- f"Can't set lora scale for layer {layer}. It either doesn't exist in this unet or it has no attentions."
161
- )
162
-
163
- return {_translate_into_actual_layer_name(name): weight for name, weight in scales.items()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/loaders/utils.py DELETED
@@ -1,59 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from 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 DELETED
@@ -1,3 +0,0 @@
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 DELETED
@@ -1,105 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from 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["autoencoders.autoencoder_asym_kl"] = ["AsymmetricAutoencoderKL"]
30
- _import_structure["autoencoders.autoencoder_kl"] = ["AutoencoderKL"]
31
- _import_structure["autoencoders.autoencoder_kl_temporal_decoder"] = ["AutoencoderKLTemporalDecoder"]
32
- _import_structure["autoencoders.autoencoder_tiny"] = ["AutoencoderTiny"]
33
- _import_structure["autoencoders.consistency_decoder_vae"] = ["ConsistencyDecoderVAE"]
34
- _import_structure["controlnet"] = ["ControlNetModel"]
35
- _import_structure["controlnet_xs"] = ["ControlNetXSAdapter", "UNetControlNetXSModel"]
36
- _import_structure["dual_transformer_2d"] = ["DualTransformer2DModel"]
37
- _import_structure["embeddings"] = ["ImageProjection"]
38
- _import_structure["modeling_utils"] = ["ModelMixin"]
39
- _import_structure["transformers.prior_transformer"] = ["PriorTransformer"]
40
- _import_structure["transformers.t5_film_transformer"] = ["T5FilmDecoder"]
41
- _import_structure["transformers.transformer_2d"] = ["Transformer2DModel"]
42
- _import_structure["transformers.transformer_temporal"] = ["TransformerTemporalModel"]
43
- _import_structure["unets.unet_1d"] = ["UNet1DModel"]
44
- _import_structure["unets.unet_2d"] = ["UNet2DModel"]
45
- _import_structure["unets.unet_2d_condition"] = ["UNet2DConditionModel"]
46
- _import_structure["unets.unet_3d_condition"] = ["UNet3DConditionModel"]
47
- _import_structure["unets.unet_i2vgen_xl"] = ["I2VGenXLUNet"]
48
- _import_structure["unets.unet_kandinsky3"] = ["Kandinsky3UNet"]
49
- _import_structure["unets.unet_motion_model"] = ["MotionAdapter", "UNetMotionModel"]
50
- _import_structure["unets.unet_spatio_temporal_condition"] = ["UNetSpatioTemporalConditionModel"]
51
- _import_structure["unets.unet_stable_cascade"] = ["StableCascadeUNet"]
52
- _import_structure["unets.uvit_2d"] = ["UVit2DModel"]
53
- _import_structure["vq_model"] = ["VQModel"]
54
-
55
- if is_flax_available():
56
- _import_structure["controlnet_flax"] = ["FlaxControlNetModel"]
57
- _import_structure["unets.unet_2d_condition_flax"] = ["FlaxUNet2DConditionModel"]
58
- _import_structure["vae_flax"] = ["FlaxAutoencoderKL"]
59
-
60
-
61
- if TYPE_CHECKING or DIFFUSERS_SLOW_IMPORT:
62
- if is_torch_available():
63
- from .adapter import MultiAdapter, T2IAdapter
64
- from .autoencoders import (
65
- AsymmetricAutoencoderKL,
66
- AutoencoderKL,
67
- AutoencoderKLTemporalDecoder,
68
- AutoencoderTiny,
69
- ConsistencyDecoderVAE,
70
- )
71
- from .controlnet import ControlNetModel
72
- from .controlnet_xs import ControlNetXSAdapter, UNetControlNetXSModel
73
- from .embeddings import ImageProjection
74
- from .modeling_utils import ModelMixin
75
- from .transformers import (
76
- DualTransformer2DModel,
77
- PriorTransformer,
78
- T5FilmDecoder,
79
- Transformer2DModel,
80
- TransformerTemporalModel,
81
- )
82
- from .unets import (
83
- I2VGenXLUNet,
84
- Kandinsky3UNet,
85
- MotionAdapter,
86
- StableCascadeUNet,
87
- UNet1DModel,
88
- UNet2DConditionModel,
89
- UNet2DModel,
90
- UNet3DConditionModel,
91
- UNetMotionModel,
92
- UNetSpatioTemporalConditionModel,
93
- UVit2DModel,
94
- )
95
- from .vq_model import VQModel
96
-
97
- if is_flax_available():
98
- from .controlnet_flax import FlaxControlNetModel
99
- from .unets import FlaxUNet2DConditionModel
100
- from .vae_flax import FlaxAutoencoderKL
101
-
102
- else:
103
- import sys
104
-
105
- sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/activations.py DELETED
@@ -1,131 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 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 deprecate
21
- from ..utils.import_utils import is_torch_npu_available
22
-
23
-
24
- if is_torch_npu_available():
25
- import torch_npu
26
-
27
- ACTIVATION_FUNCTIONS = {
28
- "swish": nn.SiLU(),
29
- "silu": nn.SiLU(),
30
- "mish": nn.Mish(),
31
- "gelu": nn.GELU(),
32
- "relu": nn.ReLU(),
33
- }
34
-
35
-
36
- def get_activation(act_fn: str) -> nn.Module:
37
- """Helper function to get activation function from string.
38
-
39
- Args:
40
- act_fn (str): Name of activation function.
41
-
42
- Returns:
43
- nn.Module: Activation function.
44
- """
45
-
46
- act_fn = act_fn.lower()
47
- if act_fn in ACTIVATION_FUNCTIONS:
48
- return ACTIVATION_FUNCTIONS[act_fn]
49
- else:
50
- raise ValueError(f"Unsupported activation function: {act_fn}")
51
-
52
-
53
- class GELU(nn.Module):
54
- r"""
55
- GELU activation function with tanh approximation support with `approximate="tanh"`.
56
-
57
- Parameters:
58
- dim_in (`int`): The number of channels in the input.
59
- dim_out (`int`): The number of channels in the output.
60
- approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
61
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
62
- """
63
-
64
- def __init__(self, dim_in: int, dim_out: int, approximate: str = "none", bias: bool = True):
65
- super().__init__()
66
- self.proj = nn.Linear(dim_in, dim_out, bias=bias)
67
- self.approximate = approximate
68
-
69
- def gelu(self, gate: torch.Tensor) -> torch.Tensor:
70
- if gate.device.type != "mps":
71
- return F.gelu(gate, approximate=self.approximate)
72
- # mps: gelu is not implemented for float16
73
- return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
74
-
75
- def forward(self, hidden_states):
76
- hidden_states = self.proj(hidden_states)
77
- hidden_states = self.gelu(hidden_states)
78
- return hidden_states
79
-
80
-
81
- class GEGLU(nn.Module):
82
- r"""
83
- A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
84
-
85
- Parameters:
86
- dim_in (`int`): The number of channels in the input.
87
- dim_out (`int`): The number of channels in the output.
88
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
89
- """
90
-
91
- def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
92
- super().__init__()
93
- self.proj = nn.Linear(dim_in, dim_out * 2, bias=bias)
94
-
95
- def gelu(self, gate: torch.Tensor) -> torch.Tensor:
96
- if gate.device.type != "mps":
97
- return F.gelu(gate)
98
- # mps: gelu is not implemented for float16
99
- return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
100
-
101
- def forward(self, hidden_states, *args, **kwargs):
102
- if len(args) > 0 or kwargs.get("scale", None) is not None:
103
- deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
104
- deprecate("scale", "1.0.0", deprecation_message)
105
- hidden_states = self.proj(hidden_states)
106
- if is_torch_npu_available():
107
- # using torch_npu.npu_geglu can run faster and save memory on NPU.
108
- return torch_npu.npu_geglu(hidden_states, dim=-1, approximate=1)[0]
109
- else:
110
- hidden_states, gate = hidden_states.chunk(2, dim=-1)
111
- return hidden_states * self.gelu(gate)
112
-
113
-
114
- class ApproximateGELU(nn.Module):
115
- r"""
116
- The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
117
- [paper](https://arxiv.org/abs/1606.08415).
118
-
119
- Parameters:
120
- dim_in (`int`): The number of channels in the input.
121
- dim_out (`int`): The number of channels in the output.
122
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
123
- """
124
-
125
- def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
126
- super().__init__()
127
- self.proj = nn.Linear(dim_in, dim_out, bias=bias)
128
-
129
- def forward(self, x: torch.Tensor) -> torch.Tensor:
130
- x = self.proj(x)
131
- return x * torch.sigmoid(1.702 * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/adapter.py DELETED
@@ -1,584 +0,0 @@
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 DELETED
@@ -1,678 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Any, Dict, Optional
15
-
16
- import torch
17
- import torch.nn.functional as F
18
- from torch import nn
19
-
20
- from ..utils import deprecate, logging
21
- from ..utils.torch_utils import maybe_allow_in_graph
22
- from .activations import GEGLU, GELU, ApproximateGELU
23
- from .attention_processor import Attention
24
- from .embeddings import SinusoidalPositionalEmbedding
25
- from .normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
26
-
27
-
28
- logger = logging.get_logger(__name__)
29
-
30
-
31
- def _chunked_feed_forward(ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int):
32
- # "feed_forward_chunk_size" can be used to save memory
33
- if hidden_states.shape[chunk_dim] % chunk_size != 0:
34
- raise ValueError(
35
- 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`."
36
- )
37
-
38
- num_chunks = hidden_states.shape[chunk_dim] // chunk_size
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
- return ff_output
44
-
45
-
46
- @maybe_allow_in_graph
47
- class GatedSelfAttentionDense(nn.Module):
48
- r"""
49
- A gated self-attention dense layer that combines visual features and object features.
50
-
51
- Parameters:
52
- query_dim (`int`): The number of channels in the query.
53
- context_dim (`int`): The number of channels in the context.
54
- n_heads (`int`): The number of heads to use for attention.
55
- d_head (`int`): The number of channels in each head.
56
- """
57
-
58
- def __init__(self, query_dim: int, context_dim: int, n_heads: int, d_head: int):
59
- super().__init__()
60
-
61
- # we need a linear projection since we need cat visual feature and obj feature
62
- self.linear = nn.Linear(context_dim, query_dim)
63
-
64
- self.attn = Attention(query_dim=query_dim, heads=n_heads, dim_head=d_head)
65
- self.ff = FeedForward(query_dim, activation_fn="geglu")
66
-
67
- self.norm1 = nn.LayerNorm(query_dim)
68
- self.norm2 = nn.LayerNorm(query_dim)
69
-
70
- self.register_parameter("alpha_attn", nn.Parameter(torch.tensor(0.0)))
71
- self.register_parameter("alpha_dense", nn.Parameter(torch.tensor(0.0)))
72
-
73
- self.enabled = True
74
-
75
- def forward(self, x: torch.Tensor, objs: torch.Tensor) -> torch.Tensor:
76
- if not self.enabled:
77
- return x
78
-
79
- n_visual = x.shape[1]
80
- objs = self.linear(objs)
81
-
82
- x = x + self.alpha_attn.tanh() * self.attn(self.norm1(torch.cat([x, objs], dim=1)))[:, :n_visual, :]
83
- x = x + self.alpha_dense.tanh() * self.ff(self.norm2(x))
84
-
85
- return x
86
-
87
-
88
- @maybe_allow_in_graph
89
- class BasicTransformerBlock(nn.Module):
90
- r"""
91
- A basic Transformer block.
92
-
93
- Parameters:
94
- dim (`int`): The number of channels in the input and output.
95
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
96
- attention_head_dim (`int`): The number of channels in each head.
97
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
98
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
99
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
100
- num_embeds_ada_norm (:
101
- obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
102
- attention_bias (:
103
- obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
104
- only_cross_attention (`bool`, *optional*):
105
- Whether to use only cross-attention layers. In this case two cross attention layers are used.
106
- double_self_attention (`bool`, *optional*):
107
- Whether to use two self-attention layers. In this case no cross attention layers are used.
108
- upcast_attention (`bool`, *optional*):
109
- Whether to upcast the attention computation to float32. This is useful for mixed precision training.
110
- norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
111
- Whether to use learnable elementwise affine parameters for normalization.
112
- norm_type (`str`, *optional*, defaults to `"layer_norm"`):
113
- The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
114
- final_dropout (`bool` *optional*, defaults to False):
115
- Whether to apply a final dropout after the last feed-forward layer.
116
- attention_type (`str`, *optional*, defaults to `"default"`):
117
- The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
118
- positional_embeddings (`str`, *optional*, defaults to `None`):
119
- The type of positional embeddings to apply to.
120
- num_positional_embeddings (`int`, *optional*, defaults to `None`):
121
- The maximum number of positional embeddings to apply.
122
- """
123
-
124
- def __init__(
125
- self,
126
- dim: int,
127
- num_attention_heads: int,
128
- attention_head_dim: int,
129
- dropout=0.0,
130
- cross_attention_dim: Optional[int] = None,
131
- activation_fn: str = "geglu",
132
- num_embeds_ada_norm: Optional[int] = None,
133
- attention_bias: bool = False,
134
- only_cross_attention: bool = False,
135
- double_self_attention: bool = False,
136
- upcast_attention: bool = False,
137
- norm_elementwise_affine: bool = True,
138
- norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
139
- norm_eps: float = 1e-5,
140
- final_dropout: bool = False,
141
- attention_type: str = "default",
142
- positional_embeddings: Optional[str] = None,
143
- num_positional_embeddings: Optional[int] = None,
144
- ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
145
- ada_norm_bias: Optional[int] = None,
146
- ff_inner_dim: Optional[int] = None,
147
- ff_bias: bool = True,
148
- attention_out_bias: bool = True,
149
- ):
150
- super().__init__()
151
- self.only_cross_attention = only_cross_attention
152
-
153
- # We keep these boolean flags for backward-compatibility.
154
- self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
155
- self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
156
- self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
157
- self.use_layer_norm = norm_type == "layer_norm"
158
- self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
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
- self.norm_type = norm_type
167
- self.num_embeds_ada_norm = num_embeds_ada_norm
168
-
169
- if positional_embeddings and (num_positional_embeddings is None):
170
- raise ValueError(
171
- "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
172
- )
173
-
174
- if positional_embeddings == "sinusoidal":
175
- self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
176
- else:
177
- self.pos_embed = None
178
-
179
- # Define 3 blocks. Each block has its own normalization layer.
180
- # 1. Self-Attn
181
- if norm_type == "ada_norm":
182
- self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
183
- elif norm_type == "ada_norm_zero":
184
- self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
185
- elif norm_type == "ada_norm_continuous":
186
- self.norm1 = AdaLayerNormContinuous(
187
- dim,
188
- ada_norm_continous_conditioning_embedding_dim,
189
- norm_elementwise_affine,
190
- norm_eps,
191
- ada_norm_bias,
192
- "rms_norm",
193
- )
194
- else:
195
- self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
196
-
197
- self.attn1 = Attention(
198
- query_dim=dim,
199
- heads=num_attention_heads,
200
- dim_head=attention_head_dim,
201
- dropout=dropout,
202
- bias=attention_bias,
203
- cross_attention_dim=cross_attention_dim if only_cross_attention else None,
204
- upcast_attention=upcast_attention,
205
- out_bias=attention_out_bias,
206
- )
207
-
208
- # 2. Cross-Attn
209
- if cross_attention_dim is not None or double_self_attention:
210
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
211
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
212
- # the second cross attention block.
213
- if norm_type == "ada_norm":
214
- self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
215
- elif norm_type == "ada_norm_continuous":
216
- self.norm2 = AdaLayerNormContinuous(
217
- dim,
218
- ada_norm_continous_conditioning_embedding_dim,
219
- norm_elementwise_affine,
220
- norm_eps,
221
- ada_norm_bias,
222
- "rms_norm",
223
- )
224
- else:
225
- self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
226
-
227
- self.attn2 = Attention(
228
- query_dim=dim,
229
- cross_attention_dim=cross_attention_dim if not double_self_attention else None,
230
- heads=num_attention_heads,
231
- dim_head=attention_head_dim,
232
- dropout=dropout,
233
- bias=attention_bias,
234
- upcast_attention=upcast_attention,
235
- out_bias=attention_out_bias,
236
- ) # is self-attn if encoder_hidden_states is none
237
- else:
238
- self.norm2 = None
239
- self.attn2 = None
240
-
241
- # 3. Feed-forward
242
- if norm_type == "ada_norm_continuous":
243
- self.norm3 = AdaLayerNormContinuous(
244
- dim,
245
- ada_norm_continous_conditioning_embedding_dim,
246
- norm_elementwise_affine,
247
- norm_eps,
248
- ada_norm_bias,
249
- "layer_norm",
250
- )
251
-
252
- elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
253
- self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
254
- elif norm_type == "layer_norm_i2vgen":
255
- self.norm3 = None
256
-
257
- self.ff = FeedForward(
258
- dim,
259
- dropout=dropout,
260
- activation_fn=activation_fn,
261
- final_dropout=final_dropout,
262
- inner_dim=ff_inner_dim,
263
- bias=ff_bias,
264
- )
265
-
266
- # 4. Fuser
267
- if attention_type == "gated" or attention_type == "gated-text-image":
268
- self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
269
-
270
- # 5. Scale-shift for PixArt-Alpha.
271
- if norm_type == "ada_norm_single":
272
- self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
273
-
274
- # let chunk size default to None
275
- self._chunk_size = None
276
- self._chunk_dim = 0
277
-
278
- def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
279
- # Sets chunk feed-forward
280
- self._chunk_size = chunk_size
281
- self._chunk_dim = dim
282
-
283
- def forward(
284
- self,
285
- hidden_states: torch.FloatTensor,
286
- attention_mask: Optional[torch.FloatTensor] = None,
287
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
288
- encoder_attention_mask: Optional[torch.FloatTensor] = None,
289
- timestep: Optional[torch.LongTensor] = None,
290
- cross_attention_kwargs: Dict[str, Any] = None,
291
- class_labels: Optional[torch.LongTensor] = None,
292
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
293
- ) -> torch.FloatTensor:
294
- if cross_attention_kwargs is not None:
295
- if cross_attention_kwargs.get("scale", None) is not None:
296
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
297
-
298
- # Notice that normalization is always applied before the real computation in the following blocks.
299
- # 0. Self-Attention
300
- batch_size = hidden_states.shape[0]
301
-
302
- if self.norm_type == "ada_norm":
303
- norm_hidden_states = self.norm1(hidden_states, timestep)
304
- elif self.norm_type == "ada_norm_zero":
305
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
306
- hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
307
- )
308
- elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
309
- norm_hidden_states = self.norm1(hidden_states)
310
- elif self.norm_type == "ada_norm_continuous":
311
- norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
312
- elif self.norm_type == "ada_norm_single":
313
- shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
314
- self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
315
- ).chunk(6, dim=1)
316
- norm_hidden_states = self.norm1(hidden_states)
317
- norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
318
- norm_hidden_states = norm_hidden_states.squeeze(1)
319
- else:
320
- raise ValueError("Incorrect norm used")
321
-
322
- if self.pos_embed is not None:
323
- norm_hidden_states = self.pos_embed(norm_hidden_states)
324
-
325
- # 1. Prepare GLIGEN inputs
326
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
327
- gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
328
-
329
- if "extracted_kv" in cross_attention_kwargs:
330
- filtered_cross_attention_kwargs = {k: v for k, v in cross_attention_kwargs.items() if k != "extracted_kv"}
331
- filtered_cross_attention_kwargs["external_kv"] = cross_attention_kwargs["extracted_kv"][self.full_name].self_attention
332
- else:
333
- filtered_cross_attention_kwargs = cross_attention_kwargs
334
-
335
- attn_output = self.attn1(
336
- norm_hidden_states,
337
- encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
338
- attention_mask=attention_mask,
339
- temb=timestep,
340
- **filtered_cross_attention_kwargs,
341
- )
342
- if self.norm_type == "ada_norm_zero":
343
- attn_output = gate_msa.unsqueeze(1) * attn_output
344
- elif self.norm_type == "ada_norm_single":
345
- attn_output = gate_msa * attn_output
346
-
347
- hidden_states = attn_output + hidden_states
348
- if hidden_states.ndim == 4:
349
- hidden_states = hidden_states.squeeze(1)
350
-
351
- # 1.2 GLIGEN Control
352
- if gligen_kwargs is not None:
353
- hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
354
-
355
- # 3. Cross-Attention
356
- if self.attn2 is not None:
357
- if self.norm_type == "ada_norm":
358
- norm_hidden_states = self.norm2(hidden_states, timestep)
359
- elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
360
- norm_hidden_states = self.norm2(hidden_states)
361
- elif self.norm_type == "ada_norm_single":
362
- # For PixArt norm2 isn't applied here:
363
- # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
364
- norm_hidden_states = hidden_states
365
- elif self.norm_type == "ada_norm_continuous":
366
- norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
367
- else:
368
- raise ValueError("Incorrect norm")
369
-
370
- if self.pos_embed is not None and self.norm_type != "ada_norm_single":
371
- norm_hidden_states = self.pos_embed(norm_hidden_states)
372
-
373
- if "extracted_kv" in cross_attention_kwargs:
374
- filtered_cross_attention_kwargs = {k: v for k, v in cross_attention_kwargs.items() if k != "extracted_kv"}
375
- filtered_cross_attention_kwargs["external_kv"] = cross_attention_kwargs["extracted_kv"][self.full_name].cross_attention
376
- else:
377
- filtered_cross_attention_kwargs = cross_attention_kwargs
378
-
379
- attn_output = self.attn2(
380
- norm_hidden_states,
381
- encoder_hidden_states=encoder_hidden_states,
382
- attention_mask=encoder_attention_mask,
383
- temb=timestep,
384
- **filtered_cross_attention_kwargs,
385
- )
386
- hidden_states = attn_output + hidden_states
387
-
388
- # 4. Feed-forward
389
- # i2vgen doesn't have this norm 🤷‍♂️
390
- if self.norm_type == "ada_norm_continuous":
391
- norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
392
- elif not self.norm_type == "ada_norm_single":
393
- norm_hidden_states = self.norm3(hidden_states)
394
-
395
- if self.norm_type == "ada_norm_zero":
396
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
397
-
398
- if self.norm_type == "ada_norm_single":
399
- norm_hidden_states = self.norm2(hidden_states)
400
- norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
401
-
402
- if self._chunk_size is not None:
403
- # "feed_forward_chunk_size" can be used to save memory
404
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
405
- else:
406
- ff_output = self.ff(norm_hidden_states)
407
-
408
- if self.norm_type == "ada_norm_zero":
409
- ff_output = gate_mlp.unsqueeze(1) * ff_output
410
- elif self.norm_type == "ada_norm_single":
411
- ff_output = gate_mlp * ff_output
412
-
413
- hidden_states = ff_output + hidden_states
414
- if hidden_states.ndim == 4:
415
- hidden_states = hidden_states.squeeze(1)
416
-
417
- return hidden_states
418
-
419
-
420
- @maybe_allow_in_graph
421
- class TemporalBasicTransformerBlock(nn.Module):
422
- r"""
423
- A basic Transformer block for video like data.
424
-
425
- Parameters:
426
- dim (`int`): The number of channels in the input and output.
427
- time_mix_inner_dim (`int`): The number of channels for temporal attention.
428
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
429
- attention_head_dim (`int`): The number of channels in each head.
430
- cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
431
- """
432
-
433
- def __init__(
434
- self,
435
- dim: int,
436
- time_mix_inner_dim: int,
437
- num_attention_heads: int,
438
- attention_head_dim: int,
439
- cross_attention_dim: Optional[int] = None,
440
- ):
441
- super().__init__()
442
- self.is_res = dim == time_mix_inner_dim
443
-
444
- self.norm_in = nn.LayerNorm(dim)
445
-
446
- # Define 3 blocks. Each block has its own normalization layer.
447
- # 1. Self-Attn
448
- self.ff_in = FeedForward(
449
- dim,
450
- dim_out=time_mix_inner_dim,
451
- activation_fn="geglu",
452
- )
453
-
454
- self.norm1 = nn.LayerNorm(time_mix_inner_dim)
455
- self.attn1 = Attention(
456
- query_dim=time_mix_inner_dim,
457
- heads=num_attention_heads,
458
- dim_head=attention_head_dim,
459
- cross_attention_dim=None,
460
- )
461
-
462
- # 2. Cross-Attn
463
- if cross_attention_dim is not None:
464
- # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
465
- # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
466
- # the second cross attention block.
467
- self.norm2 = nn.LayerNorm(time_mix_inner_dim)
468
- self.attn2 = Attention(
469
- query_dim=time_mix_inner_dim,
470
- cross_attention_dim=cross_attention_dim,
471
- heads=num_attention_heads,
472
- dim_head=attention_head_dim,
473
- ) # is self-attn if encoder_hidden_states is none
474
- else:
475
- self.norm2 = None
476
- self.attn2 = None
477
-
478
- # 3. Feed-forward
479
- self.norm3 = nn.LayerNorm(time_mix_inner_dim)
480
- self.ff = FeedForward(time_mix_inner_dim, activation_fn="geglu")
481
-
482
- # let chunk size default to None
483
- self._chunk_size = None
484
- self._chunk_dim = None
485
-
486
- def set_chunk_feed_forward(self, chunk_size: Optional[int], **kwargs):
487
- # Sets chunk feed-forward
488
- self._chunk_size = chunk_size
489
- # chunk dim should be hardcoded to 1 to have better speed vs. memory trade-off
490
- self._chunk_dim = 1
491
-
492
- def forward(
493
- self,
494
- hidden_states: torch.FloatTensor,
495
- num_frames: int,
496
- encoder_hidden_states: Optional[torch.FloatTensor] = None,
497
- ) -> torch.FloatTensor:
498
- # Notice that normalization is always applied before the real computation in the following blocks.
499
- # 0. Self-Attention
500
- batch_size = hidden_states.shape[0]
501
-
502
- batch_frames, seq_length, channels = hidden_states.shape
503
- batch_size = batch_frames // num_frames
504
-
505
- hidden_states = hidden_states[None, :].reshape(batch_size, num_frames, seq_length, channels)
506
- hidden_states = hidden_states.permute(0, 2, 1, 3)
507
- hidden_states = hidden_states.reshape(batch_size * seq_length, num_frames, channels)
508
-
509
- residual = hidden_states
510
- hidden_states = self.norm_in(hidden_states)
511
-
512
- if self._chunk_size is not None:
513
- hidden_states = _chunked_feed_forward(self.ff_in, hidden_states, self._chunk_dim, self._chunk_size)
514
- else:
515
- hidden_states = self.ff_in(hidden_states)
516
-
517
- if self.is_res:
518
- hidden_states = hidden_states + residual
519
-
520
- norm_hidden_states = self.norm1(hidden_states)
521
- attn_output = self.attn1(norm_hidden_states, encoder_hidden_states=None)
522
- hidden_states = attn_output + hidden_states
523
-
524
- # 3. Cross-Attention
525
- if self.attn2 is not None:
526
- norm_hidden_states = self.norm2(hidden_states)
527
- attn_output = self.attn2(norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
528
- hidden_states = attn_output + hidden_states
529
-
530
- # 4. Feed-forward
531
- norm_hidden_states = self.norm3(hidden_states)
532
-
533
- if self._chunk_size is not None:
534
- ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
535
- else:
536
- ff_output = self.ff(norm_hidden_states)
537
-
538
- if self.is_res:
539
- hidden_states = ff_output + hidden_states
540
- else:
541
- hidden_states = ff_output
542
-
543
- hidden_states = hidden_states[None, :].reshape(batch_size, seq_length, num_frames, channels)
544
- hidden_states = hidden_states.permute(0, 2, 1, 3)
545
- hidden_states = hidden_states.reshape(batch_size * num_frames, seq_length, channels)
546
-
547
- return hidden_states
548
-
549
-
550
- class SkipFFTransformerBlock(nn.Module):
551
- def __init__(
552
- self,
553
- dim: int,
554
- num_attention_heads: int,
555
- attention_head_dim: int,
556
- kv_input_dim: int,
557
- kv_input_dim_proj_use_bias: bool,
558
- dropout=0.0,
559
- cross_attention_dim: Optional[int] = None,
560
- attention_bias: bool = False,
561
- attention_out_bias: bool = True,
562
- ):
563
- super().__init__()
564
- if kv_input_dim != dim:
565
- self.kv_mapper = nn.Linear(kv_input_dim, dim, kv_input_dim_proj_use_bias)
566
- else:
567
- self.kv_mapper = None
568
-
569
- self.norm1 = RMSNorm(dim, 1e-06)
570
-
571
- self.attn1 = Attention(
572
- query_dim=dim,
573
- heads=num_attention_heads,
574
- dim_head=attention_head_dim,
575
- dropout=dropout,
576
- bias=attention_bias,
577
- cross_attention_dim=cross_attention_dim,
578
- out_bias=attention_out_bias,
579
- )
580
-
581
- self.norm2 = RMSNorm(dim, 1e-06)
582
-
583
- self.attn2 = Attention(
584
- query_dim=dim,
585
- cross_attention_dim=cross_attention_dim,
586
- heads=num_attention_heads,
587
- dim_head=attention_head_dim,
588
- dropout=dropout,
589
- bias=attention_bias,
590
- out_bias=attention_out_bias,
591
- )
592
-
593
- def forward(self, hidden_states, encoder_hidden_states, cross_attention_kwargs):
594
- cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
595
-
596
- if self.kv_mapper is not None:
597
- encoder_hidden_states = self.kv_mapper(F.silu(encoder_hidden_states))
598
-
599
- norm_hidden_states = self.norm1(hidden_states)
600
-
601
- attn_output = self.attn1(
602
- norm_hidden_states,
603
- encoder_hidden_states=encoder_hidden_states,
604
- **cross_attention_kwargs,
605
- )
606
-
607
- hidden_states = attn_output + hidden_states
608
-
609
- norm_hidden_states = self.norm2(hidden_states)
610
-
611
- attn_output = self.attn2(
612
- norm_hidden_states,
613
- encoder_hidden_states=encoder_hidden_states,
614
- **cross_attention_kwargs,
615
- )
616
-
617
- hidden_states = attn_output + hidden_states
618
-
619
- return hidden_states
620
-
621
-
622
- class FeedForward(nn.Module):
623
- r"""
624
- A feed-forward layer.
625
-
626
- Parameters:
627
- dim (`int`): The number of channels in the input.
628
- dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
629
- mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
630
- dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
631
- activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
632
- final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
633
- bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
634
- """
635
-
636
- def __init__(
637
- self,
638
- dim: int,
639
- dim_out: Optional[int] = None,
640
- mult: int = 4,
641
- dropout: float = 0.0,
642
- activation_fn: str = "geglu",
643
- final_dropout: bool = False,
644
- inner_dim=None,
645
- bias: bool = True,
646
- ):
647
- super().__init__()
648
- if inner_dim is None:
649
- inner_dim = int(dim * mult)
650
- dim_out = dim_out if dim_out is not None else dim
651
-
652
- if activation_fn == "gelu":
653
- act_fn = GELU(dim, inner_dim, bias=bias)
654
- if activation_fn == "gelu-approximate":
655
- act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
656
- elif activation_fn == "geglu":
657
- act_fn = GEGLU(dim, inner_dim, bias=bias)
658
- elif activation_fn == "geglu-approximate":
659
- act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
660
-
661
- self.net = nn.ModuleList([])
662
- # project in
663
- self.net.append(act_fn)
664
- # project dropout
665
- self.net.append(nn.Dropout(dropout))
666
- # project out
667
- self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
668
- # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
669
- if final_dropout:
670
- self.net.append(nn.Dropout(dropout))
671
-
672
- def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
673
- if len(args) > 0 or kwargs.get("scale", None) is not None:
674
- deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
675
- deprecate("scale", "1.0.0", deprecation_message)
676
- for module in self.net:
677
- hidden_states = module(hidden_states)
678
- return hidden_states
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/attention_flax.py DELETED
@@ -1,494 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- import 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 DELETED
The diff for this file is too large to render. See raw diff
 
diffusers/models/autoencoders/__init__.py DELETED
@@ -1,5 +0,0 @@
1
- from .autoencoder_asym_kl import AsymmetricAutoencoderKL
2
- from .autoencoder_kl import AutoencoderKL
3
- from .autoencoder_kl_temporal_decoder import AutoencoderKLTemporalDecoder
4
- from .autoencoder_tiny import AutoencoderTiny
5
- from .consistency_decoder_vae import ConsistencyDecoderVAE
 
 
 
 
 
 
diffusers/models/autoencoders/autoencoder_asym_kl.py DELETED
@@ -1,186 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import 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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/autoencoders/autoencoder_kl.py DELETED
@@ -1,490 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Dict, 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.accelerate_utils import apply_forward_hook
22
- from ..attention_processor import (
23
- ADDED_KV_ATTENTION_PROCESSORS,
24
- CROSS_ATTENTION_PROCESSORS,
25
- Attention,
26
- AttentionProcessor,
27
- AttnAddedKVProcessor,
28
- AttnProcessor,
29
- )
30
- from ..modeling_outputs import AutoencoderKLOutput
31
- from ..modeling_utils import ModelMixin
32
- from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder
33
-
34
-
35
- class AutoencoderKL(ModelMixin, ConfigMixin, FromOriginalVAEMixin):
36
- r"""
37
- A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
38
-
39
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
40
- for all models (such as downloading or saving).
41
-
42
- Parameters:
43
- in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
44
- out_channels (int, *optional*, defaults to 3): Number of channels in the output.
45
- down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
46
- Tuple of downsample block types.
47
- up_block_types (`Tuple[str]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
48
- Tuple of upsample block types.
49
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
50
- Tuple of block output channels.
51
- act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
52
- latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
53
- sample_size (`int`, *optional*, defaults to `32`): Sample input size.
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
- force_upcast (`bool`, *optional*, default to `True`):
62
- If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
63
- can be fine-tuned / trained to a lower range without loosing too much precision in which case
64
- `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
65
- """
66
-
67
- _supports_gradient_checkpointing = True
68
- _no_split_modules = ["BasicTransformerBlock", "ResnetBlock2D"]
69
-
70
- @register_to_config
71
- def __init__(
72
- self,
73
- in_channels: int = 3,
74
- out_channels: int = 3,
75
- down_block_types: Tuple[str] = ("DownEncoderBlock2D",),
76
- up_block_types: Tuple[str] = ("UpDecoderBlock2D",),
77
- block_out_channels: Tuple[int] = (64,),
78
- layers_per_block: int = 1,
79
- act_fn: str = "silu",
80
- latent_channels: int = 4,
81
- norm_num_groups: int = 32,
82
- sample_size: int = 32,
83
- scaling_factor: float = 0.18215,
84
- latents_mean: Optional[Tuple[float]] = None,
85
- latents_std: Optional[Tuple[float]] = None,
86
- force_upcast: float = True,
87
- ):
88
- super().__init__()
89
-
90
- # pass init params to Encoder
91
- self.encoder = Encoder(
92
- in_channels=in_channels,
93
- out_channels=latent_channels,
94
- down_block_types=down_block_types,
95
- block_out_channels=block_out_channels,
96
- layers_per_block=layers_per_block,
97
- act_fn=act_fn,
98
- norm_num_groups=norm_num_groups,
99
- double_z=True,
100
- )
101
-
102
- # pass init params to Decoder
103
- self.decoder = Decoder(
104
- in_channels=latent_channels,
105
- out_channels=out_channels,
106
- up_block_types=up_block_types,
107
- block_out_channels=block_out_channels,
108
- layers_per_block=layers_per_block,
109
- norm_num_groups=norm_num_groups,
110
- act_fn=act_fn,
111
- )
112
-
113
- self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
114
- self.post_quant_conv = nn.Conv2d(latent_channels, latent_channels, 1)
115
-
116
- self.use_slicing = False
117
- self.use_tiling = False
118
-
119
- # only relevant if vae tiling is enabled
120
- self.tile_sample_min_size = self.config.sample_size
121
- sample_size = (
122
- self.config.sample_size[0]
123
- if isinstance(self.config.sample_size, (list, tuple))
124
- else self.config.sample_size
125
- )
126
- self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
127
- self.tile_overlap_factor = 0.25
128
-
129
- def _set_gradient_checkpointing(self, module, value=False):
130
- if isinstance(module, (Encoder, Decoder)):
131
- module.gradient_checkpointing = value
132
-
133
- def enable_tiling(self, use_tiling: bool = True):
134
- r"""
135
- Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
136
- compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
137
- processing larger images.
138
- """
139
- self.use_tiling = use_tiling
140
-
141
- def disable_tiling(self):
142
- r"""
143
- Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
144
- decoding in one step.
145
- """
146
- self.enable_tiling(False)
147
-
148
- def enable_slicing(self):
149
- r"""
150
- Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
151
- compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
152
- """
153
- self.use_slicing = True
154
-
155
- def disable_slicing(self):
156
- r"""
157
- Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
158
- decoding in one step.
159
- """
160
- self.use_slicing = False
161
-
162
- @property
163
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
164
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
165
- r"""
166
- Returns:
167
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
168
- indexed by its weight name.
169
- """
170
- # set recursively
171
- processors = {}
172
-
173
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
174
- if hasattr(module, "get_processor"):
175
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
176
-
177
- for sub_name, child in module.named_children():
178
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
179
-
180
- return processors
181
-
182
- for name, module in self.named_children():
183
- fn_recursive_add_processors(name, module, processors)
184
-
185
- return processors
186
-
187
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
188
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
189
- r"""
190
- Sets the attention processor to use to compute attention.
191
-
192
- Parameters:
193
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
194
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
195
- for **all** `Attention` layers.
196
-
197
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
198
- processor. This is strongly recommended when setting trainable attention processors.
199
-
200
- """
201
- count = len(self.attn_processors.keys())
202
-
203
- if isinstance(processor, dict) and len(processor) != count:
204
- raise ValueError(
205
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
206
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
207
- )
208
-
209
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
210
- if hasattr(module, "set_processor"):
211
- if not isinstance(processor, dict):
212
- module.set_processor(processor)
213
- else:
214
- module.set_processor(processor.pop(f"{name}.processor"))
215
-
216
- for sub_name, child in module.named_children():
217
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
218
-
219
- for name, module in self.named_children():
220
- fn_recursive_attn_processor(name, module, processor)
221
-
222
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
223
- def set_default_attn_processor(self):
224
- """
225
- Disables custom attention processors and sets the default attention implementation.
226
- """
227
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
228
- processor = AttnAddedKVProcessor()
229
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
230
- processor = AttnProcessor()
231
- else:
232
- raise ValueError(
233
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
234
- )
235
-
236
- self.set_attn_processor(processor)
237
-
238
- @apply_forward_hook
239
- def encode(
240
- self, x: torch.FloatTensor, return_dict: bool = True
241
- ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
242
- """
243
- Encode a batch of images into latents.
244
-
245
- Args:
246
- x (`torch.FloatTensor`): Input batch of images.
247
- return_dict (`bool`, *optional*, defaults to `True`):
248
- Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
249
-
250
- Returns:
251
- The latent representations of the encoded images. If `return_dict` is True, a
252
- [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
253
- """
254
- if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
255
- return self.tiled_encode(x, return_dict=return_dict)
256
-
257
- if self.use_slicing and x.shape[0] > 1:
258
- encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
259
- h = torch.cat(encoded_slices)
260
- else:
261
- h = self.encoder(x)
262
-
263
- moments = self.quant_conv(h)
264
- posterior = DiagonalGaussianDistribution(moments)
265
-
266
- if not return_dict:
267
- return (posterior,)
268
-
269
- return AutoencoderKLOutput(latent_dist=posterior)
270
-
271
- def _decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
272
- if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
273
- return self.tiled_decode(z, return_dict=return_dict)
274
-
275
- z = self.post_quant_conv(z)
276
- dec = self.decoder(z)
277
-
278
- if not return_dict:
279
- return (dec,)
280
-
281
- return DecoderOutput(sample=dec)
282
-
283
- @apply_forward_hook
284
- def decode(
285
- self, z: torch.FloatTensor, return_dict: bool = True, generator=None
286
- ) -> Union[DecoderOutput, torch.FloatTensor]:
287
- """
288
- Decode a batch of images.
289
-
290
- Args:
291
- z (`torch.FloatTensor`): Input batch of latent vectors.
292
- return_dict (`bool`, *optional*, defaults to `True`):
293
- Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
294
-
295
- Returns:
296
- [`~models.vae.DecoderOutput`] or `tuple`:
297
- If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
298
- returned.
299
-
300
- """
301
- if self.use_slicing and z.shape[0] > 1:
302
- decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]
303
- decoded = torch.cat(decoded_slices)
304
- else:
305
- decoded = self._decode(z).sample
306
-
307
- if not return_dict:
308
- return (decoded,)
309
-
310
- return DecoderOutput(sample=decoded)
311
-
312
- def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
313
- blend_extent = min(a.shape[2], b.shape[2], blend_extent)
314
- for y in range(blend_extent):
315
- b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
316
- return b
317
-
318
- def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
319
- blend_extent = min(a.shape[3], b.shape[3], blend_extent)
320
- for x in range(blend_extent):
321
- b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
322
- return b
323
-
324
- def tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True) -> AutoencoderKLOutput:
325
- r"""Encode a batch of images using a tiled encoder.
326
-
327
- When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
328
- steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
329
- different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
330
- tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
331
- output, but they should be much less noticeable.
332
-
333
- Args:
334
- x (`torch.FloatTensor`): Input batch of images.
335
- return_dict (`bool`, *optional*, defaults to `True`):
336
- Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
337
-
338
- Returns:
339
- [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:
340
- If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain
341
- `tuple` is returned.
342
- """
343
- overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
344
- blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
345
- row_limit = self.tile_latent_min_size - blend_extent
346
-
347
- # Split the image into 512x512 tiles and encode them separately.
348
- rows = []
349
- for i in range(0, x.shape[2], overlap_size):
350
- row = []
351
- for j in range(0, x.shape[3], overlap_size):
352
- tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
353
- tile = self.encoder(tile)
354
- tile = self.quant_conv(tile)
355
- row.append(tile)
356
- rows.append(row)
357
- result_rows = []
358
- for i, row in enumerate(rows):
359
- result_row = []
360
- for j, tile in enumerate(row):
361
- # blend the above tile and the left tile
362
- # to the current tile and add the current tile to the result row
363
- if i > 0:
364
- tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
365
- if j > 0:
366
- tile = self.blend_h(row[j - 1], tile, blend_extent)
367
- result_row.append(tile[:, :, :row_limit, :row_limit])
368
- result_rows.append(torch.cat(result_row, dim=3))
369
-
370
- moments = torch.cat(result_rows, dim=2)
371
- posterior = DiagonalGaussianDistribution(moments)
372
-
373
- if not return_dict:
374
- return (posterior,)
375
-
376
- return AutoencoderKLOutput(latent_dist=posterior)
377
-
378
- def tiled_decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:
379
- r"""
380
- Decode a batch of images using a tiled decoder.
381
-
382
- Args:
383
- z (`torch.FloatTensor`): Input batch of latent vectors.
384
- return_dict (`bool`, *optional*, defaults to `True`):
385
- Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
386
-
387
- Returns:
388
- [`~models.vae.DecoderOutput`] or `tuple`:
389
- If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
390
- returned.
391
- """
392
- overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
393
- blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
394
- row_limit = self.tile_sample_min_size - blend_extent
395
-
396
- # Split z into overlapping 64x64 tiles and decode them separately.
397
- # The tiles have an overlap to avoid seams between tiles.
398
- rows = []
399
- for i in range(0, z.shape[2], overlap_size):
400
- row = []
401
- for j in range(0, z.shape[3], overlap_size):
402
- tile = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
403
- tile = self.post_quant_conv(tile)
404
- decoded = self.decoder(tile)
405
- row.append(decoded)
406
- rows.append(row)
407
- result_rows = []
408
- for i, row in enumerate(rows):
409
- result_row = []
410
- for j, tile in enumerate(row):
411
- # blend the above tile and the left tile
412
- # to the current tile and add the current tile to the result row
413
- if i > 0:
414
- tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
415
- if j > 0:
416
- tile = self.blend_h(row[j - 1], tile, blend_extent)
417
- result_row.append(tile[:, :, :row_limit, :row_limit])
418
- result_rows.append(torch.cat(result_row, dim=3))
419
-
420
- dec = torch.cat(result_rows, dim=2)
421
- if not return_dict:
422
- return (dec,)
423
-
424
- return DecoderOutput(sample=dec)
425
-
426
- def forward(
427
- self,
428
- sample: torch.FloatTensor,
429
- sample_posterior: bool = False,
430
- return_dict: bool = True,
431
- generator: Optional[torch.Generator] = None,
432
- ) -> Union[DecoderOutput, torch.FloatTensor]:
433
- r"""
434
- Args:
435
- sample (`torch.FloatTensor`): Input sample.
436
- sample_posterior (`bool`, *optional*, defaults to `False`):
437
- Whether to sample from the posterior.
438
- return_dict (`bool`, *optional*, defaults to `True`):
439
- Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
440
- """
441
- x = sample
442
- posterior = self.encode(x).latent_dist
443
- if sample_posterior:
444
- z = posterior.sample(generator=generator)
445
- else:
446
- z = posterior.mode()
447
- dec = self.decode(z).sample
448
-
449
- if not return_dict:
450
- return (dec,)
451
-
452
- return DecoderOutput(sample=dec)
453
-
454
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
455
- def fuse_qkv_projections(self):
456
- """
457
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
458
- are fused. For cross-attention modules, key and value projection matrices are fused.
459
-
460
- <Tip warning={true}>
461
-
462
- This API is 🧪 experimental.
463
-
464
- </Tip>
465
- """
466
- self.original_attn_processors = None
467
-
468
- for _, attn_processor in self.attn_processors.items():
469
- if "Added" in str(attn_processor.__class__.__name__):
470
- raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
471
-
472
- self.original_attn_processors = self.attn_processors
473
-
474
- for module in self.modules():
475
- if isinstance(module, Attention):
476
- module.fuse_projections(fuse=True)
477
-
478
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
479
- def unfuse_qkv_projections(self):
480
- """Disables the fused QKV projection if enabled.
481
-
482
- <Tip warning={true}>
483
-
484
- This API is 🧪 experimental.
485
-
486
- </Tip>
487
-
488
- """
489
- if self.original_attn_processors is not None:
490
- self.set_attn_processor(self.original_attn_processors)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py DELETED
@@ -1,399 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import Dict, 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 import is_torch_version
21
- from ...utils.accelerate_utils import apply_forward_hook
22
- from ..attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
23
- from ..modeling_outputs import AutoencoderKLOutput
24
- from ..modeling_utils import ModelMixin
25
- from ..unets.unet_3d_blocks import MidBlockTemporalDecoder, UpBlockTemporalDecoder
26
- from .vae import DecoderOutput, DiagonalGaussianDistribution, Encoder
27
-
28
-
29
- class TemporalDecoder(nn.Module):
30
- def __init__(
31
- self,
32
- in_channels: int = 4,
33
- out_channels: int = 3,
34
- block_out_channels: Tuple[int] = (128, 256, 512, 512),
35
- layers_per_block: int = 2,
36
- ):
37
- super().__init__()
38
- self.layers_per_block = layers_per_block
39
-
40
- self.conv_in = nn.Conv2d(in_channels, block_out_channels[-1], kernel_size=3, stride=1, padding=1)
41
- self.mid_block = MidBlockTemporalDecoder(
42
- num_layers=self.layers_per_block,
43
- in_channels=block_out_channels[-1],
44
- out_channels=block_out_channels[-1],
45
- attention_head_dim=block_out_channels[-1],
46
- )
47
-
48
- # up
49
- self.up_blocks = nn.ModuleList([])
50
- reversed_block_out_channels = list(reversed(block_out_channels))
51
- output_channel = reversed_block_out_channels[0]
52
- for i in range(len(block_out_channels)):
53
- prev_output_channel = output_channel
54
- output_channel = reversed_block_out_channels[i]
55
-
56
- is_final_block = i == len(block_out_channels) - 1
57
- up_block = UpBlockTemporalDecoder(
58
- num_layers=self.layers_per_block + 1,
59
- in_channels=prev_output_channel,
60
- out_channels=output_channel,
61
- add_upsample=not is_final_block,
62
- )
63
- self.up_blocks.append(up_block)
64
- prev_output_channel = output_channel
65
-
66
- self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-6)
67
-
68
- self.conv_act = nn.SiLU()
69
- self.conv_out = torch.nn.Conv2d(
70
- in_channels=block_out_channels[0],
71
- out_channels=out_channels,
72
- kernel_size=3,
73
- padding=1,
74
- )
75
-
76
- conv_out_kernel_size = (3, 1, 1)
77
- padding = [int(k // 2) for k in conv_out_kernel_size]
78
- self.time_conv_out = torch.nn.Conv3d(
79
- in_channels=out_channels,
80
- out_channels=out_channels,
81
- kernel_size=conv_out_kernel_size,
82
- padding=padding,
83
- )
84
-
85
- self.gradient_checkpointing = False
86
-
87
- def forward(
88
- self,
89
- sample: torch.FloatTensor,
90
- image_only_indicator: torch.FloatTensor,
91
- num_frames: int = 1,
92
- ) -> torch.FloatTensor:
93
- r"""The forward method of the `Decoder` class."""
94
-
95
- sample = self.conv_in(sample)
96
-
97
- upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
98
- if self.training and self.gradient_checkpointing:
99
-
100
- def create_custom_forward(module):
101
- def custom_forward(*inputs):
102
- return module(*inputs)
103
-
104
- return custom_forward
105
-
106
- if is_torch_version(">=", "1.11.0"):
107
- # middle
108
- sample = torch.utils.checkpoint.checkpoint(
109
- create_custom_forward(self.mid_block),
110
- sample,
111
- image_only_indicator,
112
- use_reentrant=False,
113
- )
114
- sample = sample.to(upscale_dtype)
115
-
116
- # up
117
- for up_block in self.up_blocks:
118
- sample = torch.utils.checkpoint.checkpoint(
119
- create_custom_forward(up_block),
120
- sample,
121
- image_only_indicator,
122
- use_reentrant=False,
123
- )
124
- else:
125
- # middle
126
- sample = torch.utils.checkpoint.checkpoint(
127
- create_custom_forward(self.mid_block),
128
- sample,
129
- image_only_indicator,
130
- )
131
- sample = sample.to(upscale_dtype)
132
-
133
- # up
134
- for up_block in self.up_blocks:
135
- sample = torch.utils.checkpoint.checkpoint(
136
- create_custom_forward(up_block),
137
- sample,
138
- image_only_indicator,
139
- )
140
- else:
141
- # middle
142
- sample = self.mid_block(sample, image_only_indicator=image_only_indicator)
143
- sample = sample.to(upscale_dtype)
144
-
145
- # up
146
- for up_block in self.up_blocks:
147
- sample = up_block(sample, image_only_indicator=image_only_indicator)
148
-
149
- # post-process
150
- sample = self.conv_norm_out(sample)
151
- sample = self.conv_act(sample)
152
- sample = self.conv_out(sample)
153
-
154
- batch_frames, channels, height, width = sample.shape
155
- batch_size = batch_frames // num_frames
156
- sample = sample[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
157
- sample = self.time_conv_out(sample)
158
-
159
- sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
160
-
161
- return sample
162
-
163
-
164
- class AutoencoderKLTemporalDecoder(ModelMixin, ConfigMixin):
165
- r"""
166
- A VAE model with KL loss for encoding images into latents and decoding latent representations into images.
167
-
168
- This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
169
- for all models (such as downloading or saving).
170
-
171
- Parameters:
172
- in_channels (int, *optional*, defaults to 3): Number of channels in the input image.
173
- out_channels (int, *optional*, defaults to 3): Number of channels in the output.
174
- down_block_types (`Tuple[str]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
175
- Tuple of downsample block types.
176
- block_out_channels (`Tuple[int]`, *optional*, defaults to `(64,)`):
177
- Tuple of block output channels.
178
- layers_per_block: (`int`, *optional*, defaults to 1): Number of layers per block.
179
- latent_channels (`int`, *optional*, defaults to 4): Number of channels in the latent space.
180
- sample_size (`int`, *optional*, defaults to `32`): Sample input size.
181
- scaling_factor (`float`, *optional*, defaults to 0.18215):
182
- The component-wise standard deviation of the trained latent space computed using the first batch of the
183
- training set. This is used to scale the latent space to have unit variance when training the diffusion
184
- model. The latents are scaled with the formula `z = z * scaling_factor` before being passed to the
185
- diffusion model. When decoding, the latents are scaled back to the original scale with the formula: `z = 1
186
- / scaling_factor * z`. For more details, refer to sections 4.3.2 and D.1 of the [High-Resolution Image
187
- Synthesis with Latent Diffusion Models](https://arxiv.org/abs/2112.10752) paper.
188
- force_upcast (`bool`, *optional*, default to `True`):
189
- If enabled it will force the VAE to run in float32 for high image resolution pipelines, such as SD-XL. VAE
190
- can be fine-tuned / trained to a lower range without loosing too much precision in which case
191
- `force_upcast` can be set to `False` - see: https://huggingface.co/madebyollin/sdxl-vae-fp16-fix
192
- """
193
-
194
- _supports_gradient_checkpointing = True
195
-
196
- @register_to_config
197
- def __init__(
198
- self,
199
- in_channels: int = 3,
200
- out_channels: int = 3,
201
- down_block_types: Tuple[str] = ("DownEncoderBlock2D",),
202
- block_out_channels: Tuple[int] = (64,),
203
- layers_per_block: int = 1,
204
- latent_channels: int = 4,
205
- sample_size: int = 32,
206
- scaling_factor: float = 0.18215,
207
- force_upcast: float = True,
208
- ):
209
- super().__init__()
210
-
211
- # pass init params to Encoder
212
- self.encoder = Encoder(
213
- in_channels=in_channels,
214
- out_channels=latent_channels,
215
- down_block_types=down_block_types,
216
- block_out_channels=block_out_channels,
217
- layers_per_block=layers_per_block,
218
- double_z=True,
219
- )
220
-
221
- # pass init params to Decoder
222
- self.decoder = TemporalDecoder(
223
- in_channels=latent_channels,
224
- out_channels=out_channels,
225
- block_out_channels=block_out_channels,
226
- layers_per_block=layers_per_block,
227
- )
228
-
229
- self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
230
-
231
- sample_size = (
232
- self.config.sample_size[0]
233
- if isinstance(self.config.sample_size, (list, tuple))
234
- else self.config.sample_size
235
- )
236
- self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
237
- self.tile_overlap_factor = 0.25
238
-
239
- def _set_gradient_checkpointing(self, module, value=False):
240
- if isinstance(module, (Encoder, TemporalDecoder)):
241
- module.gradient_checkpointing = value
242
-
243
- @property
244
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
245
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
246
- r"""
247
- Returns:
248
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
249
- indexed by its weight name.
250
- """
251
- # set recursively
252
- processors = {}
253
-
254
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
255
- if hasattr(module, "get_processor"):
256
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
257
-
258
- for sub_name, child in module.named_children():
259
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
260
-
261
- return processors
262
-
263
- for name, module in self.named_children():
264
- fn_recursive_add_processors(name, module, processors)
265
-
266
- return processors
267
-
268
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
269
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
270
- r"""
271
- Sets the attention processor to use to compute attention.
272
-
273
- Parameters:
274
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
275
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
276
- for **all** `Attention` layers.
277
-
278
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
279
- processor. This is strongly recommended when setting trainable attention processors.
280
-
281
- """
282
- count = len(self.attn_processors.keys())
283
-
284
- if isinstance(processor, dict) and len(processor) != count:
285
- raise ValueError(
286
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
287
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
288
- )
289
-
290
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
291
- if hasattr(module, "set_processor"):
292
- if not isinstance(processor, dict):
293
- module.set_processor(processor)
294
- else:
295
- module.set_processor(processor.pop(f"{name}.processor"))
296
-
297
- for sub_name, child in module.named_children():
298
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
299
-
300
- for name, module in self.named_children():
301
- fn_recursive_attn_processor(name, module, processor)
302
-
303
- def set_default_attn_processor(self):
304
- """
305
- Disables custom attention processors and sets the default attention implementation.
306
- """
307
- if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
308
- processor = AttnProcessor()
309
- else:
310
- raise ValueError(
311
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
312
- )
313
-
314
- self.set_attn_processor(processor)
315
-
316
- @apply_forward_hook
317
- def encode(
318
- self, x: torch.FloatTensor, return_dict: bool = True
319
- ) -> Union[AutoencoderKLOutput, Tuple[DiagonalGaussianDistribution]]:
320
- """
321
- Encode a batch of images into latents.
322
-
323
- Args:
324
- x (`torch.FloatTensor`): Input batch of images.
325
- return_dict (`bool`, *optional*, defaults to `True`):
326
- Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.
327
-
328
- Returns:
329
- The latent representations of the encoded images. If `return_dict` is True, a
330
- [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.
331
- """
332
- h = self.encoder(x)
333
- moments = self.quant_conv(h)
334
- posterior = DiagonalGaussianDistribution(moments)
335
-
336
- if not return_dict:
337
- return (posterior,)
338
-
339
- return AutoencoderKLOutput(latent_dist=posterior)
340
-
341
- @apply_forward_hook
342
- def decode(
343
- self,
344
- z: torch.FloatTensor,
345
- num_frames: int,
346
- return_dict: bool = True,
347
- ) -> Union[DecoderOutput, torch.FloatTensor]:
348
- """
349
- Decode a batch of images.
350
-
351
- Args:
352
- z (`torch.FloatTensor`): Input batch of latent vectors.
353
- return_dict (`bool`, *optional*, defaults to `True`):
354
- Whether to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.
355
-
356
- Returns:
357
- [`~models.vae.DecoderOutput`] or `tuple`:
358
- If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is
359
- returned.
360
-
361
- """
362
- batch_size = z.shape[0] // num_frames
363
- image_only_indicator = torch.zeros(batch_size, num_frames, dtype=z.dtype, device=z.device)
364
- decoded = self.decoder(z, num_frames=num_frames, image_only_indicator=image_only_indicator)
365
-
366
- if not return_dict:
367
- return (decoded,)
368
-
369
- return DecoderOutput(sample=decoded)
370
-
371
- def forward(
372
- self,
373
- sample: torch.FloatTensor,
374
- sample_posterior: bool = False,
375
- return_dict: bool = True,
376
- generator: Optional[torch.Generator] = None,
377
- num_frames: int = 1,
378
- ) -> Union[DecoderOutput, torch.FloatTensor]:
379
- r"""
380
- Args:
381
- sample (`torch.FloatTensor`): Input sample.
382
- sample_posterior (`bool`, *optional*, defaults to `False`):
383
- Whether to sample from the posterior.
384
- return_dict (`bool`, *optional*, defaults to `True`):
385
- Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
386
- """
387
- x = sample
388
- posterior = self.encode(x).latent_dist
389
- if sample_posterior:
390
- z = posterior.sample(generator=generator)
391
- else:
392
- z = posterior.mode()
393
-
394
- dec = self.decode(z, num_frames=num_frames).sample
395
-
396
- if not return_dict:
397
- return (dec,)
398
-
399
- return DecoderOutput(sample=dec)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/autoencoders/autoencoder_tiny.py DELETED
@@ -1,349 +0,0 @@
1
- # Copyright 2024 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
- upsample_fn: str = "nearest",
106
- latent_channels: int = 4,
107
- upsampling_scaling_factor: int = 2,
108
- num_encoder_blocks: Tuple[int, ...] = (1, 3, 3, 3),
109
- num_decoder_blocks: Tuple[int, ...] = (3, 3, 3, 1),
110
- latent_magnitude: int = 3,
111
- latent_shift: float = 0.5,
112
- force_upcast: bool = False,
113
- scaling_factor: float = 1.0,
114
- ):
115
- super().__init__()
116
-
117
- if len(encoder_block_out_channels) != len(num_encoder_blocks):
118
- raise ValueError("`encoder_block_out_channels` should have the same length as `num_encoder_blocks`.")
119
- if len(decoder_block_out_channels) != len(num_decoder_blocks):
120
- raise ValueError("`decoder_block_out_channels` should have the same length as `num_decoder_blocks`.")
121
-
122
- self.encoder = EncoderTiny(
123
- in_channels=in_channels,
124
- out_channels=latent_channels,
125
- num_blocks=num_encoder_blocks,
126
- block_out_channels=encoder_block_out_channels,
127
- act_fn=act_fn,
128
- )
129
-
130
- self.decoder = DecoderTiny(
131
- in_channels=latent_channels,
132
- out_channels=out_channels,
133
- num_blocks=num_decoder_blocks,
134
- block_out_channels=decoder_block_out_channels,
135
- upsampling_scaling_factor=upsampling_scaling_factor,
136
- act_fn=act_fn,
137
- upsample_fn=upsample_fn,
138
- )
139
-
140
- self.latent_magnitude = latent_magnitude
141
- self.latent_shift = latent_shift
142
- self.scaling_factor = scaling_factor
143
-
144
- self.use_slicing = False
145
- self.use_tiling = False
146
-
147
- # only relevant if vae tiling is enabled
148
- self.spatial_scale_factor = 2**out_channels
149
- self.tile_overlap_factor = 0.125
150
- self.tile_sample_min_size = 512
151
- self.tile_latent_min_size = self.tile_sample_min_size // self.spatial_scale_factor
152
-
153
- self.register_to_config(block_out_channels=decoder_block_out_channels)
154
- self.register_to_config(force_upcast=False)
155
-
156
- def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
157
- if isinstance(module, (EncoderTiny, DecoderTiny)):
158
- module.gradient_checkpointing = value
159
-
160
- def scale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
161
- """raw latents -> [0, 1]"""
162
- return x.div(2 * self.latent_magnitude).add(self.latent_shift).clamp(0, 1)
163
-
164
- def unscale_latents(self, x: torch.FloatTensor) -> torch.FloatTensor:
165
- """[0, 1] -> raw latents"""
166
- return x.sub(self.latent_shift).mul(2 * self.latent_magnitude)
167
-
168
- def enable_slicing(self) -> None:
169
- r"""
170
- Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
171
- compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
172
- """
173
- self.use_slicing = True
174
-
175
- def disable_slicing(self) -> None:
176
- r"""
177
- Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
178
- decoding in one step.
179
- """
180
- self.use_slicing = False
181
-
182
- def enable_tiling(self, use_tiling: bool = True) -> None:
183
- r"""
184
- Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
185
- compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
186
- processing larger images.
187
- """
188
- self.use_tiling = use_tiling
189
-
190
- def disable_tiling(self) -> None:
191
- r"""
192
- Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
193
- decoding in one step.
194
- """
195
- self.enable_tiling(False)
196
-
197
- def _tiled_encode(self, x: torch.FloatTensor) -> torch.FloatTensor:
198
- r"""Encode a batch of images using a tiled encoder.
199
-
200
- When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
201
- steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
202
- tiles overlap and are blended together to form a smooth output.
203
-
204
- Args:
205
- x (`torch.FloatTensor`): Input batch of images.
206
-
207
- Returns:
208
- `torch.FloatTensor`: Encoded batch of images.
209
- """
210
- # scale of encoder output relative to input
211
- sf = self.spatial_scale_factor
212
- tile_size = self.tile_sample_min_size
213
-
214
- # number of pixels to blend and to traverse between tile
215
- blend_size = int(tile_size * self.tile_overlap_factor)
216
- traverse_size = tile_size - blend_size
217
-
218
- # tiles index (up/left)
219
- ti = range(0, x.shape[-2], traverse_size)
220
- tj = range(0, x.shape[-1], traverse_size)
221
-
222
- # mask for blending
223
- blend_masks = torch.stack(
224
- torch.meshgrid([torch.arange(tile_size / sf) / (blend_size / sf - 1)] * 2, indexing="ij")
225
- )
226
- blend_masks = blend_masks.clamp(0, 1).to(x.device)
227
-
228
- # output array
229
- out = torch.zeros(x.shape[0], 4, x.shape[-2] // sf, x.shape[-1] // sf, device=x.device)
230
- for i in ti:
231
- for j in tj:
232
- tile_in = x[..., i : i + tile_size, j : j + tile_size]
233
- # tile result
234
- tile_out = out[..., i // sf : (i + tile_size) // sf, j // sf : (j + tile_size) // sf]
235
- tile = self.encoder(tile_in)
236
- h, w = tile.shape[-2], tile.shape[-1]
237
- # blend tile result into output
238
- blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
239
- blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
240
- blend_mask = blend_mask_i * blend_mask_j
241
- tile, blend_mask = tile[..., :h, :w], blend_mask[..., :h, :w]
242
- tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
243
- return out
244
-
245
- def _tiled_decode(self, x: torch.FloatTensor) -> torch.FloatTensor:
246
- r"""Encode a batch of images using a tiled encoder.
247
-
248
- When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
249
- steps. This is useful to keep memory use constant regardless of image size. To avoid tiling artifacts, the
250
- tiles overlap and are blended together to form a smooth output.
251
-
252
- Args:
253
- x (`torch.FloatTensor`): Input batch of images.
254
-
255
- Returns:
256
- `torch.FloatTensor`: Encoded batch of images.
257
- """
258
- # scale of decoder output relative to input
259
- sf = self.spatial_scale_factor
260
- tile_size = self.tile_latent_min_size
261
-
262
- # number of pixels to blend and to traverse between tiles
263
- blend_size = int(tile_size * self.tile_overlap_factor)
264
- traverse_size = tile_size - blend_size
265
-
266
- # tiles index (up/left)
267
- ti = range(0, x.shape[-2], traverse_size)
268
- tj = range(0, x.shape[-1], traverse_size)
269
-
270
- # mask for blending
271
- blend_masks = torch.stack(
272
- torch.meshgrid([torch.arange(tile_size * sf) / (blend_size * sf - 1)] * 2, indexing="ij")
273
- )
274
- blend_masks = blend_masks.clamp(0, 1).to(x.device)
275
-
276
- # output array
277
- out = torch.zeros(x.shape[0], 3, x.shape[-2] * sf, x.shape[-1] * sf, device=x.device)
278
- for i in ti:
279
- for j in tj:
280
- tile_in = x[..., i : i + tile_size, j : j + tile_size]
281
- # tile result
282
- tile_out = out[..., i * sf : (i + tile_size) * sf, j * sf : (j + tile_size) * sf]
283
- tile = self.decoder(tile_in)
284
- h, w = tile.shape[-2], tile.shape[-1]
285
- # blend tile result into output
286
- blend_mask_i = torch.ones_like(blend_masks[0]) if i == 0 else blend_masks[0]
287
- blend_mask_j = torch.ones_like(blend_masks[1]) if j == 0 else blend_masks[1]
288
- blend_mask = (blend_mask_i * blend_mask_j)[..., :h, :w]
289
- tile_out.copy_(blend_mask * tile + (1 - blend_mask) * tile_out)
290
- return out
291
-
292
- @apply_forward_hook
293
- def encode(
294
- self, x: torch.FloatTensor, return_dict: bool = True
295
- ) -> Union[AutoencoderTinyOutput, Tuple[torch.FloatTensor]]:
296
- if self.use_slicing and x.shape[0] > 1:
297
- output = [
298
- self._tiled_encode(x_slice) if self.use_tiling else self.encoder(x_slice) for x_slice in x.split(1)
299
- ]
300
- output = torch.cat(output)
301
- else:
302
- output = self._tiled_encode(x) if self.use_tiling else self.encoder(x)
303
-
304
- if not return_dict:
305
- return (output,)
306
-
307
- return AutoencoderTinyOutput(latents=output)
308
-
309
- @apply_forward_hook
310
- def decode(
311
- self, x: torch.FloatTensor, generator: Optional[torch.Generator] = None, return_dict: bool = True
312
- ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
313
- if self.use_slicing and x.shape[0] > 1:
314
- output = [self._tiled_decode(x_slice) if self.use_tiling else self.decoder(x) for x_slice in x.split(1)]
315
- output = torch.cat(output)
316
- else:
317
- output = self._tiled_decode(x) if self.use_tiling else self.decoder(x)
318
-
319
- if not return_dict:
320
- return (output,)
321
-
322
- return DecoderOutput(sample=output)
323
-
324
- def forward(
325
- self,
326
- sample: torch.FloatTensor,
327
- return_dict: bool = True,
328
- ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
329
- r"""
330
- Args:
331
- sample (`torch.FloatTensor`): Input sample.
332
- return_dict (`bool`, *optional*, defaults to `True`):
333
- Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
334
- """
335
- enc = self.encode(sample).latents
336
-
337
- # scale latents to be in [0, 1], then quantize latents to a byte tensor,
338
- # as if we were storing the latents in an RGBA uint8 image.
339
- scaled_enc = self.scale_latents(enc).mul_(255).round_().byte()
340
-
341
- # unquantize latents back into [0, 1], then unscale latents back to their original range,
342
- # as if we were loading the latents from an RGBA uint8 image.
343
- unscaled_enc = self.unscale_latents(scaled_enc / 255.0)
344
-
345
- dec = self.decode(unscaled_enc)
346
-
347
- if not return_dict:
348
- return (dec,)
349
- return DecoderOutput(sample=dec)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/autoencoders/consistency_decoder_vae.py DELETED
@@ -1,462 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from 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 ..unets.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
- >>> image = pipe("horse", generator=torch.manual_seed(0)).images[0]
67
- >>> image
68
- ```
69
- """
70
-
71
- @register_to_config
72
- def __init__(
73
- self,
74
- scaling_factor: float = 0.18215,
75
- latent_channels: int = 4,
76
- sample_size: int = 32,
77
- encoder_act_fn: str = "silu",
78
- encoder_block_out_channels: Tuple[int, ...] = (128, 256, 512, 512),
79
- encoder_double_z: bool = True,
80
- encoder_down_block_types: Tuple[str, ...] = (
81
- "DownEncoderBlock2D",
82
- "DownEncoderBlock2D",
83
- "DownEncoderBlock2D",
84
- "DownEncoderBlock2D",
85
- ),
86
- encoder_in_channels: int = 3,
87
- encoder_layers_per_block: int = 2,
88
- encoder_norm_num_groups: int = 32,
89
- encoder_out_channels: int = 4,
90
- decoder_add_attention: bool = False,
91
- decoder_block_out_channels: Tuple[int, ...] = (320, 640, 1024, 1024),
92
- decoder_down_block_types: Tuple[str, ...] = (
93
- "ResnetDownsampleBlock2D",
94
- "ResnetDownsampleBlock2D",
95
- "ResnetDownsampleBlock2D",
96
- "ResnetDownsampleBlock2D",
97
- ),
98
- decoder_downsample_padding: int = 1,
99
- decoder_in_channels: int = 7,
100
- decoder_layers_per_block: int = 3,
101
- decoder_norm_eps: float = 1e-05,
102
- decoder_norm_num_groups: int = 32,
103
- decoder_num_train_timesteps: int = 1024,
104
- decoder_out_channels: int = 6,
105
- decoder_resnet_time_scale_shift: str = "scale_shift",
106
- decoder_time_embedding_type: str = "learned",
107
- decoder_up_block_types: Tuple[str, ...] = (
108
- "ResnetUpsampleBlock2D",
109
- "ResnetUpsampleBlock2D",
110
- "ResnetUpsampleBlock2D",
111
- "ResnetUpsampleBlock2D",
112
- ),
113
- ):
114
- super().__init__()
115
- self.encoder = Encoder(
116
- act_fn=encoder_act_fn,
117
- block_out_channels=encoder_block_out_channels,
118
- double_z=encoder_double_z,
119
- down_block_types=encoder_down_block_types,
120
- in_channels=encoder_in_channels,
121
- layers_per_block=encoder_layers_per_block,
122
- norm_num_groups=encoder_norm_num_groups,
123
- out_channels=encoder_out_channels,
124
- )
125
-
126
- self.decoder_unet = UNet2DModel(
127
- add_attention=decoder_add_attention,
128
- block_out_channels=decoder_block_out_channels,
129
- down_block_types=decoder_down_block_types,
130
- downsample_padding=decoder_downsample_padding,
131
- in_channels=decoder_in_channels,
132
- layers_per_block=decoder_layers_per_block,
133
- norm_eps=decoder_norm_eps,
134
- norm_num_groups=decoder_norm_num_groups,
135
- num_train_timesteps=decoder_num_train_timesteps,
136
- out_channels=decoder_out_channels,
137
- resnet_time_scale_shift=decoder_resnet_time_scale_shift,
138
- time_embedding_type=decoder_time_embedding_type,
139
- up_block_types=decoder_up_block_types,
140
- )
141
- self.decoder_scheduler = ConsistencyDecoderScheduler()
142
- self.register_to_config(block_out_channels=encoder_block_out_channels)
143
- self.register_to_config(force_upcast=False)
144
- self.register_buffer(
145
- "means",
146
- torch.tensor([0.38862467, 0.02253063, 0.07381133, -0.0171294])[None, :, None, None],
147
- persistent=False,
148
- )
149
- self.register_buffer(
150
- "stds", torch.tensor([0.9654121, 1.0440036, 0.76147926, 0.77022034])[None, :, None, None], persistent=False
151
- )
152
-
153
- self.quant_conv = nn.Conv2d(2 * latent_channels, 2 * latent_channels, 1)
154
-
155
- self.use_slicing = False
156
- self.use_tiling = False
157
-
158
- # only relevant if vae tiling is enabled
159
- self.tile_sample_min_size = self.config.sample_size
160
- sample_size = (
161
- self.config.sample_size[0]
162
- if isinstance(self.config.sample_size, (list, tuple))
163
- else self.config.sample_size
164
- )
165
- self.tile_latent_min_size = int(sample_size / (2 ** (len(self.config.block_out_channels) - 1)))
166
- self.tile_overlap_factor = 0.25
167
-
168
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_tiling
169
- def enable_tiling(self, use_tiling: bool = True):
170
- r"""
171
- Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
172
- compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
173
- processing larger images.
174
- """
175
- self.use_tiling = use_tiling
176
-
177
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_tiling
178
- def disable_tiling(self):
179
- r"""
180
- Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing
181
- decoding in one step.
182
- """
183
- self.enable_tiling(False)
184
-
185
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.enable_slicing
186
- def enable_slicing(self):
187
- r"""
188
- Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
189
- compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
190
- """
191
- self.use_slicing = True
192
-
193
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.disable_slicing
194
- def disable_slicing(self):
195
- r"""
196
- Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing
197
- decoding in one step.
198
- """
199
- self.use_slicing = False
200
-
201
- @property
202
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
203
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
204
- r"""
205
- Returns:
206
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
207
- indexed by its weight name.
208
- """
209
- # set recursively
210
- processors = {}
211
-
212
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
213
- if hasattr(module, "get_processor"):
214
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
215
-
216
- for sub_name, child in module.named_children():
217
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
218
-
219
- return processors
220
-
221
- for name, module in self.named_children():
222
- fn_recursive_add_processors(name, module, processors)
223
-
224
- return processors
225
-
226
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
227
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
228
- r"""
229
- Sets the attention processor to use to compute attention.
230
-
231
- Parameters:
232
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
233
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
234
- for **all** `Attention` layers.
235
-
236
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
237
- processor. This is strongly recommended when setting trainable attention processors.
238
-
239
- """
240
- count = len(self.attn_processors.keys())
241
-
242
- if isinstance(processor, dict) and len(processor) != count:
243
- raise ValueError(
244
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
245
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
246
- )
247
-
248
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
249
- if hasattr(module, "set_processor"):
250
- if not isinstance(processor, dict):
251
- module.set_processor(processor)
252
- else:
253
- module.set_processor(processor.pop(f"{name}.processor"))
254
-
255
- for sub_name, child in module.named_children():
256
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
257
-
258
- for name, module in self.named_children():
259
- fn_recursive_attn_processor(name, module, processor)
260
-
261
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
262
- def set_default_attn_processor(self):
263
- """
264
- Disables custom attention processors and sets the default attention implementation.
265
- """
266
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
267
- processor = AttnAddedKVProcessor()
268
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
269
- processor = AttnProcessor()
270
- else:
271
- raise ValueError(
272
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
273
- )
274
-
275
- self.set_attn_processor(processor)
276
-
277
- @apply_forward_hook
278
- def encode(
279
- self, x: torch.FloatTensor, return_dict: bool = True
280
- ) -> Union[ConsistencyDecoderVAEOutput, Tuple[DiagonalGaussianDistribution]]:
281
- """
282
- Encode a batch of images into latents.
283
-
284
- Args:
285
- x (`torch.FloatTensor`): Input batch of images.
286
- return_dict (`bool`, *optional*, defaults to `True`):
287
- Whether to return a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] instead of a plain
288
- tuple.
289
-
290
- Returns:
291
- The latent representations of the encoded images. If `return_dict` is True, a
292
- [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned, otherwise a plain `tuple`
293
- is returned.
294
- """
295
- if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
296
- return self.tiled_encode(x, return_dict=return_dict)
297
-
298
- if self.use_slicing and x.shape[0] > 1:
299
- encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]
300
- h = torch.cat(encoded_slices)
301
- else:
302
- h = self.encoder(x)
303
-
304
- moments = self.quant_conv(h)
305
- posterior = DiagonalGaussianDistribution(moments)
306
-
307
- if not return_dict:
308
- return (posterior,)
309
-
310
- return ConsistencyDecoderVAEOutput(latent_dist=posterior)
311
-
312
- @apply_forward_hook
313
- def decode(
314
- self,
315
- z: torch.FloatTensor,
316
- generator: Optional[torch.Generator] = None,
317
- return_dict: bool = True,
318
- num_inference_steps: int = 2,
319
- ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
320
- """
321
- Decodes the input latent vector `z` using the consistency decoder VAE model.
322
-
323
- Args:
324
- z (torch.FloatTensor): The input latent vector.
325
- generator (Optional[torch.Generator]): The random number generator. Default is None.
326
- return_dict (bool): Whether to return the output as a dictionary. Default is True.
327
- num_inference_steps (int): The number of inference steps. Default is 2.
328
-
329
- Returns:
330
- Union[DecoderOutput, Tuple[torch.FloatTensor]]: The decoded output.
331
-
332
- """
333
- z = (z * self.config.scaling_factor - self.means) / self.stds
334
-
335
- scale_factor = 2 ** (len(self.config.block_out_channels) - 1)
336
- z = F.interpolate(z, mode="nearest", scale_factor=scale_factor)
337
-
338
- batch_size, _, height, width = z.shape
339
-
340
- self.decoder_scheduler.set_timesteps(num_inference_steps, device=self.device)
341
-
342
- x_t = self.decoder_scheduler.init_noise_sigma * randn_tensor(
343
- (batch_size, 3, height, width), generator=generator, dtype=z.dtype, device=z.device
344
- )
345
-
346
- for t in self.decoder_scheduler.timesteps:
347
- model_input = torch.concat([self.decoder_scheduler.scale_model_input(x_t, t), z], dim=1)
348
- model_output = self.decoder_unet(model_input, t).sample[:, :3, :, :]
349
- prev_sample = self.decoder_scheduler.step(model_output, t, x_t, generator).prev_sample
350
- x_t = prev_sample
351
-
352
- x_0 = x_t
353
-
354
- if not return_dict:
355
- return (x_0,)
356
-
357
- return DecoderOutput(sample=x_0)
358
-
359
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_v
360
- def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
361
- blend_extent = min(a.shape[2], b.shape[2], blend_extent)
362
- for y in range(blend_extent):
363
- b[:, :, y, :] = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
364
- return b
365
-
366
- # Copied from diffusers.models.autoencoders.autoencoder_kl.AutoencoderKL.blend_h
367
- def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:
368
- blend_extent = min(a.shape[3], b.shape[3], blend_extent)
369
- for x in range(blend_extent):
370
- b[:, :, :, x] = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
371
- return b
372
-
373
- def tiled_encode(
374
- self, x: torch.FloatTensor, return_dict: bool = True
375
- ) -> Union[ConsistencyDecoderVAEOutput, Tuple]:
376
- r"""Encode a batch of images using a tiled encoder.
377
-
378
- When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several
379
- steps. This is useful to keep memory use constant regardless of image size. The end result of tiled encoding is
380
- different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the
381
- tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the
382
- output, but they should be much less noticeable.
383
-
384
- Args:
385
- x (`torch.FloatTensor`): Input batch of images.
386
- return_dict (`bool`, *optional*, defaults to `True`):
387
- Whether or not to return a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] instead of a
388
- plain tuple.
389
-
390
- Returns:
391
- [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] or `tuple`:
392
- If return_dict is True, a [`~models.consistency_decoder_vae.ConsistencyDecoderVAEOutput`] is returned,
393
- otherwise a plain `tuple` is returned.
394
- """
395
- overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
396
- blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
397
- row_limit = self.tile_latent_min_size - blend_extent
398
-
399
- # Split the image into 512x512 tiles and encode them separately.
400
- rows = []
401
- for i in range(0, x.shape[2], overlap_size):
402
- row = []
403
- for j in range(0, x.shape[3], overlap_size):
404
- tile = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
405
- tile = self.encoder(tile)
406
- tile = self.quant_conv(tile)
407
- row.append(tile)
408
- rows.append(row)
409
- result_rows = []
410
- for i, row in enumerate(rows):
411
- result_row = []
412
- for j, tile in enumerate(row):
413
- # blend the above tile and the left tile
414
- # to the current tile and add the current tile to the result row
415
- if i > 0:
416
- tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
417
- if j > 0:
418
- tile = self.blend_h(row[j - 1], tile, blend_extent)
419
- result_row.append(tile[:, :, :row_limit, :row_limit])
420
- result_rows.append(torch.cat(result_row, dim=3))
421
-
422
- moments = torch.cat(result_rows, dim=2)
423
- posterior = DiagonalGaussianDistribution(moments)
424
-
425
- if not return_dict:
426
- return (posterior,)
427
-
428
- return ConsistencyDecoderVAEOutput(latent_dist=posterior)
429
-
430
- def forward(
431
- self,
432
- sample: torch.FloatTensor,
433
- sample_posterior: bool = False,
434
- return_dict: bool = True,
435
- generator: Optional[torch.Generator] = None,
436
- ) -> Union[DecoderOutput, Tuple[torch.FloatTensor]]:
437
- r"""
438
- Args:
439
- sample (`torch.FloatTensor`): Input sample.
440
- sample_posterior (`bool`, *optional*, defaults to `False`):
441
- Whether to sample from the posterior.
442
- return_dict (`bool`, *optional*, defaults to `True`):
443
- Whether or not to return a [`DecoderOutput`] instead of a plain tuple.
444
- generator (`torch.Generator`, *optional*, defaults to `None`):
445
- Generator to use for sampling.
446
-
447
- Returns:
448
- [`DecoderOutput`] or `tuple`:
449
- If return_dict is True, a [`DecoderOutput`] is returned, otherwise a plain `tuple` is returned.
450
- """
451
- x = sample
452
- posterior = self.encode(x).latent_dist
453
- if sample_posterior:
454
- z = posterior.sample(generator=generator)
455
- else:
456
- z = posterior.mode()
457
- dec = self.decode(z, generator=generator).sample
458
-
459
- if not return_dict:
460
- return (dec,)
461
-
462
- return DecoderOutput(sample=dec)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/autoencoders/vae.py DELETED
@@ -1,981 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from typing import Optional, Tuple
16
-
17
- import numpy as np
18
- import torch
19
- import torch.nn as nn
20
-
21
- from ...utils import BaseOutput, is_torch_version
22
- from ...utils.torch_utils import randn_tensor
23
- from ..activations import get_activation
24
- from ..attention_processor import SpatialNorm
25
- from ..unets.unet_2d_blocks import (
26
- AutoencoderTinyBlock,
27
- UNetMidBlock2D,
28
- get_down_block,
29
- get_up_block,
30
- )
31
-
32
-
33
- @dataclass
34
- class DecoderOutput(BaseOutput):
35
- r"""
36
- Output of decoding method.
37
-
38
- Args:
39
- sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
40
- The decoded output sample from the last layer of the model.
41
- """
42
-
43
- sample: torch.FloatTensor
44
-
45
-
46
- class Encoder(nn.Module):
47
- r"""
48
- The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
49
-
50
- Args:
51
- in_channels (`int`, *optional*, defaults to 3):
52
- The number of input channels.
53
- out_channels (`int`, *optional*, defaults to 3):
54
- The number of output channels.
55
- down_block_types (`Tuple[str, ...]`, *optional*, defaults to `("DownEncoderBlock2D",)`):
56
- The types of down blocks to use. See `~diffusers.models.unet_2d_blocks.get_down_block` for available
57
- options.
58
- block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
59
- The number of output channels for each block.
60
- layers_per_block (`int`, *optional*, defaults to 2):
61
- The number of layers per block.
62
- norm_num_groups (`int`, *optional*, defaults to 32):
63
- The number of groups for normalization.
64
- act_fn (`str`, *optional*, defaults to `"silu"`):
65
- The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
66
- double_z (`bool`, *optional*, defaults to `True`):
67
- Whether to double the number of output channels for the last block.
68
- """
69
-
70
- def __init__(
71
- self,
72
- in_channels: int = 3,
73
- out_channels: int = 3,
74
- down_block_types: Tuple[str, ...] = ("DownEncoderBlock2D",),
75
- block_out_channels: Tuple[int, ...] = (64,),
76
- layers_per_block: int = 2,
77
- norm_num_groups: int = 32,
78
- act_fn: str = "silu",
79
- double_z: bool = True,
80
- mid_block_add_attention=True,
81
- ):
82
- super().__init__()
83
- self.layers_per_block = layers_per_block
84
-
85
- self.conv_in = nn.Conv2d(
86
- in_channels,
87
- block_out_channels[0],
88
- kernel_size=3,
89
- stride=1,
90
- padding=1,
91
- )
92
-
93
- self.down_blocks = nn.ModuleList([])
94
-
95
- # down
96
- output_channel = block_out_channels[0]
97
- for i, down_block_type in enumerate(down_block_types):
98
- input_channel = output_channel
99
- output_channel = block_out_channels[i]
100
- is_final_block = i == len(block_out_channels) - 1
101
-
102
- down_block = get_down_block(
103
- down_block_type,
104
- num_layers=self.layers_per_block,
105
- in_channels=input_channel,
106
- out_channels=output_channel,
107
- add_downsample=not is_final_block,
108
- resnet_eps=1e-6,
109
- downsample_padding=0,
110
- resnet_act_fn=act_fn,
111
- resnet_groups=norm_num_groups,
112
- attention_head_dim=output_channel,
113
- temb_channels=None,
114
- )
115
- self.down_blocks.append(down_block)
116
-
117
- # mid
118
- self.mid_block = UNetMidBlock2D(
119
- in_channels=block_out_channels[-1],
120
- resnet_eps=1e-6,
121
- resnet_act_fn=act_fn,
122
- output_scale_factor=1,
123
- resnet_time_scale_shift="default",
124
- attention_head_dim=block_out_channels[-1],
125
- resnet_groups=norm_num_groups,
126
- temb_channels=None,
127
- add_attention=mid_block_add_attention,
128
- )
129
-
130
- # out
131
- self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6)
132
- self.conv_act = nn.SiLU()
133
-
134
- conv_out_channels = 2 * out_channels if double_z else out_channels
135
- self.conv_out = nn.Conv2d(block_out_channels[-1], conv_out_channels, 3, padding=1)
136
-
137
- self.gradient_checkpointing = False
138
-
139
- def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:
140
- r"""The forward method of the `Encoder` class."""
141
-
142
- sample = self.conv_in(sample)
143
-
144
- if self.training and self.gradient_checkpointing:
145
-
146
- def create_custom_forward(module):
147
- def custom_forward(*inputs):
148
- return module(*inputs)
149
-
150
- return custom_forward
151
-
152
- # down
153
- if is_torch_version(">=", "1.11.0"):
154
- for down_block in self.down_blocks:
155
- sample = torch.utils.checkpoint.checkpoint(
156
- create_custom_forward(down_block), sample, use_reentrant=False
157
- )
158
- # middle
159
- sample = torch.utils.checkpoint.checkpoint(
160
- create_custom_forward(self.mid_block), sample, use_reentrant=False
161
- )
162
- else:
163
- for down_block in self.down_blocks:
164
- sample = torch.utils.checkpoint.checkpoint(create_custom_forward(down_block), sample)
165
- # middle
166
- sample = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block), sample)
167
-
168
- else:
169
- # down
170
- for down_block in self.down_blocks:
171
- sample = down_block(sample)
172
-
173
- # middle
174
- sample = self.mid_block(sample)
175
-
176
- # post-process
177
- sample = self.conv_norm_out(sample)
178
- sample = self.conv_act(sample)
179
- sample = self.conv_out(sample)
180
-
181
- return sample
182
-
183
-
184
- class Decoder(nn.Module):
185
- r"""
186
- The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
187
-
188
- Args:
189
- in_channels (`int`, *optional*, defaults to 3):
190
- The number of input channels.
191
- out_channels (`int`, *optional*, defaults to 3):
192
- The number of output channels.
193
- up_block_types (`Tuple[str, ...]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
194
- The types of up blocks to use. See `~diffusers.models.unet_2d_blocks.get_up_block` for available options.
195
- block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
196
- The number of output channels for each block.
197
- layers_per_block (`int`, *optional*, defaults to 2):
198
- The number of layers per block.
199
- norm_num_groups (`int`, *optional*, defaults to 32):
200
- The number of groups for normalization.
201
- act_fn (`str`, *optional*, defaults to `"silu"`):
202
- The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
203
- norm_type (`str`, *optional*, defaults to `"group"`):
204
- The normalization type to use. Can be either `"group"` or `"spatial"`.
205
- """
206
-
207
- def __init__(
208
- self,
209
- in_channels: int = 3,
210
- out_channels: int = 3,
211
- up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
212
- block_out_channels: Tuple[int, ...] = (64,),
213
- layers_per_block: int = 2,
214
- norm_num_groups: int = 32,
215
- act_fn: str = "silu",
216
- norm_type: str = "group", # group, spatial
217
- mid_block_add_attention=True,
218
- ):
219
- super().__init__()
220
- self.layers_per_block = layers_per_block
221
-
222
- self.conv_in = nn.Conv2d(
223
- in_channels,
224
- block_out_channels[-1],
225
- kernel_size=3,
226
- stride=1,
227
- padding=1,
228
- )
229
-
230
- self.up_blocks = nn.ModuleList([])
231
-
232
- temb_channels = in_channels if norm_type == "spatial" else None
233
-
234
- # mid
235
- self.mid_block = UNetMidBlock2D(
236
- in_channels=block_out_channels[-1],
237
- resnet_eps=1e-6,
238
- resnet_act_fn=act_fn,
239
- output_scale_factor=1,
240
- resnet_time_scale_shift="default" if norm_type == "group" else norm_type,
241
- attention_head_dim=block_out_channels[-1],
242
- resnet_groups=norm_num_groups,
243
- temb_channels=temb_channels,
244
- add_attention=mid_block_add_attention,
245
- )
246
-
247
- # up
248
- reversed_block_out_channels = list(reversed(block_out_channels))
249
- output_channel = reversed_block_out_channels[0]
250
- for i, up_block_type in enumerate(up_block_types):
251
- prev_output_channel = output_channel
252
- output_channel = reversed_block_out_channels[i]
253
-
254
- is_final_block = i == len(block_out_channels) - 1
255
-
256
- up_block = get_up_block(
257
- up_block_type,
258
- num_layers=self.layers_per_block + 1,
259
- in_channels=prev_output_channel,
260
- out_channels=output_channel,
261
- prev_output_channel=None,
262
- add_upsample=not is_final_block,
263
- resnet_eps=1e-6,
264
- resnet_act_fn=act_fn,
265
- resnet_groups=norm_num_groups,
266
- attention_head_dim=output_channel,
267
- temb_channels=temb_channels,
268
- resnet_time_scale_shift=norm_type,
269
- )
270
- self.up_blocks.append(up_block)
271
- prev_output_channel = output_channel
272
-
273
- # out
274
- if norm_type == "spatial":
275
- self.conv_norm_out = SpatialNorm(block_out_channels[0], temb_channels)
276
- else:
277
- self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6)
278
- self.conv_act = nn.SiLU()
279
- self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, 3, padding=1)
280
-
281
- self.gradient_checkpointing = False
282
-
283
- def forward(
284
- self,
285
- sample: torch.FloatTensor,
286
- latent_embeds: Optional[torch.FloatTensor] = None,
287
- ) -> torch.FloatTensor:
288
- r"""The forward method of the `Decoder` class."""
289
-
290
- sample = self.conv_in(sample)
291
-
292
- upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
293
- if self.training and self.gradient_checkpointing:
294
-
295
- def create_custom_forward(module):
296
- def custom_forward(*inputs):
297
- return module(*inputs)
298
-
299
- return custom_forward
300
-
301
- if is_torch_version(">=", "1.11.0"):
302
- # middle
303
- sample = torch.utils.checkpoint.checkpoint(
304
- create_custom_forward(self.mid_block),
305
- sample,
306
- latent_embeds,
307
- use_reentrant=False,
308
- )
309
- sample = sample.to(upscale_dtype)
310
-
311
- # up
312
- for up_block in self.up_blocks:
313
- sample = torch.utils.checkpoint.checkpoint(
314
- create_custom_forward(up_block),
315
- sample,
316
- latent_embeds,
317
- use_reentrant=False,
318
- )
319
- else:
320
- # middle
321
- sample = torch.utils.checkpoint.checkpoint(
322
- create_custom_forward(self.mid_block), sample, latent_embeds
323
- )
324
- sample = sample.to(upscale_dtype)
325
-
326
- # up
327
- for up_block in self.up_blocks:
328
- sample = torch.utils.checkpoint.checkpoint(create_custom_forward(up_block), sample, latent_embeds)
329
- else:
330
- # middle
331
- sample = self.mid_block(sample, latent_embeds)
332
- sample = sample.to(upscale_dtype)
333
-
334
- # up
335
- for up_block in self.up_blocks:
336
- sample = up_block(sample, latent_embeds)
337
-
338
- # post-process
339
- if latent_embeds is None:
340
- sample = self.conv_norm_out(sample)
341
- else:
342
- sample = self.conv_norm_out(sample, latent_embeds)
343
- sample = self.conv_act(sample)
344
- sample = self.conv_out(sample)
345
-
346
- return sample
347
-
348
-
349
- class UpSample(nn.Module):
350
- r"""
351
- The `UpSample` layer of a variational autoencoder that upsamples its input.
352
-
353
- Args:
354
- in_channels (`int`, *optional*, defaults to 3):
355
- The number of input channels.
356
- out_channels (`int`, *optional*, defaults to 3):
357
- The number of output channels.
358
- """
359
-
360
- def __init__(
361
- self,
362
- in_channels: int,
363
- out_channels: int,
364
- ) -> None:
365
- super().__init__()
366
- self.in_channels = in_channels
367
- self.out_channels = out_channels
368
- self.deconv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size=4, stride=2, padding=1)
369
-
370
- def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
371
- r"""The forward method of the `UpSample` class."""
372
- x = torch.relu(x)
373
- x = self.deconv(x)
374
- return x
375
-
376
-
377
- class MaskConditionEncoder(nn.Module):
378
- """
379
- used in AsymmetricAutoencoderKL
380
- """
381
-
382
- def __init__(
383
- self,
384
- in_ch: int,
385
- out_ch: int = 192,
386
- res_ch: int = 768,
387
- stride: int = 16,
388
- ) -> None:
389
- super().__init__()
390
-
391
- channels = []
392
- while stride > 1:
393
- stride = stride // 2
394
- in_ch_ = out_ch * 2
395
- if out_ch > res_ch:
396
- out_ch = res_ch
397
- if stride == 1:
398
- in_ch_ = res_ch
399
- channels.append((in_ch_, out_ch))
400
- out_ch *= 2
401
-
402
- out_channels = []
403
- for _in_ch, _out_ch in channels:
404
- out_channels.append(_out_ch)
405
- out_channels.append(channels[-1][0])
406
-
407
- layers = []
408
- in_ch_ = in_ch
409
- for l in range(len(out_channels)):
410
- out_ch_ = out_channels[l]
411
- if l == 0 or l == 1:
412
- layers.append(nn.Conv2d(in_ch_, out_ch_, kernel_size=3, stride=1, padding=1))
413
- else:
414
- layers.append(nn.Conv2d(in_ch_, out_ch_, kernel_size=4, stride=2, padding=1))
415
- in_ch_ = out_ch_
416
-
417
- self.layers = nn.Sequential(*layers)
418
-
419
- def forward(self, x: torch.FloatTensor, mask=None) -> torch.FloatTensor:
420
- r"""The forward method of the `MaskConditionEncoder` class."""
421
- out = {}
422
- for l in range(len(self.layers)):
423
- layer = self.layers[l]
424
- x = layer(x)
425
- out[str(tuple(x.shape))] = x
426
- x = torch.relu(x)
427
- return out
428
-
429
-
430
- class MaskConditionDecoder(nn.Module):
431
- r"""The `MaskConditionDecoder` should be used in combination with [`AsymmetricAutoencoderKL`] to enhance the model's
432
- decoder with a conditioner on the mask and masked image.
433
-
434
- Args:
435
- in_channels (`int`, *optional*, defaults to 3):
436
- The number of input channels.
437
- out_channels (`int`, *optional*, defaults to 3):
438
- The number of output channels.
439
- up_block_types (`Tuple[str, ...]`, *optional*, defaults to `("UpDecoderBlock2D",)`):
440
- The types of up blocks to use. See `~diffusers.models.unet_2d_blocks.get_up_block` for available options.
441
- block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
442
- The number of output channels for each block.
443
- layers_per_block (`int`, *optional*, defaults to 2):
444
- The number of layers per block.
445
- norm_num_groups (`int`, *optional*, defaults to 32):
446
- The number of groups for normalization.
447
- act_fn (`str`, *optional*, defaults to `"silu"`):
448
- The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
449
- norm_type (`str`, *optional*, defaults to `"group"`):
450
- The normalization type to use. Can be either `"group"` or `"spatial"`.
451
- """
452
-
453
- def __init__(
454
- self,
455
- in_channels: int = 3,
456
- out_channels: int = 3,
457
- up_block_types: Tuple[str, ...] = ("UpDecoderBlock2D",),
458
- block_out_channels: Tuple[int, ...] = (64,),
459
- layers_per_block: int = 2,
460
- norm_num_groups: int = 32,
461
- act_fn: str = "silu",
462
- norm_type: str = "group", # group, spatial
463
- ):
464
- super().__init__()
465
- self.layers_per_block = layers_per_block
466
-
467
- self.conv_in = nn.Conv2d(
468
- in_channels,
469
- block_out_channels[-1],
470
- kernel_size=3,
471
- stride=1,
472
- padding=1,
473
- )
474
-
475
- self.up_blocks = nn.ModuleList([])
476
-
477
- temb_channels = in_channels if norm_type == "spatial" else None
478
-
479
- # mid
480
- self.mid_block = UNetMidBlock2D(
481
- in_channels=block_out_channels[-1],
482
- resnet_eps=1e-6,
483
- resnet_act_fn=act_fn,
484
- output_scale_factor=1,
485
- resnet_time_scale_shift="default" if norm_type == "group" else norm_type,
486
- attention_head_dim=block_out_channels[-1],
487
- resnet_groups=norm_num_groups,
488
- temb_channels=temb_channels,
489
- )
490
-
491
- # up
492
- reversed_block_out_channels = list(reversed(block_out_channels))
493
- output_channel = reversed_block_out_channels[0]
494
- for i, up_block_type in enumerate(up_block_types):
495
- prev_output_channel = output_channel
496
- output_channel = reversed_block_out_channels[i]
497
-
498
- is_final_block = i == len(block_out_channels) - 1
499
-
500
- up_block = get_up_block(
501
- up_block_type,
502
- num_layers=self.layers_per_block + 1,
503
- in_channels=prev_output_channel,
504
- out_channels=output_channel,
505
- prev_output_channel=None,
506
- add_upsample=not is_final_block,
507
- resnet_eps=1e-6,
508
- resnet_act_fn=act_fn,
509
- resnet_groups=norm_num_groups,
510
- attention_head_dim=output_channel,
511
- temb_channels=temb_channels,
512
- resnet_time_scale_shift=norm_type,
513
- )
514
- self.up_blocks.append(up_block)
515
- prev_output_channel = output_channel
516
-
517
- # condition encoder
518
- self.condition_encoder = MaskConditionEncoder(
519
- in_ch=out_channels,
520
- out_ch=block_out_channels[0],
521
- res_ch=block_out_channels[-1],
522
- )
523
-
524
- # out
525
- if norm_type == "spatial":
526
- self.conv_norm_out = SpatialNorm(block_out_channels[0], temb_channels)
527
- else:
528
- self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6)
529
- self.conv_act = nn.SiLU()
530
- self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, 3, padding=1)
531
-
532
- self.gradient_checkpointing = False
533
-
534
- def forward(
535
- self,
536
- z: torch.FloatTensor,
537
- image: Optional[torch.FloatTensor] = None,
538
- mask: Optional[torch.FloatTensor] = None,
539
- latent_embeds: Optional[torch.FloatTensor] = None,
540
- ) -> torch.FloatTensor:
541
- r"""The forward method of the `MaskConditionDecoder` class."""
542
- sample = z
543
- sample = self.conv_in(sample)
544
-
545
- upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
546
- if self.training and self.gradient_checkpointing:
547
-
548
- def create_custom_forward(module):
549
- def custom_forward(*inputs):
550
- return module(*inputs)
551
-
552
- return custom_forward
553
-
554
- if is_torch_version(">=", "1.11.0"):
555
- # middle
556
- sample = torch.utils.checkpoint.checkpoint(
557
- create_custom_forward(self.mid_block),
558
- sample,
559
- latent_embeds,
560
- use_reentrant=False,
561
- )
562
- sample = sample.to(upscale_dtype)
563
-
564
- # condition encoder
565
- if image is not None and mask is not None:
566
- masked_image = (1 - mask) * image
567
- im_x = torch.utils.checkpoint.checkpoint(
568
- create_custom_forward(self.condition_encoder),
569
- masked_image,
570
- mask,
571
- use_reentrant=False,
572
- )
573
-
574
- # up
575
- for up_block in self.up_blocks:
576
- if image is not None and mask is not None:
577
- sample_ = im_x[str(tuple(sample.shape))]
578
- mask_ = nn.functional.interpolate(mask, size=sample.shape[-2:], mode="nearest")
579
- sample = sample * mask_ + sample_ * (1 - mask_)
580
- sample = torch.utils.checkpoint.checkpoint(
581
- create_custom_forward(up_block),
582
- sample,
583
- latent_embeds,
584
- use_reentrant=False,
585
- )
586
- if image is not None and mask is not None:
587
- sample = sample * mask + im_x[str(tuple(sample.shape))] * (1 - mask)
588
- else:
589
- # middle
590
- sample = torch.utils.checkpoint.checkpoint(
591
- create_custom_forward(self.mid_block), sample, latent_embeds
592
- )
593
- sample = sample.to(upscale_dtype)
594
-
595
- # condition encoder
596
- if image is not None and mask is not None:
597
- masked_image = (1 - mask) * image
598
- im_x = torch.utils.checkpoint.checkpoint(
599
- create_custom_forward(self.condition_encoder),
600
- masked_image,
601
- mask,
602
- )
603
-
604
- # up
605
- for up_block in self.up_blocks:
606
- if image is not None and mask is not None:
607
- sample_ = im_x[str(tuple(sample.shape))]
608
- mask_ = nn.functional.interpolate(mask, size=sample.shape[-2:], mode="nearest")
609
- sample = sample * mask_ + sample_ * (1 - mask_)
610
- sample = torch.utils.checkpoint.checkpoint(create_custom_forward(up_block), sample, latent_embeds)
611
- if image is not None and mask is not None:
612
- sample = sample * mask + im_x[str(tuple(sample.shape))] * (1 - mask)
613
- else:
614
- # middle
615
- sample = self.mid_block(sample, latent_embeds)
616
- sample = sample.to(upscale_dtype)
617
-
618
- # condition encoder
619
- if image is not None and mask is not None:
620
- masked_image = (1 - mask) * image
621
- im_x = self.condition_encoder(masked_image, mask)
622
-
623
- # up
624
- for up_block in self.up_blocks:
625
- if image is not None and mask is not None:
626
- sample_ = im_x[str(tuple(sample.shape))]
627
- mask_ = nn.functional.interpolate(mask, size=sample.shape[-2:], mode="nearest")
628
- sample = sample * mask_ + sample_ * (1 - mask_)
629
- sample = up_block(sample, latent_embeds)
630
- if image is not None and mask is not None:
631
- sample = sample * mask + im_x[str(tuple(sample.shape))] * (1 - mask)
632
-
633
- # post-process
634
- if latent_embeds is None:
635
- sample = self.conv_norm_out(sample)
636
- else:
637
- sample = self.conv_norm_out(sample, latent_embeds)
638
- sample = self.conv_act(sample)
639
- sample = self.conv_out(sample)
640
-
641
- return sample
642
-
643
-
644
- class VectorQuantizer(nn.Module):
645
- """
646
- Improved version over VectorQuantizer, can be used as a drop-in replacement. Mostly avoids costly matrix
647
- multiplications and allows for post-hoc remapping of indices.
648
- """
649
-
650
- # NOTE: due to a bug the beta term was applied to the wrong term. for
651
- # backwards compatibility we use the buggy version by default, but you can
652
- # specify legacy=False to fix it.
653
- def __init__(
654
- self,
655
- n_e: int,
656
- vq_embed_dim: int,
657
- beta: float,
658
- remap=None,
659
- unknown_index: str = "random",
660
- sane_index_shape: bool = False,
661
- legacy: bool = True,
662
- ):
663
- super().__init__()
664
- self.n_e = n_e
665
- self.vq_embed_dim = vq_embed_dim
666
- self.beta = beta
667
- self.legacy = legacy
668
-
669
- self.embedding = nn.Embedding(self.n_e, self.vq_embed_dim)
670
- self.embedding.weight.data.uniform_(-1.0 / self.n_e, 1.0 / self.n_e)
671
-
672
- self.remap = remap
673
- if self.remap is not None:
674
- self.register_buffer("used", torch.tensor(np.load(self.remap)))
675
- self.used: torch.Tensor
676
- self.re_embed = self.used.shape[0]
677
- self.unknown_index = unknown_index # "random" or "extra" or integer
678
- if self.unknown_index == "extra":
679
- self.unknown_index = self.re_embed
680
- self.re_embed = self.re_embed + 1
681
- print(
682
- f"Remapping {self.n_e} indices to {self.re_embed} indices. "
683
- f"Using {self.unknown_index} for unknown indices."
684
- )
685
- else:
686
- self.re_embed = n_e
687
-
688
- self.sane_index_shape = sane_index_shape
689
-
690
- def remap_to_used(self, inds: torch.LongTensor) -> torch.LongTensor:
691
- ishape = inds.shape
692
- assert len(ishape) > 1
693
- inds = inds.reshape(ishape[0], -1)
694
- used = self.used.to(inds)
695
- match = (inds[:, :, None] == used[None, None, ...]).long()
696
- new = match.argmax(-1)
697
- unknown = match.sum(2) < 1
698
- if self.unknown_index == "random":
699
- new[unknown] = torch.randint(0, self.re_embed, size=new[unknown].shape).to(device=new.device)
700
- else:
701
- new[unknown] = self.unknown_index
702
- return new.reshape(ishape)
703
-
704
- def unmap_to_all(self, inds: torch.LongTensor) -> torch.LongTensor:
705
- ishape = inds.shape
706
- assert len(ishape) > 1
707
- inds = inds.reshape(ishape[0], -1)
708
- used = self.used.to(inds)
709
- if self.re_embed > self.used.shape[0]: # extra token
710
- inds[inds >= self.used.shape[0]] = 0 # simply set to zero
711
- back = torch.gather(used[None, :][inds.shape[0] * [0], :], 1, inds)
712
- return back.reshape(ishape)
713
-
714
- def forward(self, z: torch.FloatTensor) -> Tuple[torch.FloatTensor, torch.FloatTensor, Tuple]:
715
- # reshape z -> (batch, height, width, channel) and flatten
716
- z = z.permute(0, 2, 3, 1).contiguous()
717
- z_flattened = z.view(-1, self.vq_embed_dim)
718
-
719
- # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
720
- min_encoding_indices = torch.argmin(torch.cdist(z_flattened, self.embedding.weight), dim=1)
721
-
722
- z_q = self.embedding(min_encoding_indices).view(z.shape)
723
- perplexity = None
724
- min_encodings = None
725
-
726
- # compute loss for embedding
727
- if not self.legacy:
728
- loss = self.beta * torch.mean((z_q.detach() - z) ** 2) + torch.mean((z_q - z.detach()) ** 2)
729
- else:
730
- loss = torch.mean((z_q.detach() - z) ** 2) + self.beta * torch.mean((z_q - z.detach()) ** 2)
731
-
732
- # preserve gradients
733
- z_q: torch.FloatTensor = z + (z_q - z).detach()
734
-
735
- # reshape back to match original input shape
736
- z_q = z_q.permute(0, 3, 1, 2).contiguous()
737
-
738
- if self.remap is not None:
739
- min_encoding_indices = min_encoding_indices.reshape(z.shape[0], -1) # add batch axis
740
- min_encoding_indices = self.remap_to_used(min_encoding_indices)
741
- min_encoding_indices = min_encoding_indices.reshape(-1, 1) # flatten
742
-
743
- if self.sane_index_shape:
744
- min_encoding_indices = min_encoding_indices.reshape(z_q.shape[0], z_q.shape[2], z_q.shape[3])
745
-
746
- return z_q, loss, (perplexity, min_encodings, min_encoding_indices)
747
-
748
- def get_codebook_entry(self, indices: torch.LongTensor, shape: Tuple[int, ...]) -> torch.FloatTensor:
749
- # shape specifying (batch, height, width, channel)
750
- if self.remap is not None:
751
- indices = indices.reshape(shape[0], -1) # add batch axis
752
- indices = self.unmap_to_all(indices)
753
- indices = indices.reshape(-1) # flatten again
754
-
755
- # get quantized latent vectors
756
- z_q: torch.FloatTensor = self.embedding(indices)
757
-
758
- if shape is not None:
759
- z_q = z_q.view(shape)
760
- # reshape back to match original input shape
761
- z_q = z_q.permute(0, 3, 1, 2).contiguous()
762
-
763
- return z_q
764
-
765
-
766
- class DiagonalGaussianDistribution(object):
767
- def __init__(self, parameters: torch.Tensor, deterministic: bool = False):
768
- self.parameters = parameters
769
- self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
770
- self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
771
- self.deterministic = deterministic
772
- self.std = torch.exp(0.5 * self.logvar)
773
- self.var = torch.exp(self.logvar)
774
- if self.deterministic:
775
- self.var = self.std = torch.zeros_like(
776
- self.mean, device=self.parameters.device, dtype=self.parameters.dtype
777
- )
778
-
779
- def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:
780
- # make sure sample is on the same device as the parameters and has same dtype
781
- sample = randn_tensor(
782
- self.mean.shape,
783
- generator=generator,
784
- device=self.parameters.device,
785
- dtype=self.parameters.dtype,
786
- )
787
- x = self.mean + self.std * sample
788
- return x
789
-
790
- def kl(self, other: "DiagonalGaussianDistribution" = None) -> torch.Tensor:
791
- if self.deterministic:
792
- return torch.Tensor([0.0])
793
- else:
794
- if other is None:
795
- return 0.5 * torch.sum(
796
- torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,
797
- dim=[1, 2, 3],
798
- )
799
- else:
800
- return 0.5 * torch.sum(
801
- torch.pow(self.mean - other.mean, 2) / other.var
802
- + self.var / other.var
803
- - 1.0
804
- - self.logvar
805
- + other.logvar,
806
- dim=[1, 2, 3],
807
- )
808
-
809
- def nll(self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]) -> torch.Tensor:
810
- if self.deterministic:
811
- return torch.Tensor([0.0])
812
- logtwopi = np.log(2.0 * np.pi)
813
- return 0.5 * torch.sum(
814
- logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
815
- dim=dims,
816
- )
817
-
818
- def mode(self) -> torch.Tensor:
819
- return self.mean
820
-
821
-
822
- class EncoderTiny(nn.Module):
823
- r"""
824
- The `EncoderTiny` layer is a simpler version of the `Encoder` layer.
825
-
826
- Args:
827
- in_channels (`int`):
828
- The number of input channels.
829
- out_channels (`int`):
830
- The number of output channels.
831
- num_blocks (`Tuple[int, ...]`):
832
- Each value of the tuple represents a Conv2d layer followed by `value` number of `AutoencoderTinyBlock`'s to
833
- use.
834
- block_out_channels (`Tuple[int, ...]`):
835
- The number of output channels for each block.
836
- act_fn (`str`):
837
- The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
838
- """
839
-
840
- def __init__(
841
- self,
842
- in_channels: int,
843
- out_channels: int,
844
- num_blocks: Tuple[int, ...],
845
- block_out_channels: Tuple[int, ...],
846
- act_fn: str,
847
- ):
848
- super().__init__()
849
-
850
- layers = []
851
- for i, num_block in enumerate(num_blocks):
852
- num_channels = block_out_channels[i]
853
-
854
- if i == 0:
855
- layers.append(nn.Conv2d(in_channels, num_channels, kernel_size=3, padding=1))
856
- else:
857
- layers.append(
858
- nn.Conv2d(
859
- num_channels,
860
- num_channels,
861
- kernel_size=3,
862
- padding=1,
863
- stride=2,
864
- bias=False,
865
- )
866
- )
867
-
868
- for _ in range(num_block):
869
- layers.append(AutoencoderTinyBlock(num_channels, num_channels, act_fn))
870
-
871
- layers.append(nn.Conv2d(block_out_channels[-1], out_channels, kernel_size=3, padding=1))
872
-
873
- self.layers = nn.Sequential(*layers)
874
- self.gradient_checkpointing = False
875
-
876
- def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
877
- r"""The forward method of the `EncoderTiny` class."""
878
- if self.training and self.gradient_checkpointing:
879
-
880
- def create_custom_forward(module):
881
- def custom_forward(*inputs):
882
- return module(*inputs)
883
-
884
- return custom_forward
885
-
886
- if is_torch_version(">=", "1.11.0"):
887
- x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x, use_reentrant=False)
888
- else:
889
- x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x)
890
-
891
- else:
892
- # scale image from [-1, 1] to [0, 1] to match TAESD convention
893
- x = self.layers(x.add(1).div(2))
894
-
895
- return x
896
-
897
-
898
- class DecoderTiny(nn.Module):
899
- r"""
900
- The `DecoderTiny` layer is a simpler version of the `Decoder` layer.
901
-
902
- Args:
903
- in_channels (`int`):
904
- The number of input channels.
905
- out_channels (`int`):
906
- The number of output channels.
907
- num_blocks (`Tuple[int, ...]`):
908
- Each value of the tuple represents a Conv2d layer followed by `value` number of `AutoencoderTinyBlock`'s to
909
- use.
910
- block_out_channels (`Tuple[int, ...]`):
911
- The number of output channels for each block.
912
- upsampling_scaling_factor (`int`):
913
- The scaling factor to use for upsampling.
914
- act_fn (`str`):
915
- The activation function to use. See `~diffusers.models.activations.get_activation` for available options.
916
- """
917
-
918
- def __init__(
919
- self,
920
- in_channels: int,
921
- out_channels: int,
922
- num_blocks: Tuple[int, ...],
923
- block_out_channels: Tuple[int, ...],
924
- upsampling_scaling_factor: int,
925
- act_fn: str,
926
- upsample_fn: str,
927
- ):
928
- super().__init__()
929
-
930
- layers = [
931
- nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=1),
932
- get_activation(act_fn),
933
- ]
934
-
935
- for i, num_block in enumerate(num_blocks):
936
- is_final_block = i == (len(num_blocks) - 1)
937
- num_channels = block_out_channels[i]
938
-
939
- for _ in range(num_block):
940
- layers.append(AutoencoderTinyBlock(num_channels, num_channels, act_fn))
941
-
942
- if not is_final_block:
943
- layers.append(nn.Upsample(scale_factor=upsampling_scaling_factor, mode=upsample_fn))
944
-
945
- conv_out_channel = num_channels if not is_final_block else out_channels
946
- layers.append(
947
- nn.Conv2d(
948
- num_channels,
949
- conv_out_channel,
950
- kernel_size=3,
951
- padding=1,
952
- bias=is_final_block,
953
- )
954
- )
955
-
956
- self.layers = nn.Sequential(*layers)
957
- self.gradient_checkpointing = False
958
-
959
- def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
960
- r"""The forward method of the `DecoderTiny` class."""
961
- # Clamp.
962
- x = torch.tanh(x / 3) * 3
963
-
964
- if self.training and self.gradient_checkpointing:
965
-
966
- def create_custom_forward(module):
967
- def custom_forward(*inputs):
968
- return module(*inputs)
969
-
970
- return custom_forward
971
-
972
- if is_torch_version(">=", "1.11.0"):
973
- x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x, use_reentrant=False)
974
- else:
975
- x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.layers), x)
976
-
977
- else:
978
- x = self.layers(x)
979
-
980
- # scale image from [0, 1] to [-1, 1] to match diffusers convention
981
- return x.mul(2).sub(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/controlnet.py DELETED
@@ -1,907 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from 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 .unets.unet_2d_blocks import (
34
- CrossAttnDownBlock2D,
35
- DownBlock2D,
36
- UNetMidBlock2D,
37
- UNetMidBlock2DCrossAttn,
38
- get_down_block,
39
- )
40
- from .unets.unet_2d_condition import UNet2DConditionModel
41
-
42
-
43
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
44
-
45
-
46
- @dataclass
47
- class ControlNetOutput(BaseOutput):
48
- """
49
- The output of [`ControlNetModel`].
50
-
51
- Args:
52
- down_block_res_samples (`tuple[torch.Tensor]`):
53
- A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
54
- be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
55
- used to condition the original UNet's downsampling activations.
56
- mid_down_block_re_sample (`torch.Tensor`):
57
- The activation of the midde block (the lowest sample resolution). Each tensor should be of shape
58
- `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
59
- Output can be used to condition the original UNet's middle block activation.
60
- """
61
-
62
- down_block_res_samples: Tuple[torch.Tensor]
63
- mid_block_res_sample: torch.Tensor
64
-
65
-
66
- class ControlNetConditioningEmbedding(nn.Module):
67
- """
68
- Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
69
- [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
70
- training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
71
- convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
72
- (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
73
- model) to encode image-space conditions ... into feature maps ..."
74
- """
75
-
76
- def __init__(
77
- self,
78
- conditioning_embedding_channels: int,
79
- conditioning_channels: int = 3,
80
- block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
81
- ):
82
- super().__init__()
83
-
84
- self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
85
-
86
- self.blocks = nn.ModuleList([])
87
-
88
- for i in range(len(block_out_channels) - 1):
89
- channel_in = block_out_channels[i]
90
- channel_out = block_out_channels[i + 1]
91
- self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
92
- self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
93
-
94
- self.conv_out = zero_module(
95
- nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
96
- )
97
-
98
- def forward(self, conditioning):
99
- embedding = self.conv_in(conditioning)
100
- embedding = F.silu(embedding)
101
-
102
- for block in self.blocks:
103
- embedding = block(embedding)
104
- embedding = F.silu(embedding)
105
-
106
- embedding = self.conv_out(embedding)
107
-
108
- return embedding
109
-
110
-
111
- class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalControlNetMixin):
112
- """
113
- A ControlNet model.
114
-
115
- Args:
116
- in_channels (`int`, defaults to 4):
117
- The number of channels in the input sample.
118
- flip_sin_to_cos (`bool`, defaults to `True`):
119
- Whether to flip the sin to cos in the time embedding.
120
- freq_shift (`int`, defaults to 0):
121
- The frequency shift to apply to the time embedding.
122
- down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
123
- The tuple of downsample blocks to use.
124
- only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
125
- block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
126
- The tuple of output channels for each block.
127
- layers_per_block (`int`, defaults to 2):
128
- The number of layers per block.
129
- downsample_padding (`int`, defaults to 1):
130
- The padding to use for the downsampling convolution.
131
- mid_block_scale_factor (`float`, defaults to 1):
132
- The scale factor to use for the mid block.
133
- act_fn (`str`, defaults to "silu"):
134
- The activation function to use.
135
- norm_num_groups (`int`, *optional*, defaults to 32):
136
- The number of groups to use for the normalization. If None, normalization and activation layers is skipped
137
- in post-processing.
138
- norm_eps (`float`, defaults to 1e-5):
139
- The epsilon to use for the normalization.
140
- cross_attention_dim (`int`, defaults to 1280):
141
- The dimension of the cross attention features.
142
- transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
143
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
144
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
145
- [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
146
- encoder_hid_dim (`int`, *optional*, defaults to None):
147
- If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
148
- dimension to `cross_attention_dim`.
149
- encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
150
- If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
151
- embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
152
- attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
153
- The dimension of the attention heads.
154
- use_linear_projection (`bool`, defaults to `False`):
155
- class_embed_type (`str`, *optional*, defaults to `None`):
156
- The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
157
- `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
158
- addition_embed_type (`str`, *optional*, defaults to `None`):
159
- Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
160
- "text". "text" will use the `TextTimeEmbedding` layer.
161
- num_class_embeds (`int`, *optional*, defaults to 0):
162
- Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
163
- class conditioning with `class_embed_type` equal to `None`.
164
- upcast_attention (`bool`, defaults to `False`):
165
- resnet_time_scale_shift (`str`, defaults to `"default"`):
166
- Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
167
- projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
168
- The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
169
- `class_embed_type="projection"`.
170
- controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
171
- The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
172
- conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
173
- The tuple of output channel for each block in the `conditioning_embedding` layer.
174
- global_pool_conditions (`bool`, defaults to `False`):
175
- TODO(Patrick) - unused parameter.
176
- addition_embed_type_num_heads (`int`, defaults to 64):
177
- The number of heads to use for the `TextTimeEmbedding` layer.
178
- """
179
-
180
- _supports_gradient_checkpointing = True
181
-
182
- @register_to_config
183
- def __init__(
184
- self,
185
- in_channels: int = 4,
186
- conditioning_channels: int = 3,
187
- flip_sin_to_cos: bool = True,
188
- freq_shift: int = 0,
189
- down_block_types: Tuple[str, ...] = (
190
- "CrossAttnDownBlock2D",
191
- "CrossAttnDownBlock2D",
192
- "CrossAttnDownBlock2D",
193
- "DownBlock2D",
194
- ),
195
- mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
196
- only_cross_attention: Union[bool, Tuple[bool]] = False,
197
- block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
198
- layers_per_block: int = 2,
199
- downsample_padding: int = 1,
200
- mid_block_scale_factor: float = 1,
201
- act_fn: str = "silu",
202
- norm_num_groups: Optional[int] = 32,
203
- norm_eps: float = 1e-5,
204
- cross_attention_dim: int = 1280,
205
- transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
206
- encoder_hid_dim: Optional[int] = None,
207
- encoder_hid_dim_type: Optional[str] = None,
208
- attention_head_dim: Union[int, Tuple[int, ...]] = 8,
209
- num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
210
- use_linear_projection: bool = False,
211
- class_embed_type: Optional[str] = None,
212
- addition_embed_type: Optional[str] = None,
213
- addition_time_embed_dim: Optional[int] = None,
214
- num_class_embeds: Optional[int] = None,
215
- upcast_attention: bool = False,
216
- resnet_time_scale_shift: str = "default",
217
- projection_class_embeddings_input_dim: Optional[int] = None,
218
- controlnet_conditioning_channel_order: str = "rgb",
219
- conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
220
- global_pool_conditions: bool = False,
221
- addition_embed_type_num_heads: int = 64,
222
- ):
223
- super().__init__()
224
-
225
- # If `num_attention_heads` is not defined (which is the case for most models)
226
- # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
227
- # The reason for this behavior is to correct for incorrectly named variables that were introduced
228
- # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
229
- # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
230
- # which is why we correct for the naming here.
231
- num_attention_heads = num_attention_heads or attention_head_dim
232
-
233
- # Check inputs
234
- if len(block_out_channels) != len(down_block_types):
235
- raise ValueError(
236
- 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}."
237
- )
238
-
239
- if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
240
- raise ValueError(
241
- 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}."
242
- )
243
-
244
- if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
245
- raise ValueError(
246
- 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}."
247
- )
248
-
249
- if isinstance(transformer_layers_per_block, int):
250
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
251
-
252
- # input
253
- conv_in_kernel = 3
254
- conv_in_padding = (conv_in_kernel - 1) // 2
255
- self.conv_in = nn.Conv2d(
256
- in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
257
- )
258
-
259
- # time
260
- time_embed_dim = block_out_channels[0] * 4
261
- self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
262
- timestep_input_dim = block_out_channels[0]
263
- self.time_embedding = TimestepEmbedding(
264
- timestep_input_dim,
265
- time_embed_dim,
266
- act_fn=act_fn,
267
- )
268
-
269
- if encoder_hid_dim_type is None and encoder_hid_dim is not None:
270
- encoder_hid_dim_type = "text_proj"
271
- self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
272
- logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
273
-
274
- if encoder_hid_dim is None and encoder_hid_dim_type is not None:
275
- raise ValueError(
276
- f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
277
- )
278
-
279
- if encoder_hid_dim_type == "text_proj":
280
- self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
281
- elif encoder_hid_dim_type == "text_image_proj":
282
- # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
283
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
284
- # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
285
- self.encoder_hid_proj = TextImageProjection(
286
- text_embed_dim=encoder_hid_dim,
287
- image_embed_dim=cross_attention_dim,
288
- cross_attention_dim=cross_attention_dim,
289
- )
290
-
291
- elif encoder_hid_dim_type is not None:
292
- raise ValueError(
293
- f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
294
- )
295
- else:
296
- self.encoder_hid_proj = None
297
-
298
- # class embedding
299
- if class_embed_type is None and num_class_embeds is not None:
300
- self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
301
- elif class_embed_type == "timestep":
302
- self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
303
- elif class_embed_type == "identity":
304
- self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
305
- elif class_embed_type == "projection":
306
- if projection_class_embeddings_input_dim is None:
307
- raise ValueError(
308
- "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
309
- )
310
- # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
311
- # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
312
- # 2. it projects from an arbitrary input dimension.
313
- #
314
- # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
315
- # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
316
- # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
317
- self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
318
- else:
319
- self.class_embedding = None
320
-
321
- if addition_embed_type == "text":
322
- if encoder_hid_dim is not None:
323
- text_time_embedding_from_dim = encoder_hid_dim
324
- else:
325
- text_time_embedding_from_dim = cross_attention_dim
326
-
327
- self.add_embedding = TextTimeEmbedding(
328
- text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
329
- )
330
- elif addition_embed_type == "text_image":
331
- # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
332
- # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
333
- # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
334
- self.add_embedding = TextImageTimeEmbedding(
335
- text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
336
- )
337
- elif addition_embed_type == "text_time":
338
- self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
339
- self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
340
-
341
- elif addition_embed_type is not None:
342
- raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
343
-
344
- # control net conditioning embedding
345
- self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
346
- conditioning_embedding_channels=block_out_channels[0],
347
- block_out_channels=conditioning_embedding_out_channels,
348
- conditioning_channels=conditioning_channels,
349
- )
350
-
351
- self.down_blocks = nn.ModuleList([])
352
- self.controlnet_down_blocks = nn.ModuleList([])
353
-
354
- if isinstance(only_cross_attention, bool):
355
- only_cross_attention = [only_cross_attention] * len(down_block_types)
356
-
357
- if isinstance(attention_head_dim, int):
358
- attention_head_dim = (attention_head_dim,) * len(down_block_types)
359
-
360
- if isinstance(num_attention_heads, int):
361
- num_attention_heads = (num_attention_heads,) * len(down_block_types)
362
-
363
- # down
364
- output_channel = block_out_channels[0]
365
-
366
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
367
- controlnet_block = zero_module(controlnet_block)
368
- self.controlnet_down_blocks.append(controlnet_block)
369
-
370
- for i, down_block_type in enumerate(down_block_types):
371
- input_channel = output_channel
372
- output_channel = block_out_channels[i]
373
- is_final_block = i == len(block_out_channels) - 1
374
-
375
- down_block = get_down_block(
376
- down_block_type,
377
- num_layers=layers_per_block,
378
- transformer_layers_per_block=transformer_layers_per_block[i],
379
- in_channels=input_channel,
380
- out_channels=output_channel,
381
- temb_channels=time_embed_dim,
382
- add_downsample=not is_final_block,
383
- resnet_eps=norm_eps,
384
- resnet_act_fn=act_fn,
385
- resnet_groups=norm_num_groups,
386
- cross_attention_dim=cross_attention_dim,
387
- num_attention_heads=num_attention_heads[i],
388
- attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
389
- downsample_padding=downsample_padding,
390
- use_linear_projection=use_linear_projection,
391
- only_cross_attention=only_cross_attention[i],
392
- upcast_attention=upcast_attention,
393
- resnet_time_scale_shift=resnet_time_scale_shift,
394
- )
395
- self.down_blocks.append(down_block)
396
-
397
- for _ in range(layers_per_block):
398
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
399
- controlnet_block = zero_module(controlnet_block)
400
- self.controlnet_down_blocks.append(controlnet_block)
401
-
402
- if not is_final_block:
403
- controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
404
- controlnet_block = zero_module(controlnet_block)
405
- self.controlnet_down_blocks.append(controlnet_block)
406
-
407
- # mid
408
- mid_block_channel = block_out_channels[-1]
409
-
410
- controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
411
- controlnet_block = zero_module(controlnet_block)
412
- self.controlnet_mid_block = controlnet_block
413
-
414
- if mid_block_type == "UNetMidBlock2DCrossAttn":
415
- self.mid_block = UNetMidBlock2DCrossAttn(
416
- transformer_layers_per_block=transformer_layers_per_block[-1],
417
- in_channels=mid_block_channel,
418
- temb_channels=time_embed_dim,
419
- resnet_eps=norm_eps,
420
- resnet_act_fn=act_fn,
421
- output_scale_factor=mid_block_scale_factor,
422
- resnet_time_scale_shift=resnet_time_scale_shift,
423
- cross_attention_dim=cross_attention_dim,
424
- num_attention_heads=num_attention_heads[-1],
425
- resnet_groups=norm_num_groups,
426
- use_linear_projection=use_linear_projection,
427
- upcast_attention=upcast_attention,
428
- )
429
- elif mid_block_type == "UNetMidBlock2D":
430
- self.mid_block = UNetMidBlock2D(
431
- in_channels=block_out_channels[-1],
432
- temb_channels=time_embed_dim,
433
- num_layers=0,
434
- resnet_eps=norm_eps,
435
- resnet_act_fn=act_fn,
436
- output_scale_factor=mid_block_scale_factor,
437
- resnet_groups=norm_num_groups,
438
- resnet_time_scale_shift=resnet_time_scale_shift,
439
- add_attention=False,
440
- )
441
- else:
442
- raise ValueError(f"unknown mid_block_type : {mid_block_type}")
443
-
444
- @classmethod
445
- def from_unet(
446
- cls,
447
- unet: UNet2DConditionModel,
448
- controlnet_conditioning_channel_order: str = "rgb",
449
- conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
450
- load_weights_from_unet: bool = True,
451
- conditioning_channels: int = 3,
452
- ):
453
- r"""
454
- Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
455
-
456
- Parameters:
457
- unet (`UNet2DConditionModel`):
458
- The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
459
- where applicable.
460
- """
461
- transformer_layers_per_block = (
462
- unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
463
- )
464
- encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
465
- encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
466
- addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
467
- addition_time_embed_dim = (
468
- unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
469
- )
470
-
471
- controlnet = cls(
472
- encoder_hid_dim=encoder_hid_dim,
473
- encoder_hid_dim_type=encoder_hid_dim_type,
474
- addition_embed_type=addition_embed_type,
475
- addition_time_embed_dim=addition_time_embed_dim,
476
- transformer_layers_per_block=transformer_layers_per_block,
477
- in_channels=unet.config.in_channels,
478
- flip_sin_to_cos=unet.config.flip_sin_to_cos,
479
- freq_shift=unet.config.freq_shift,
480
- down_block_types=unet.config.down_block_types,
481
- only_cross_attention=unet.config.only_cross_attention,
482
- block_out_channels=unet.config.block_out_channels,
483
- layers_per_block=unet.config.layers_per_block,
484
- downsample_padding=unet.config.downsample_padding,
485
- mid_block_scale_factor=unet.config.mid_block_scale_factor,
486
- act_fn=unet.config.act_fn,
487
- norm_num_groups=unet.config.norm_num_groups,
488
- norm_eps=unet.config.norm_eps,
489
- cross_attention_dim=unet.config.cross_attention_dim,
490
- attention_head_dim=unet.config.attention_head_dim,
491
- num_attention_heads=unet.config.num_attention_heads,
492
- use_linear_projection=unet.config.use_linear_projection,
493
- class_embed_type=unet.config.class_embed_type,
494
- num_class_embeds=unet.config.num_class_embeds,
495
- upcast_attention=unet.config.upcast_attention,
496
- resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
497
- projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
498
- mid_block_type=unet.config.mid_block_type,
499
- controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
500
- conditioning_embedding_out_channels=conditioning_embedding_out_channels,
501
- conditioning_channels=conditioning_channels,
502
- )
503
-
504
- if load_weights_from_unet:
505
- controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
506
- controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
507
- controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
508
-
509
- if controlnet.class_embedding:
510
- controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
511
-
512
- if hasattr(controlnet, "add_embedding"):
513
- controlnet.add_embedding.load_state_dict(unet.add_embedding.state_dict())
514
-
515
- controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
516
- controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
517
-
518
- return controlnet
519
-
520
- @property
521
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
522
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
523
- r"""
524
- Returns:
525
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
526
- indexed by its weight name.
527
- """
528
- # set recursively
529
- processors = {}
530
-
531
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
532
- if hasattr(module, "get_processor"):
533
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
534
-
535
- for sub_name, child in module.named_children():
536
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
537
-
538
- return processors
539
-
540
- for name, module in self.named_children():
541
- fn_recursive_add_processors(name, module, processors)
542
-
543
- return processors
544
-
545
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
546
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
547
- r"""
548
- Sets the attention processor to use to compute attention.
549
-
550
- Parameters:
551
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
552
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
553
- for **all** `Attention` layers.
554
-
555
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
556
- processor. This is strongly recommended when setting trainable attention processors.
557
-
558
- """
559
- count = len(self.attn_processors.keys())
560
-
561
- if isinstance(processor, dict) and len(processor) != count:
562
- raise ValueError(
563
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
564
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
565
- )
566
-
567
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
568
- if hasattr(module, "set_processor"):
569
- if not isinstance(processor, dict):
570
- module.set_processor(processor)
571
- else:
572
- module.set_processor(processor.pop(f"{name}.processor"))
573
-
574
- for sub_name, child in module.named_children():
575
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
576
-
577
- for name, module in self.named_children():
578
- fn_recursive_attn_processor(name, module, processor)
579
-
580
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
581
- def set_default_attn_processor(self):
582
- """
583
- Disables custom attention processors and sets the default attention implementation.
584
- """
585
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
586
- processor = AttnAddedKVProcessor()
587
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
588
- processor = AttnProcessor()
589
- else:
590
- raise ValueError(
591
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
592
- )
593
-
594
- self.set_attn_processor(processor)
595
-
596
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
597
- def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
598
- r"""
599
- Enable sliced attention computation.
600
-
601
- When this option is enabled, the attention module splits the input tensor in slices to compute attention in
602
- several steps. This is useful for saving some memory in exchange for a small decrease in speed.
603
-
604
- Args:
605
- slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
606
- When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
607
- `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
608
- provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
609
- must be a multiple of `slice_size`.
610
- """
611
- sliceable_head_dims = []
612
-
613
- def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
614
- if hasattr(module, "set_attention_slice"):
615
- sliceable_head_dims.append(module.sliceable_head_dim)
616
-
617
- for child in module.children():
618
- fn_recursive_retrieve_sliceable_dims(child)
619
-
620
- # retrieve number of attention layers
621
- for module in self.children():
622
- fn_recursive_retrieve_sliceable_dims(module)
623
-
624
- num_sliceable_layers = len(sliceable_head_dims)
625
-
626
- if slice_size == "auto":
627
- # half the attention head size is usually a good trade-off between
628
- # speed and memory
629
- slice_size = [dim // 2 for dim in sliceable_head_dims]
630
- elif slice_size == "max":
631
- # make smallest slice possible
632
- slice_size = num_sliceable_layers * [1]
633
-
634
- slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
635
-
636
- if len(slice_size) != len(sliceable_head_dims):
637
- raise ValueError(
638
- f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
639
- f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
640
- )
641
-
642
- for i in range(len(slice_size)):
643
- size = slice_size[i]
644
- dim = sliceable_head_dims[i]
645
- if size is not None and size > dim:
646
- raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
647
-
648
- # Recursively walk through all the children.
649
- # Any children which exposes the set_attention_slice method
650
- # gets the message
651
- def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
652
- if hasattr(module, "set_attention_slice"):
653
- module.set_attention_slice(slice_size.pop())
654
-
655
- for child in module.children():
656
- fn_recursive_set_attention_slice(child, slice_size)
657
-
658
- reversed_slice_size = list(reversed(slice_size))
659
- for module in self.children():
660
- fn_recursive_set_attention_slice(module, reversed_slice_size)
661
-
662
- def process_encoder_hidden_states(
663
- self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]
664
- ) -> torch.Tensor:
665
- if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_proj":
666
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
667
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "text_image_proj":
668
- # Kandinsky 2.1 - style
669
- if "image_embeds" not in added_cond_kwargs:
670
- raise ValueError(
671
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
672
- )
673
-
674
- image_embeds = added_cond_kwargs.get("image_embeds")
675
- encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)
676
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "image_proj":
677
- # Kandinsky 2.2 - style
678
- if "image_embeds" not in added_cond_kwargs:
679
- raise ValueError(
680
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
681
- )
682
- image_embeds = added_cond_kwargs.get("image_embeds")
683
- encoder_hidden_states = self.encoder_hid_proj(image_embeds)
684
- elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == "ip_image_proj":
685
- if "image_embeds" not in added_cond_kwargs:
686
- raise ValueError(
687
- f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
688
- )
689
- image_embeds = added_cond_kwargs.get("image_embeds")
690
- image_embeds = self.encoder_hid_proj(image_embeds)
691
- encoder_hidden_states = (encoder_hidden_states, image_embeds)
692
- return encoder_hidden_states
693
-
694
- def _set_gradient_checkpointing(self, module, value: bool = False) -> None:
695
- if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
696
- module.gradient_checkpointing = value
697
-
698
- def forward(
699
- self,
700
- sample: torch.FloatTensor,
701
- timestep: Union[torch.Tensor, float, int],
702
- encoder_hidden_states: torch.Tensor,
703
- controlnet_cond: torch.FloatTensor,
704
- conditioning_scale: float = 1.0,
705
- class_labels: Optional[torch.Tensor] = None,
706
- timestep_cond: Optional[torch.Tensor] = None,
707
- attention_mask: Optional[torch.Tensor] = None,
708
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
709
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
710
- guess_mode: bool = False,
711
- return_dict: bool = True,
712
- ) -> Union[ControlNetOutput, Tuple[Tuple[torch.FloatTensor, ...], torch.FloatTensor]]:
713
- """
714
- The [`ControlNetModel`] forward method.
715
-
716
- Args:
717
- sample (`torch.FloatTensor`):
718
- The noisy input tensor.
719
- timestep (`Union[torch.Tensor, float, int]`):
720
- The number of timesteps to denoise an input.
721
- encoder_hidden_states (`torch.Tensor`):
722
- The encoder hidden states.
723
- controlnet_cond (`torch.FloatTensor`):
724
- The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
725
- conditioning_scale (`float`, defaults to `1.0`):
726
- The scale factor for ControlNet outputs.
727
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
728
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
729
- timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
730
- Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
731
- timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
732
- embeddings.
733
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
734
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
735
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
736
- negative values to the attention scores corresponding to "discard" tokens.
737
- added_cond_kwargs (`dict`):
738
- Additional conditions for the Stable Diffusion XL UNet.
739
- cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
740
- A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
741
- guess_mode (`bool`, defaults to `False`):
742
- In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
743
- you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
744
- return_dict (`bool`, defaults to `True`):
745
- Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
746
-
747
- Returns:
748
- [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
749
- If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
750
- returned where the first element is the sample tensor.
751
- """
752
- # check channel order
753
- channel_order = self.config.controlnet_conditioning_channel_order
754
-
755
- if channel_order == "rgb":
756
- # in rgb order by default
757
- ...
758
- elif channel_order == "bgr":
759
- controlnet_cond = torch.flip(controlnet_cond, dims=[1])
760
- else:
761
- raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
762
-
763
- # prepare attention_mask
764
- if attention_mask is not None:
765
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
766
- attention_mask = attention_mask.unsqueeze(1)
767
-
768
- # 1. time
769
- timesteps = timestep
770
- if not torch.is_tensor(timesteps):
771
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
772
- # This would be a good case for the `match` statement (Python 3.10+)
773
- is_mps = sample.device.type == "mps"
774
- if isinstance(timestep, float):
775
- dtype = torch.float32 if is_mps else torch.float64
776
- else:
777
- dtype = torch.int32 if is_mps else torch.int64
778
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
779
- elif len(timesteps.shape) == 0:
780
- timesteps = timesteps[None].to(sample.device)
781
-
782
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
783
- timesteps = timesteps.expand(sample.shape[0])
784
-
785
- t_emb = self.time_proj(timesteps)
786
-
787
- # timesteps does not contain any weights and will always return f32 tensors
788
- # but time_embedding might actually be running in fp16. so we need to cast here.
789
- # there might be better ways to encapsulate this.
790
- t_emb = t_emb.to(dtype=sample.dtype)
791
-
792
- emb = self.time_embedding(t_emb, timestep_cond)
793
- aug_emb = None
794
-
795
- if self.class_embedding is not None:
796
- if class_labels is None:
797
- raise ValueError("class_labels should be provided when num_class_embeds > 0")
798
-
799
- if self.config.class_embed_type == "timestep":
800
- class_labels = self.time_proj(class_labels)
801
-
802
- class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
803
- emb = emb + class_emb
804
-
805
- if self.config.addition_embed_type is not None:
806
- if self.config.addition_embed_type == "text":
807
- aug_emb = self.add_embedding(encoder_hidden_states)
808
-
809
- elif self.config.addition_embed_type == "text_time":
810
- if "text_embeds" not in added_cond_kwargs:
811
- raise ValueError(
812
- 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`"
813
- )
814
- text_embeds = added_cond_kwargs.get("text_embeds")
815
- if "time_ids" not in added_cond_kwargs:
816
- raise ValueError(
817
- 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`"
818
- )
819
- time_ids = added_cond_kwargs.get("time_ids")
820
- time_embeds = self.add_time_proj(time_ids.flatten())
821
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
822
-
823
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
824
- add_embeds = add_embeds.to(emb.dtype)
825
- aug_emb = self.add_embedding(add_embeds)
826
-
827
- emb = emb + aug_emb if aug_emb is not None else emb
828
-
829
- encoder_hidden_states = self.process_encoder_hidden_states(
830
- encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs
831
- )
832
-
833
- # 2. pre-process
834
- sample = self.conv_in(sample)
835
-
836
- controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
837
- sample = sample + controlnet_cond
838
-
839
- # 3. down
840
- down_block_res_samples = (sample,)
841
- for downsample_block in self.down_blocks:
842
- if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
843
- sample, res_samples = downsample_block(
844
- hidden_states=sample,
845
- temb=emb,
846
- encoder_hidden_states=encoder_hidden_states,
847
- attention_mask=attention_mask,
848
- cross_attention_kwargs=cross_attention_kwargs,
849
- )
850
- else:
851
- sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
852
-
853
- down_block_res_samples += res_samples
854
-
855
- # 4. mid
856
- if self.mid_block is not None:
857
- if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
858
- sample = self.mid_block(
859
- sample,
860
- emb,
861
- encoder_hidden_states=encoder_hidden_states,
862
- attention_mask=attention_mask,
863
- cross_attention_kwargs=cross_attention_kwargs,
864
- )
865
- else:
866
- sample = self.mid_block(sample, emb)
867
-
868
- # 5. Control net blocks
869
-
870
- controlnet_down_block_res_samples = ()
871
-
872
- for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
873
- down_block_res_sample = controlnet_block(down_block_res_sample)
874
- controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
875
-
876
- down_block_res_samples = controlnet_down_block_res_samples
877
-
878
- mid_block_res_sample = self.controlnet_mid_block(sample)
879
-
880
- # 6. scaling
881
- if guess_mode and not self.config.global_pool_conditions:
882
- scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
883
- scales = scales * conditioning_scale
884
- down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
885
- mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
886
- else:
887
- down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
888
- mid_block_res_sample = mid_block_res_sample * conditioning_scale
889
-
890
- if self.config.global_pool_conditions:
891
- down_block_res_samples = [
892
- torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
893
- ]
894
- mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
895
-
896
- if not return_dict:
897
- return (down_block_res_samples, mid_block_res_sample)
898
-
899
- return ControlNetOutput(
900
- down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
901
- )
902
-
903
-
904
- def zero_module(module):
905
- for p in module.parameters():
906
- nn.init.zeros_(p)
907
- return module
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/controlnet_flax.py DELETED
@@ -1,395 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from typing import 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 .unets.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.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] instead of
333
- a plain tuple.
334
- train (`bool`, *optional*, defaults to `False`):
335
- Use deterministic functions and disable dropout when not training.
336
-
337
- Returns:
338
- [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] or `tuple`:
339
- [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise
340
- a `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/controlnet_xs.py DELETED
@@ -1,1915 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from dataclasses import dataclass
15
- from math import gcd
16
- from typing import Any, Dict, List, Optional, Tuple, Union
17
-
18
- import torch
19
- import torch.utils.checkpoint
20
- from torch import FloatTensor, nn
21
-
22
- from ..configuration_utils import ConfigMixin, register_to_config
23
- from ..utils import BaseOutput, is_torch_version, logging
24
- from ..utils.torch_utils import apply_freeu
25
- from .attention_processor import (
26
- ADDED_KV_ATTENTION_PROCESSORS,
27
- CROSS_ATTENTION_PROCESSORS,
28
- Attention,
29
- AttentionProcessor,
30
- AttnAddedKVProcessor,
31
- AttnProcessor,
32
- )
33
- from .controlnet import ControlNetConditioningEmbedding
34
- from .embeddings import TimestepEmbedding, Timesteps
35
- from .modeling_utils import ModelMixin
36
- from .unets.unet_2d_blocks import (
37
- CrossAttnDownBlock2D,
38
- CrossAttnUpBlock2D,
39
- Downsample2D,
40
- ResnetBlock2D,
41
- Transformer2DModel,
42
- UNetMidBlock2DCrossAttn,
43
- Upsample2D,
44
- )
45
- from .unets.unet_2d_condition import UNet2DConditionModel
46
-
47
-
48
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
-
50
-
51
- @dataclass
52
- class ControlNetXSOutput(BaseOutput):
53
- """
54
- The output of [`UNetControlNetXSModel`].
55
-
56
- Args:
57
- sample (`FloatTensor` of shape `(batch_size, num_channels, height, width)`):
58
- The output of the `UNetControlNetXSModel`. Unlike `ControlNetOutput` this is NOT to be added to the base
59
- model output, but is already the final output.
60
- """
61
-
62
- sample: FloatTensor = None
63
-
64
-
65
- class DownBlockControlNetXSAdapter(nn.Module):
66
- """Components that together with corresponding components from the base model will form a
67
- `ControlNetXSCrossAttnDownBlock2D`"""
68
-
69
- def __init__(
70
- self,
71
- resnets: nn.ModuleList,
72
- base_to_ctrl: nn.ModuleList,
73
- ctrl_to_base: nn.ModuleList,
74
- attentions: Optional[nn.ModuleList] = None,
75
- downsampler: Optional[nn.Conv2d] = None,
76
- ):
77
- super().__init__()
78
- self.resnets = resnets
79
- self.base_to_ctrl = base_to_ctrl
80
- self.ctrl_to_base = ctrl_to_base
81
- self.attentions = attentions
82
- self.downsamplers = downsampler
83
-
84
-
85
- class MidBlockControlNetXSAdapter(nn.Module):
86
- """Components that together with corresponding components from the base model will form a
87
- `ControlNetXSCrossAttnMidBlock2D`"""
88
-
89
- def __init__(self, midblock: UNetMidBlock2DCrossAttn, base_to_ctrl: nn.ModuleList, ctrl_to_base: nn.ModuleList):
90
- super().__init__()
91
- self.midblock = midblock
92
- self.base_to_ctrl = base_to_ctrl
93
- self.ctrl_to_base = ctrl_to_base
94
-
95
-
96
- class UpBlockControlNetXSAdapter(nn.Module):
97
- """Components that together with corresponding components from the base model will form a `ControlNetXSCrossAttnUpBlock2D`"""
98
-
99
- def __init__(self, ctrl_to_base: nn.ModuleList):
100
- super().__init__()
101
- self.ctrl_to_base = ctrl_to_base
102
-
103
-
104
- def get_down_block_adapter(
105
- base_in_channels: int,
106
- base_out_channels: int,
107
- ctrl_in_channels: int,
108
- ctrl_out_channels: int,
109
- temb_channels: int,
110
- max_norm_num_groups: Optional[int] = 32,
111
- has_crossattn=True,
112
- transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
113
- num_attention_heads: Optional[int] = 1,
114
- cross_attention_dim: Optional[int] = 1024,
115
- add_downsample: bool = True,
116
- upcast_attention: Optional[bool] = False,
117
- ):
118
- num_layers = 2 # only support sd + sdxl
119
-
120
- resnets = []
121
- attentions = []
122
- ctrl_to_base = []
123
- base_to_ctrl = []
124
-
125
- if isinstance(transformer_layers_per_block, int):
126
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
127
-
128
- for i in range(num_layers):
129
- base_in_channels = base_in_channels if i == 0 else base_out_channels
130
- ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
131
-
132
- # Before the resnet/attention application, information is concatted from base to control.
133
- # Concat doesn't require change in number of channels
134
- base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
135
-
136
- resnets.append(
137
- ResnetBlock2D(
138
- in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
139
- out_channels=ctrl_out_channels,
140
- temb_channels=temb_channels,
141
- groups=find_largest_factor(ctrl_in_channels + base_in_channels, max_factor=max_norm_num_groups),
142
- groups_out=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
143
- eps=1e-5,
144
- )
145
- )
146
-
147
- if has_crossattn:
148
- attentions.append(
149
- Transformer2DModel(
150
- num_attention_heads,
151
- ctrl_out_channels // num_attention_heads,
152
- in_channels=ctrl_out_channels,
153
- num_layers=transformer_layers_per_block[i],
154
- cross_attention_dim=cross_attention_dim,
155
- use_linear_projection=True,
156
- upcast_attention=upcast_attention,
157
- norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
158
- )
159
- )
160
-
161
- # After the resnet/attention application, information is added from control to base
162
- # Addition requires change in number of channels
163
- ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
164
-
165
- if add_downsample:
166
- # Before the downsampler application, information is concatted from base to control
167
- # Concat doesn't require change in number of channels
168
- base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
169
-
170
- downsamplers = Downsample2D(
171
- ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
172
- )
173
-
174
- # After the downsampler application, information is added from control to base
175
- # Addition requires change in number of channels
176
- ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
177
- else:
178
- downsamplers = None
179
-
180
- down_block_components = DownBlockControlNetXSAdapter(
181
- resnets=nn.ModuleList(resnets),
182
- base_to_ctrl=nn.ModuleList(base_to_ctrl),
183
- ctrl_to_base=nn.ModuleList(ctrl_to_base),
184
- )
185
-
186
- if has_crossattn:
187
- down_block_components.attentions = nn.ModuleList(attentions)
188
- if downsamplers is not None:
189
- down_block_components.downsamplers = downsamplers
190
-
191
- return down_block_components
192
-
193
-
194
- def get_mid_block_adapter(
195
- base_channels: int,
196
- ctrl_channels: int,
197
- temb_channels: Optional[int] = None,
198
- max_norm_num_groups: Optional[int] = 32,
199
- transformer_layers_per_block: int = 1,
200
- num_attention_heads: Optional[int] = 1,
201
- cross_attention_dim: Optional[int] = 1024,
202
- upcast_attention: bool = False,
203
- ):
204
- # Before the midblock application, information is concatted from base to control.
205
- # Concat doesn't require change in number of channels
206
- base_to_ctrl = make_zero_conv(base_channels, base_channels)
207
-
208
- midblock = UNetMidBlock2DCrossAttn(
209
- transformer_layers_per_block=transformer_layers_per_block,
210
- in_channels=ctrl_channels + base_channels,
211
- out_channels=ctrl_channels,
212
- temb_channels=temb_channels,
213
- # number or norm groups must divide both in_channels and out_channels
214
- resnet_groups=find_largest_factor(gcd(ctrl_channels, ctrl_channels + base_channels), max_norm_num_groups),
215
- cross_attention_dim=cross_attention_dim,
216
- num_attention_heads=num_attention_heads,
217
- use_linear_projection=True,
218
- upcast_attention=upcast_attention,
219
- )
220
-
221
- # After the midblock application, information is added from control to base
222
- # Addition requires change in number of channels
223
- ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
224
-
225
- return MidBlockControlNetXSAdapter(base_to_ctrl=base_to_ctrl, midblock=midblock, ctrl_to_base=ctrl_to_base)
226
-
227
-
228
- def get_up_block_adapter(
229
- out_channels: int,
230
- prev_output_channel: int,
231
- ctrl_skip_channels: List[int],
232
- ):
233
- ctrl_to_base = []
234
- num_layers = 3 # only support sd + sdxl
235
- for i in range(num_layers):
236
- resnet_in_channels = prev_output_channel if i == 0 else out_channels
237
- ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
238
-
239
- return UpBlockControlNetXSAdapter(ctrl_to_base=nn.ModuleList(ctrl_to_base))
240
-
241
-
242
- class ControlNetXSAdapter(ModelMixin, ConfigMixin):
243
- r"""
244
- A `ControlNetXSAdapter` model. To use it, pass it into a `UNetControlNetXSModel` (together with a
245
- `UNet2DConditionModel` base model).
246
-
247
- This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
248
- methods implemented for all models (such as downloading or saving).
249
-
250
- Like `UNetControlNetXSModel`, `ControlNetXSAdapter` is compatible with StableDiffusion and StableDiffusion-XL. It's
251
- default parameters are compatible with StableDiffusion.
252
-
253
- Parameters:
254
- conditioning_channels (`int`, defaults to 3):
255
- Number of channels of conditioning input (e.g. an image)
256
- conditioning_channel_order (`str`, defaults to `"rgb"`):
257
- The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
258
- conditioning_embedding_out_channels (`tuple[int]`, defaults to `(16, 32, 96, 256)`):
259
- The tuple of output channels for each block in the `controlnet_cond_embedding` layer.
260
- time_embedding_mix (`float`, defaults to 1.0):
261
- If 0, then only the control adapters's time embedding is used. If 1, then only the base unet's time
262
- embedding is used. Otherwise, both are combined.
263
- learn_time_embedding (`bool`, defaults to `False`):
264
- Whether a time embedding should be learned. If yes, `UNetControlNetXSModel` will combine the time
265
- embeddings of the base model and the control adapter. If no, `UNetControlNetXSModel` will use the base
266
- model's time embedding.
267
- num_attention_heads (`list[int]`, defaults to `[4]`):
268
- The number of attention heads.
269
- block_out_channels (`list[int]`, defaults to `[4, 8, 16, 16]`):
270
- The tuple of output channels for each block.
271
- base_block_out_channels (`list[int]`, defaults to `[320, 640, 1280, 1280]`):
272
- The tuple of output channels for each block in the base unet.
273
- cross_attention_dim (`int`, defaults to 1024):
274
- The dimension of the cross attention features.
275
- down_block_types (`list[str]`, defaults to `["CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D"]`):
276
- The tuple of downsample blocks to use.
277
- sample_size (`int`, defaults to 96):
278
- Height and width of input/output sample.
279
- transformer_layers_per_block (`Union[int, Tuple[int]]`, defaults to 1):
280
- The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
281
- [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
282
- upcast_attention (`bool`, defaults to `True`):
283
- Whether the attention computation should always be upcasted.
284
- max_norm_num_groups (`int`, defaults to 32):
285
- Maximum number of groups in group normal. The actual number will the the largest divisor of the respective
286
- channels, that is <= max_norm_num_groups.
287
- """
288
-
289
- @register_to_config
290
- def __init__(
291
- self,
292
- conditioning_channels: int = 3,
293
- conditioning_channel_order: str = "rgb",
294
- conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
295
- time_embedding_mix: float = 1.0,
296
- learn_time_embedding: bool = False,
297
- num_attention_heads: Union[int, Tuple[int]] = 4,
298
- block_out_channels: Tuple[int] = (4, 8, 16, 16),
299
- base_block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
300
- cross_attention_dim: int = 1024,
301
- down_block_types: Tuple[str] = (
302
- "CrossAttnDownBlock2D",
303
- "CrossAttnDownBlock2D",
304
- "CrossAttnDownBlock2D",
305
- "DownBlock2D",
306
- ),
307
- sample_size: Optional[int] = 96,
308
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
309
- upcast_attention: bool = True,
310
- max_norm_num_groups: int = 32,
311
- ):
312
- super().__init__()
313
-
314
- time_embedding_input_dim = base_block_out_channels[0]
315
- time_embedding_dim = base_block_out_channels[0] * 4
316
-
317
- # Check inputs
318
- if conditioning_channel_order not in ["rgb", "bgr"]:
319
- raise ValueError(f"unknown `conditioning_channel_order`: {conditioning_channel_order}")
320
-
321
- if len(block_out_channels) != len(down_block_types):
322
- raise ValueError(
323
- 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}."
324
- )
325
-
326
- if not isinstance(transformer_layers_per_block, (list, tuple)):
327
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
328
- if not isinstance(cross_attention_dim, (list, tuple)):
329
- cross_attention_dim = [cross_attention_dim] * len(down_block_types)
330
- # see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why `ControlNetXSAdapter` takes `num_attention_heads` instead of `attention_head_dim`
331
- if not isinstance(num_attention_heads, (list, tuple)):
332
- num_attention_heads = [num_attention_heads] * len(down_block_types)
333
-
334
- if len(num_attention_heads) != len(down_block_types):
335
- raise ValueError(
336
- 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}."
337
- )
338
-
339
- # 5 - Create conditioning hint embedding
340
- self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
341
- conditioning_embedding_channels=block_out_channels[0],
342
- block_out_channels=conditioning_embedding_out_channels,
343
- conditioning_channels=conditioning_channels,
344
- )
345
-
346
- # time
347
- if learn_time_embedding:
348
- self.time_embedding = TimestepEmbedding(time_embedding_input_dim, time_embedding_dim)
349
- else:
350
- self.time_embedding = None
351
-
352
- self.down_blocks = nn.ModuleList([])
353
- self.up_connections = nn.ModuleList([])
354
-
355
- # input
356
- self.conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
357
- self.control_to_base_for_conv_in = make_zero_conv(block_out_channels[0], base_block_out_channels[0])
358
-
359
- # down
360
- base_out_channels = base_block_out_channels[0]
361
- ctrl_out_channels = block_out_channels[0]
362
- for i, down_block_type in enumerate(down_block_types):
363
- base_in_channels = base_out_channels
364
- base_out_channels = base_block_out_channels[i]
365
- ctrl_in_channels = ctrl_out_channels
366
- ctrl_out_channels = block_out_channels[i]
367
- has_crossattn = "CrossAttn" in down_block_type
368
- is_final_block = i == len(down_block_types) - 1
369
-
370
- self.down_blocks.append(
371
- get_down_block_adapter(
372
- base_in_channels=base_in_channels,
373
- base_out_channels=base_out_channels,
374
- ctrl_in_channels=ctrl_in_channels,
375
- ctrl_out_channels=ctrl_out_channels,
376
- temb_channels=time_embedding_dim,
377
- max_norm_num_groups=max_norm_num_groups,
378
- has_crossattn=has_crossattn,
379
- transformer_layers_per_block=transformer_layers_per_block[i],
380
- num_attention_heads=num_attention_heads[i],
381
- cross_attention_dim=cross_attention_dim[i],
382
- add_downsample=not is_final_block,
383
- upcast_attention=upcast_attention,
384
- )
385
- )
386
-
387
- # mid
388
- self.mid_block = get_mid_block_adapter(
389
- base_channels=base_block_out_channels[-1],
390
- ctrl_channels=block_out_channels[-1],
391
- temb_channels=time_embedding_dim,
392
- transformer_layers_per_block=transformer_layers_per_block[-1],
393
- num_attention_heads=num_attention_heads[-1],
394
- cross_attention_dim=cross_attention_dim[-1],
395
- upcast_attention=upcast_attention,
396
- )
397
-
398
- # up
399
- # The skip connection channels are the output of the conv_in and of all the down subblocks
400
- ctrl_skip_channels = [block_out_channels[0]]
401
- for i, out_channels in enumerate(block_out_channels):
402
- number_of_subblocks = (
403
- 3 if i < len(block_out_channels) - 1 else 2
404
- ) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
405
- ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
406
-
407
- reversed_base_block_out_channels = list(reversed(base_block_out_channels))
408
-
409
- base_out_channels = reversed_base_block_out_channels[0]
410
- for i in range(len(down_block_types)):
411
- prev_base_output_channel = base_out_channels
412
- base_out_channels = reversed_base_block_out_channels[i]
413
- ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
414
-
415
- self.up_connections.append(
416
- get_up_block_adapter(
417
- out_channels=base_out_channels,
418
- prev_output_channel=prev_base_output_channel,
419
- ctrl_skip_channels=ctrl_skip_channels_,
420
- )
421
- )
422
-
423
- @classmethod
424
- def from_unet(
425
- cls,
426
- unet: UNet2DConditionModel,
427
- size_ratio: Optional[float] = None,
428
- block_out_channels: Optional[List[int]] = None,
429
- num_attention_heads: Optional[List[int]] = None,
430
- learn_time_embedding: bool = False,
431
- time_embedding_mix: int = 1.0,
432
- conditioning_channels: int = 3,
433
- conditioning_channel_order: str = "rgb",
434
- conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
435
- ):
436
- r"""
437
- Instantiate a [`ControlNetXSAdapter`] from a [`UNet2DConditionModel`].
438
-
439
- Parameters:
440
- unet (`UNet2DConditionModel`):
441
- The UNet model we want to control. The dimensions of the ControlNetXSAdapter will be adapted to it.
442
- size_ratio (float, *optional*, defaults to `None`):
443
- When given, block_out_channels is set to a fraction of the base model's block_out_channels. Either this
444
- or `block_out_channels` must be given.
445
- block_out_channels (`List[int]`, *optional*, defaults to `None`):
446
- Down blocks output channels in control model. Either this or `size_ratio` must be given.
447
- num_attention_heads (`List[int]`, *optional*, defaults to `None`):
448
- The dimension of the attention heads. The naming seems a bit confusing and it is, see
449
- https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
450
- learn_time_embedding (`bool`, defaults to `False`):
451
- Whether the `ControlNetXSAdapter` should learn a time embedding.
452
- time_embedding_mix (`float`, defaults to 1.0):
453
- If 0, then only the control adapter's time embedding is used. If 1, then only the base unet's time
454
- embedding is used. Otherwise, both are combined.
455
- conditioning_channels (`int`, defaults to 3):
456
- Number of channels of conditioning input (e.g. an image)
457
- conditioning_channel_order (`str`, defaults to `"rgb"`):
458
- The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
459
- conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
460
- The tuple of output channel for each block in the `controlnet_cond_embedding` layer.
461
- """
462
-
463
- # Check input
464
- fixed_size = block_out_channels is not None
465
- relative_size = size_ratio is not None
466
- if not (fixed_size ^ relative_size):
467
- raise ValueError(
468
- "Pass exactly one of `block_out_channels` (for absolute sizing) or `size_ratio` (for relative sizing)."
469
- )
470
-
471
- # Create model
472
- block_out_channels = block_out_channels or [int(b * size_ratio) for b in unet.config.block_out_channels]
473
- if num_attention_heads is None:
474
- # The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
475
- num_attention_heads = unet.config.attention_head_dim
476
-
477
- model = cls(
478
- conditioning_channels=conditioning_channels,
479
- conditioning_channel_order=conditioning_channel_order,
480
- conditioning_embedding_out_channels=conditioning_embedding_out_channels,
481
- time_embedding_mix=time_embedding_mix,
482
- learn_time_embedding=learn_time_embedding,
483
- num_attention_heads=num_attention_heads,
484
- block_out_channels=block_out_channels,
485
- base_block_out_channels=unet.config.block_out_channels,
486
- cross_attention_dim=unet.config.cross_attention_dim,
487
- down_block_types=unet.config.down_block_types,
488
- sample_size=unet.config.sample_size,
489
- transformer_layers_per_block=unet.config.transformer_layers_per_block,
490
- upcast_attention=unet.config.upcast_attention,
491
- max_norm_num_groups=unet.config.norm_num_groups,
492
- )
493
-
494
- # ensure that the ControlNetXSAdapter is the same dtype as the UNet2DConditionModel
495
- model.to(unet.dtype)
496
-
497
- return model
498
-
499
- def forward(self, *args, **kwargs):
500
- raise ValueError(
501
- "A ControlNetXSAdapter cannot be run by itself. Use it together with a UNet2DConditionModel to instantiate a UNetControlNetXSModel."
502
- )
503
-
504
-
505
- class UNetControlNetXSModel(ModelMixin, ConfigMixin):
506
- r"""
507
- A UNet fused with a ControlNet-XS adapter model
508
-
509
- This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
510
- methods implemented for all models (such as downloading or saving).
511
-
512
- `UNetControlNetXSModel` is compatible with StableDiffusion and StableDiffusion-XL. It's default parameters are
513
- compatible with StableDiffusion.
514
-
515
- It's parameters are either passed to the underlying `UNet2DConditionModel` or used exactly like in
516
- `ControlNetXSAdapter` . See their documentation for details.
517
- """
518
-
519
- _supports_gradient_checkpointing = True
520
-
521
- @register_to_config
522
- def __init__(
523
- self,
524
- # unet configs
525
- sample_size: Optional[int] = 96,
526
- down_block_types: Tuple[str] = (
527
- "CrossAttnDownBlock2D",
528
- "CrossAttnDownBlock2D",
529
- "CrossAttnDownBlock2D",
530
- "DownBlock2D",
531
- ),
532
- up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
533
- block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
534
- norm_num_groups: Optional[int] = 32,
535
- cross_attention_dim: Union[int, Tuple[int]] = 1024,
536
- transformer_layers_per_block: Union[int, Tuple[int]] = 1,
537
- num_attention_heads: Union[int, Tuple[int]] = 8,
538
- addition_embed_type: Optional[str] = None,
539
- addition_time_embed_dim: Optional[int] = None,
540
- upcast_attention: bool = True,
541
- time_cond_proj_dim: Optional[int] = None,
542
- projection_class_embeddings_input_dim: Optional[int] = None,
543
- # additional controlnet configs
544
- time_embedding_mix: float = 1.0,
545
- ctrl_conditioning_channels: int = 3,
546
- ctrl_conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
547
- ctrl_conditioning_channel_order: str = "rgb",
548
- ctrl_learn_time_embedding: bool = False,
549
- ctrl_block_out_channels: Tuple[int] = (4, 8, 16, 16),
550
- ctrl_num_attention_heads: Union[int, Tuple[int]] = 4,
551
- ctrl_max_norm_num_groups: int = 32,
552
- ):
553
- super().__init__()
554
-
555
- if time_embedding_mix < 0 or time_embedding_mix > 1:
556
- raise ValueError("`time_embedding_mix` needs to be between 0 and 1.")
557
- if time_embedding_mix < 1 and not ctrl_learn_time_embedding:
558
- raise ValueError("To use `time_embedding_mix` < 1, `ctrl_learn_time_embedding` must be `True`")
559
-
560
- if addition_embed_type is not None and addition_embed_type != "text_time":
561
- raise ValueError(
562
- "As `UNetControlNetXSModel` currently only supports StableDiffusion and StableDiffusion-XL, `addition_embed_type` must be `None` or `'text_time'`."
563
- )
564
-
565
- if not isinstance(transformer_layers_per_block, (list, tuple)):
566
- transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
567
- if not isinstance(cross_attention_dim, (list, tuple)):
568
- cross_attention_dim = [cross_attention_dim] * len(down_block_types)
569
- if not isinstance(num_attention_heads, (list, tuple)):
570
- num_attention_heads = [num_attention_heads] * len(down_block_types)
571
- if not isinstance(ctrl_num_attention_heads, (list, tuple)):
572
- ctrl_num_attention_heads = [ctrl_num_attention_heads] * len(down_block_types)
573
-
574
- base_num_attention_heads = num_attention_heads
575
-
576
- self.in_channels = 4
577
-
578
- # # Input
579
- self.base_conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
580
- self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
581
- conditioning_embedding_channels=ctrl_block_out_channels[0],
582
- block_out_channels=ctrl_conditioning_embedding_out_channels,
583
- conditioning_channels=ctrl_conditioning_channels,
584
- )
585
- self.ctrl_conv_in = nn.Conv2d(4, ctrl_block_out_channels[0], kernel_size=3, padding=1)
586
- self.control_to_base_for_conv_in = make_zero_conv(ctrl_block_out_channels[0], block_out_channels[0])
587
-
588
- # # Time
589
- time_embed_input_dim = block_out_channels[0]
590
- time_embed_dim = block_out_channels[0] * 4
591
-
592
- self.base_time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos=True, downscale_freq_shift=0)
593
- self.base_time_embedding = TimestepEmbedding(
594
- time_embed_input_dim,
595
- time_embed_dim,
596
- cond_proj_dim=time_cond_proj_dim,
597
- )
598
- self.ctrl_time_embedding = TimestepEmbedding(in_channels=time_embed_input_dim, time_embed_dim=time_embed_dim)
599
-
600
- if addition_embed_type is None:
601
- self.base_add_time_proj = None
602
- self.base_add_embedding = None
603
- else:
604
- self.base_add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
605
- self.base_add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
606
-
607
- # # Create down blocks
608
- down_blocks = []
609
- base_out_channels = block_out_channels[0]
610
- ctrl_out_channels = ctrl_block_out_channels[0]
611
- for i, down_block_type in enumerate(down_block_types):
612
- base_in_channels = base_out_channels
613
- base_out_channels = block_out_channels[i]
614
- ctrl_in_channels = ctrl_out_channels
615
- ctrl_out_channels = ctrl_block_out_channels[i]
616
- has_crossattn = "CrossAttn" in down_block_type
617
- is_final_block = i == len(down_block_types) - 1
618
-
619
- down_blocks.append(
620
- ControlNetXSCrossAttnDownBlock2D(
621
- base_in_channels=base_in_channels,
622
- base_out_channels=base_out_channels,
623
- ctrl_in_channels=ctrl_in_channels,
624
- ctrl_out_channels=ctrl_out_channels,
625
- temb_channels=time_embed_dim,
626
- norm_num_groups=norm_num_groups,
627
- ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
628
- has_crossattn=has_crossattn,
629
- transformer_layers_per_block=transformer_layers_per_block[i],
630
- base_num_attention_heads=base_num_attention_heads[i],
631
- ctrl_num_attention_heads=ctrl_num_attention_heads[i],
632
- cross_attention_dim=cross_attention_dim[i],
633
- add_downsample=not is_final_block,
634
- upcast_attention=upcast_attention,
635
- )
636
- )
637
-
638
- # # Create mid block
639
- self.mid_block = ControlNetXSCrossAttnMidBlock2D(
640
- base_channels=block_out_channels[-1],
641
- ctrl_channels=ctrl_block_out_channels[-1],
642
- temb_channels=time_embed_dim,
643
- norm_num_groups=norm_num_groups,
644
- ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
645
- transformer_layers_per_block=transformer_layers_per_block[-1],
646
- base_num_attention_heads=base_num_attention_heads[-1],
647
- ctrl_num_attention_heads=ctrl_num_attention_heads[-1],
648
- cross_attention_dim=cross_attention_dim[-1],
649
- upcast_attention=upcast_attention,
650
- )
651
-
652
- # # Create up blocks
653
- up_blocks = []
654
- rev_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
655
- rev_num_attention_heads = list(reversed(base_num_attention_heads))
656
- rev_cross_attention_dim = list(reversed(cross_attention_dim))
657
-
658
- # The skip connection channels are the output of the conv_in and of all the down subblocks
659
- ctrl_skip_channels = [ctrl_block_out_channels[0]]
660
- for i, out_channels in enumerate(ctrl_block_out_channels):
661
- number_of_subblocks = (
662
- 3 if i < len(ctrl_block_out_channels) - 1 else 2
663
- ) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
664
- ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
665
-
666
- reversed_block_out_channels = list(reversed(block_out_channels))
667
-
668
- out_channels = reversed_block_out_channels[0]
669
- for i, up_block_type in enumerate(up_block_types):
670
- prev_output_channel = out_channels
671
- out_channels = reversed_block_out_channels[i]
672
- in_channels = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
673
- ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
674
-
675
- has_crossattn = "CrossAttn" in up_block_type
676
- is_final_block = i == len(block_out_channels) - 1
677
-
678
- up_blocks.append(
679
- ControlNetXSCrossAttnUpBlock2D(
680
- in_channels=in_channels,
681
- out_channels=out_channels,
682
- prev_output_channel=prev_output_channel,
683
- ctrl_skip_channels=ctrl_skip_channels_,
684
- temb_channels=time_embed_dim,
685
- resolution_idx=i,
686
- has_crossattn=has_crossattn,
687
- transformer_layers_per_block=rev_transformer_layers_per_block[i],
688
- num_attention_heads=rev_num_attention_heads[i],
689
- cross_attention_dim=rev_cross_attention_dim[i],
690
- add_upsample=not is_final_block,
691
- upcast_attention=upcast_attention,
692
- norm_num_groups=norm_num_groups,
693
- )
694
- )
695
-
696
- self.down_blocks = nn.ModuleList(down_blocks)
697
- self.up_blocks = nn.ModuleList(up_blocks)
698
-
699
- self.base_conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups)
700
- self.base_conv_act = nn.SiLU()
701
- self.base_conv_out = nn.Conv2d(block_out_channels[0], 4, kernel_size=3, padding=1)
702
-
703
- @classmethod
704
- def from_unet(
705
- cls,
706
- unet: UNet2DConditionModel,
707
- controlnet: Optional[ControlNetXSAdapter] = None,
708
- size_ratio: Optional[float] = None,
709
- ctrl_block_out_channels: Optional[List[float]] = None,
710
- time_embedding_mix: Optional[float] = None,
711
- ctrl_optional_kwargs: Optional[Dict] = None,
712
- ):
713
- r"""
714
- Instantiate a [`UNetControlNetXSModel`] from a [`UNet2DConditionModel`] and an optional [`ControlNetXSAdapter`]
715
- .
716
-
717
- Parameters:
718
- unet (`UNet2DConditionModel`):
719
- The UNet model we want to control.
720
- controlnet (`ControlNetXSAdapter`):
721
- The ConntrolNet-XS adapter with which the UNet will be fused. If none is given, a new ConntrolNet-XS
722
- adapter will be created.
723
- size_ratio (float, *optional*, defaults to `None`):
724
- Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
725
- ctrl_block_out_channels (`List[int]`, *optional*, defaults to `None`):
726
- Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details,
727
- where this parameter is called `block_out_channels`.
728
- time_embedding_mix (`float`, *optional*, defaults to None):
729
- Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
730
- ctrl_optional_kwargs (`Dict`, *optional*, defaults to `None`):
731
- Passed to the `init` of the new controlent if no controlent was given.
732
- """
733
- if controlnet is None:
734
- controlnet = ControlNetXSAdapter.from_unet(
735
- unet, size_ratio, ctrl_block_out_channels, **ctrl_optional_kwargs
736
- )
737
- else:
738
- if any(
739
- o is not None for o in (size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs)
740
- ):
741
- raise ValueError(
742
- "When a controlnet is passed, none of these parameters should be passed: size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs."
743
- )
744
-
745
- # # get params
746
- params_for_unet = [
747
- "sample_size",
748
- "down_block_types",
749
- "up_block_types",
750
- "block_out_channels",
751
- "norm_num_groups",
752
- "cross_attention_dim",
753
- "transformer_layers_per_block",
754
- "addition_embed_type",
755
- "addition_time_embed_dim",
756
- "upcast_attention",
757
- "time_cond_proj_dim",
758
- "projection_class_embeddings_input_dim",
759
- ]
760
- params_for_unet = {k: v for k, v in unet.config.items() if k in params_for_unet}
761
- # The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
762
- params_for_unet["num_attention_heads"] = unet.config.attention_head_dim
763
-
764
- params_for_controlnet = [
765
- "conditioning_channels",
766
- "conditioning_embedding_out_channels",
767
- "conditioning_channel_order",
768
- "learn_time_embedding",
769
- "block_out_channels",
770
- "num_attention_heads",
771
- "max_norm_num_groups",
772
- ]
773
- params_for_controlnet = {"ctrl_" + k: v for k, v in controlnet.config.items() if k in params_for_controlnet}
774
- params_for_controlnet["time_embedding_mix"] = controlnet.config.time_embedding_mix
775
-
776
- # # create model
777
- model = cls.from_config({**params_for_unet, **params_for_controlnet})
778
-
779
- # # load weights
780
- # from unet
781
- modules_from_unet = [
782
- "time_embedding",
783
- "conv_in",
784
- "conv_norm_out",
785
- "conv_out",
786
- ]
787
- for m in modules_from_unet:
788
- getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
789
-
790
- optional_modules_from_unet = [
791
- "add_time_proj",
792
- "add_embedding",
793
- ]
794
- for m in optional_modules_from_unet:
795
- if hasattr(unet, m) and getattr(unet, m) is not None:
796
- getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
797
-
798
- # from controlnet
799
- model.controlnet_cond_embedding.load_state_dict(controlnet.controlnet_cond_embedding.state_dict())
800
- model.ctrl_conv_in.load_state_dict(controlnet.conv_in.state_dict())
801
- if controlnet.time_embedding is not None:
802
- model.ctrl_time_embedding.load_state_dict(controlnet.time_embedding.state_dict())
803
- model.control_to_base_for_conv_in.load_state_dict(controlnet.control_to_base_for_conv_in.state_dict())
804
-
805
- # from both
806
- model.down_blocks = nn.ModuleList(
807
- ControlNetXSCrossAttnDownBlock2D.from_modules(b, c)
808
- for b, c in zip(unet.down_blocks, controlnet.down_blocks)
809
- )
810
- model.mid_block = ControlNetXSCrossAttnMidBlock2D.from_modules(unet.mid_block, controlnet.mid_block)
811
- model.up_blocks = nn.ModuleList(
812
- ControlNetXSCrossAttnUpBlock2D.from_modules(b, c)
813
- for b, c in zip(unet.up_blocks, controlnet.up_connections)
814
- )
815
-
816
- # ensure that the UNetControlNetXSModel is the same dtype as the UNet2DConditionModel
817
- model.to(unet.dtype)
818
-
819
- return model
820
-
821
- def freeze_unet_params(self) -> None:
822
- """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
823
- tuning."""
824
- # Freeze everything
825
- for param in self.parameters():
826
- param.requires_grad = True
827
-
828
- # Unfreeze ControlNetXSAdapter
829
- base_parts = [
830
- "base_time_proj",
831
- "base_time_embedding",
832
- "base_add_time_proj",
833
- "base_add_embedding",
834
- "base_conv_in",
835
- "base_conv_norm_out",
836
- "base_conv_act",
837
- "base_conv_out",
838
- ]
839
- base_parts = [getattr(self, part) for part in base_parts if getattr(self, part) is not None]
840
- for part in base_parts:
841
- for param in part.parameters():
842
- param.requires_grad = False
843
-
844
- for d in self.down_blocks:
845
- d.freeze_base_params()
846
- self.mid_block.freeze_base_params()
847
- for u in self.up_blocks:
848
- u.freeze_base_params()
849
-
850
- def _set_gradient_checkpointing(self, module, value=False):
851
- if hasattr(module, "gradient_checkpointing"):
852
- module.gradient_checkpointing = value
853
-
854
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel
855
- @property
856
- def attn_processors(self) -> Dict[str, AttentionProcessor]:
857
- r"""
858
- Returns:
859
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
860
- indexed by its weight name.
861
- """
862
- # set recursively
863
- processors = {}
864
-
865
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
866
- if hasattr(module, "get_processor"):
867
- processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
868
-
869
- for sub_name, child in module.named_children():
870
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
871
-
872
- return processors
873
-
874
- for name, module in self.named_children():
875
- fn_recursive_add_processors(name, module, processors)
876
-
877
- return processors
878
-
879
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
880
- def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
881
- r"""
882
- Sets the attention processor to use to compute attention.
883
-
884
- Parameters:
885
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
886
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
887
- for **all** `Attention` layers.
888
-
889
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
890
- processor. This is strongly recommended when setting trainable attention processors.
891
-
892
- """
893
- count = len(self.attn_processors.keys())
894
-
895
- if isinstance(processor, dict) and len(processor) != count:
896
- raise ValueError(
897
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
898
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
899
- )
900
-
901
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
902
- if hasattr(module, "set_processor"):
903
- if not isinstance(processor, dict):
904
- module.set_processor(processor)
905
- else:
906
- module.set_processor(processor.pop(f"{name}.processor"))
907
-
908
- for sub_name, child in module.named_children():
909
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
910
-
911
- for name, module in self.named_children():
912
- fn_recursive_attn_processor(name, module, processor)
913
-
914
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
915
- def set_default_attn_processor(self):
916
- """
917
- Disables custom attention processors and sets the default attention implementation.
918
- """
919
- if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
920
- processor = AttnAddedKVProcessor()
921
- elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
922
- processor = AttnProcessor()
923
- else:
924
- raise ValueError(
925
- f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
926
- )
927
-
928
- self.set_attn_processor(processor)
929
-
930
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.enable_freeu
931
- def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
932
- r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
933
-
934
- The suffixes after the scaling factors represent the stage blocks where they are being applied.
935
-
936
- Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
937
- are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
938
-
939
- Args:
940
- s1 (`float`):
941
- Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
942
- mitigate the "oversmoothing effect" in the enhanced denoising process.
943
- s2 (`float`):
944
- Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
945
- mitigate the "oversmoothing effect" in the enhanced denoising process.
946
- b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
947
- b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
948
- """
949
- for i, upsample_block in enumerate(self.up_blocks):
950
- setattr(upsample_block, "s1", s1)
951
- setattr(upsample_block, "s2", s2)
952
- setattr(upsample_block, "b1", b1)
953
- setattr(upsample_block, "b2", b2)
954
-
955
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.disable_freeu
956
- def disable_freeu(self):
957
- """Disables the FreeU mechanism."""
958
- freeu_keys = {"s1", "s2", "b1", "b2"}
959
- for i, upsample_block in enumerate(self.up_blocks):
960
- for k in freeu_keys:
961
- if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
962
- setattr(upsample_block, k, None)
963
-
964
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
965
- def fuse_qkv_projections(self):
966
- """
967
- Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
968
- are fused. For cross-attention modules, key and value projection matrices are fused.
969
-
970
- <Tip warning={true}>
971
-
972
- This API is 🧪 experimental.
973
-
974
- </Tip>
975
- """
976
- self.original_attn_processors = None
977
-
978
- for _, attn_processor in self.attn_processors.items():
979
- if "Added" in str(attn_processor.__class__.__name__):
980
- raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
981
-
982
- self.original_attn_processors = self.attn_processors
983
-
984
- for module in self.modules():
985
- if isinstance(module, Attention):
986
- module.fuse_projections(fuse=True)
987
-
988
- # copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
989
- def unfuse_qkv_projections(self):
990
- """Disables the fused QKV projection if enabled.
991
-
992
- <Tip warning={true}>
993
-
994
- This API is 🧪 experimental.
995
-
996
- </Tip>
997
-
998
- """
999
- if self.original_attn_processors is not None:
1000
- self.set_attn_processor(self.original_attn_processors)
1001
-
1002
- def forward(
1003
- self,
1004
- sample: FloatTensor,
1005
- timestep: Union[torch.Tensor, float, int],
1006
- encoder_hidden_states: torch.Tensor,
1007
- controlnet_cond: Optional[torch.Tensor] = None,
1008
- conditioning_scale: Optional[float] = 1.0,
1009
- class_labels: Optional[torch.Tensor] = None,
1010
- timestep_cond: Optional[torch.Tensor] = None,
1011
- attention_mask: Optional[torch.Tensor] = None,
1012
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1013
- added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1014
- return_dict: bool = True,
1015
- apply_control: bool = True,
1016
- ) -> Union[ControlNetXSOutput, Tuple]:
1017
- """
1018
- The [`ControlNetXSModel`] forward method.
1019
-
1020
- Args:
1021
- sample (`FloatTensor`):
1022
- The noisy input tensor.
1023
- timestep (`Union[torch.Tensor, float, int]`):
1024
- The number of timesteps to denoise an input.
1025
- encoder_hidden_states (`torch.Tensor`):
1026
- The encoder hidden states.
1027
- controlnet_cond (`FloatTensor`):
1028
- The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
1029
- conditioning_scale (`float`, defaults to `1.0`):
1030
- How much the control model affects the base model outputs.
1031
- class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1032
- Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1033
- timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
1034
- Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
1035
- timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
1036
- embeddings.
1037
- attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1038
- An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1039
- is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1040
- negative values to the attention scores corresponding to "discard" tokens.
1041
- cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
1042
- A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
1043
- added_cond_kwargs (`dict`):
1044
- Additional conditions for the Stable Diffusion XL UNet.
1045
- return_dict (`bool`, defaults to `True`):
1046
- Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
1047
- apply_control (`bool`, defaults to `True`):
1048
- If `False`, the input is run only through the base model.
1049
-
1050
- Returns:
1051
- [`~models.controlnetxs.ControlNetXSOutput`] **or** `tuple`:
1052
- If `return_dict` is `True`, a [`~models.controlnetxs.ControlNetXSOutput`] is returned, otherwise a
1053
- tuple is returned where the first element is the sample tensor.
1054
- """
1055
-
1056
- # check channel order
1057
- if self.config.ctrl_conditioning_channel_order == "bgr":
1058
- controlnet_cond = torch.flip(controlnet_cond, dims=[1])
1059
-
1060
- # prepare attention_mask
1061
- if attention_mask is not None:
1062
- attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1063
- attention_mask = attention_mask.unsqueeze(1)
1064
-
1065
- # 1. time
1066
- timesteps = timestep
1067
- if not torch.is_tensor(timesteps):
1068
- # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1069
- # This would be a good case for the `match` statement (Python 3.10+)
1070
- is_mps = sample.device.type == "mps"
1071
- if isinstance(timestep, float):
1072
- dtype = torch.float32 if is_mps else torch.float64
1073
- else:
1074
- dtype = torch.int32 if is_mps else torch.int64
1075
- timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1076
- elif len(timesteps.shape) == 0:
1077
- timesteps = timesteps[None].to(sample.device)
1078
-
1079
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1080
- timesteps = timesteps.expand(sample.shape[0])
1081
-
1082
- t_emb = self.base_time_proj(timesteps)
1083
-
1084
- # timesteps does not contain any weights and will always return f32 tensors
1085
- # but time_embedding might actually be running in fp16. so we need to cast here.
1086
- # there might be better ways to encapsulate this.
1087
- t_emb = t_emb.to(dtype=sample.dtype)
1088
-
1089
- if self.config.ctrl_learn_time_embedding and apply_control:
1090
- ctrl_temb = self.ctrl_time_embedding(t_emb, timestep_cond)
1091
- base_temb = self.base_time_embedding(t_emb, timestep_cond)
1092
- interpolation_param = self.config.time_embedding_mix**0.3
1093
-
1094
- temb = ctrl_temb * interpolation_param + base_temb * (1 - interpolation_param)
1095
- else:
1096
- temb = self.base_time_embedding(t_emb)
1097
-
1098
- # added time & text embeddings
1099
- aug_emb = None
1100
-
1101
- if self.config.addition_embed_type is None:
1102
- pass
1103
- elif self.config.addition_embed_type == "text_time":
1104
- # SDXL - style
1105
- if "text_embeds" not in added_cond_kwargs:
1106
- raise ValueError(
1107
- 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`"
1108
- )
1109
- text_embeds = added_cond_kwargs.get("text_embeds")
1110
- if "time_ids" not in added_cond_kwargs:
1111
- raise ValueError(
1112
- 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`"
1113
- )
1114
- time_ids = added_cond_kwargs.get("time_ids")
1115
- time_embeds = self.base_add_time_proj(time_ids.flatten())
1116
- time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1117
- add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1118
- add_embeds = add_embeds.to(temb.dtype)
1119
- aug_emb = self.base_add_embedding(add_embeds)
1120
- else:
1121
- raise ValueError(
1122
- f"ControlNet-XS currently only supports StableDiffusion and StableDiffusion-XL, so addition_embed_type = {self.config.addition_embed_type} is currently not supported."
1123
- )
1124
-
1125
- temb = temb + aug_emb if aug_emb is not None else temb
1126
-
1127
- # text embeddings
1128
- cemb = encoder_hidden_states
1129
-
1130
- # Preparation
1131
- h_ctrl = h_base = sample
1132
- hs_base, hs_ctrl = [], []
1133
-
1134
- # Cross Control
1135
- guided_hint = self.controlnet_cond_embedding(controlnet_cond)
1136
-
1137
- # 1 - conv in & down
1138
-
1139
- h_base = self.base_conv_in(h_base)
1140
- h_ctrl = self.ctrl_conv_in(h_ctrl)
1141
- if guided_hint is not None:
1142
- h_ctrl += guided_hint
1143
- if apply_control:
1144
- h_base = h_base + self.control_to_base_for_conv_in(h_ctrl) * conditioning_scale # add ctrl -> base
1145
-
1146
- hs_base.append(h_base)
1147
- hs_ctrl.append(h_ctrl)
1148
-
1149
- for down in self.down_blocks:
1150
- h_base, h_ctrl, residual_hb, residual_hc = down(
1151
- hidden_states_base=h_base,
1152
- hidden_states_ctrl=h_ctrl,
1153
- temb=temb,
1154
- encoder_hidden_states=cemb,
1155
- conditioning_scale=conditioning_scale,
1156
- cross_attention_kwargs=cross_attention_kwargs,
1157
- attention_mask=attention_mask,
1158
- apply_control=apply_control,
1159
- )
1160
- hs_base.extend(residual_hb)
1161
- hs_ctrl.extend(residual_hc)
1162
-
1163
- # 2 - mid
1164
- h_base, h_ctrl = self.mid_block(
1165
- hidden_states_base=h_base,
1166
- hidden_states_ctrl=h_ctrl,
1167
- temb=temb,
1168
- encoder_hidden_states=cemb,
1169
- conditioning_scale=conditioning_scale,
1170
- cross_attention_kwargs=cross_attention_kwargs,
1171
- attention_mask=attention_mask,
1172
- apply_control=apply_control,
1173
- )
1174
-
1175
- # 3 - up
1176
- for up in self.up_blocks:
1177
- n_resnets = len(up.resnets)
1178
- skips_hb = hs_base[-n_resnets:]
1179
- skips_hc = hs_ctrl[-n_resnets:]
1180
- hs_base = hs_base[:-n_resnets]
1181
- hs_ctrl = hs_ctrl[:-n_resnets]
1182
- h_base = up(
1183
- hidden_states=h_base,
1184
- res_hidden_states_tuple_base=skips_hb,
1185
- res_hidden_states_tuple_ctrl=skips_hc,
1186
- temb=temb,
1187
- encoder_hidden_states=cemb,
1188
- conditioning_scale=conditioning_scale,
1189
- cross_attention_kwargs=cross_attention_kwargs,
1190
- attention_mask=attention_mask,
1191
- apply_control=apply_control,
1192
- )
1193
-
1194
- # 4 - conv out
1195
- h_base = self.base_conv_norm_out(h_base)
1196
- h_base = self.base_conv_act(h_base)
1197
- h_base = self.base_conv_out(h_base)
1198
-
1199
- if not return_dict:
1200
- return (h_base,)
1201
-
1202
- return ControlNetXSOutput(sample=h_base)
1203
-
1204
-
1205
- class ControlNetXSCrossAttnDownBlock2D(nn.Module):
1206
- def __init__(
1207
- self,
1208
- base_in_channels: int,
1209
- base_out_channels: int,
1210
- ctrl_in_channels: int,
1211
- ctrl_out_channels: int,
1212
- temb_channels: int,
1213
- norm_num_groups: int = 32,
1214
- ctrl_max_norm_num_groups: int = 32,
1215
- has_crossattn=True,
1216
- transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
1217
- base_num_attention_heads: Optional[int] = 1,
1218
- ctrl_num_attention_heads: Optional[int] = 1,
1219
- cross_attention_dim: Optional[int] = 1024,
1220
- add_downsample: bool = True,
1221
- upcast_attention: Optional[bool] = False,
1222
- ):
1223
- super().__init__()
1224
- base_resnets = []
1225
- base_attentions = []
1226
- ctrl_resnets = []
1227
- ctrl_attentions = []
1228
- ctrl_to_base = []
1229
- base_to_ctrl = []
1230
-
1231
- num_layers = 2 # only support sd + sdxl
1232
-
1233
- if isinstance(transformer_layers_per_block, int):
1234
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
1235
-
1236
- for i in range(num_layers):
1237
- base_in_channels = base_in_channels if i == 0 else base_out_channels
1238
- ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
1239
-
1240
- # Before the resnet/attention application, information is concatted from base to control.
1241
- # Concat doesn't require change in number of channels
1242
- base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
1243
-
1244
- base_resnets.append(
1245
- ResnetBlock2D(
1246
- in_channels=base_in_channels,
1247
- out_channels=base_out_channels,
1248
- temb_channels=temb_channels,
1249
- groups=norm_num_groups,
1250
- )
1251
- )
1252
- ctrl_resnets.append(
1253
- ResnetBlock2D(
1254
- in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
1255
- out_channels=ctrl_out_channels,
1256
- temb_channels=temb_channels,
1257
- groups=find_largest_factor(
1258
- ctrl_in_channels + base_in_channels, max_factor=ctrl_max_norm_num_groups
1259
- ),
1260
- groups_out=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
1261
- eps=1e-5,
1262
- )
1263
- )
1264
-
1265
- if has_crossattn:
1266
- base_attentions.append(
1267
- Transformer2DModel(
1268
- base_num_attention_heads,
1269
- base_out_channels // base_num_attention_heads,
1270
- in_channels=base_out_channels,
1271
- num_layers=transformer_layers_per_block[i],
1272
- cross_attention_dim=cross_attention_dim,
1273
- use_linear_projection=True,
1274
- upcast_attention=upcast_attention,
1275
- norm_num_groups=norm_num_groups,
1276
- )
1277
- )
1278
- ctrl_attentions.append(
1279
- Transformer2DModel(
1280
- ctrl_num_attention_heads,
1281
- ctrl_out_channels // ctrl_num_attention_heads,
1282
- in_channels=ctrl_out_channels,
1283
- num_layers=transformer_layers_per_block[i],
1284
- cross_attention_dim=cross_attention_dim,
1285
- use_linear_projection=True,
1286
- upcast_attention=upcast_attention,
1287
- norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
1288
- )
1289
- )
1290
-
1291
- # After the resnet/attention application, information is added from control to base
1292
- # Addition requires change in number of channels
1293
- ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
1294
-
1295
- if add_downsample:
1296
- # Before the downsampler application, information is concatted from base to control
1297
- # Concat doesn't require change in number of channels
1298
- base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
1299
-
1300
- self.base_downsamplers = Downsample2D(
1301
- base_out_channels, use_conv=True, out_channels=base_out_channels, name="op"
1302
- )
1303
- self.ctrl_downsamplers = Downsample2D(
1304
- ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
1305
- )
1306
-
1307
- # After the downsampler application, information is added from control to base
1308
- # Addition requires change in number of channels
1309
- ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
1310
- else:
1311
- self.base_downsamplers = None
1312
- self.ctrl_downsamplers = None
1313
-
1314
- self.base_resnets = nn.ModuleList(base_resnets)
1315
- self.ctrl_resnets = nn.ModuleList(ctrl_resnets)
1316
- self.base_attentions = nn.ModuleList(base_attentions) if has_crossattn else [None] * num_layers
1317
- self.ctrl_attentions = nn.ModuleList(ctrl_attentions) if has_crossattn else [None] * num_layers
1318
- self.base_to_ctrl = nn.ModuleList(base_to_ctrl)
1319
- self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
1320
-
1321
- self.gradient_checkpointing = False
1322
-
1323
- @classmethod
1324
- def from_modules(cls, base_downblock: CrossAttnDownBlock2D, ctrl_downblock: DownBlockControlNetXSAdapter):
1325
- # get params
1326
- def get_first_cross_attention(block):
1327
- return block.attentions[0].transformer_blocks[0].attn2
1328
-
1329
- base_in_channels = base_downblock.resnets[0].in_channels
1330
- base_out_channels = base_downblock.resnets[0].out_channels
1331
- ctrl_in_channels = (
1332
- ctrl_downblock.resnets[0].in_channels - base_in_channels
1333
- ) # base channels are concatted to ctrl channels in init
1334
- ctrl_out_channels = ctrl_downblock.resnets[0].out_channels
1335
- temb_channels = base_downblock.resnets[0].time_emb_proj.in_features
1336
- num_groups = base_downblock.resnets[0].norm1.num_groups
1337
- ctrl_num_groups = ctrl_downblock.resnets[0].norm1.num_groups
1338
- if hasattr(base_downblock, "attentions"):
1339
- has_crossattn = True
1340
- transformer_layers_per_block = len(base_downblock.attentions[0].transformer_blocks)
1341
- base_num_attention_heads = get_first_cross_attention(base_downblock).heads
1342
- ctrl_num_attention_heads = get_first_cross_attention(ctrl_downblock).heads
1343
- cross_attention_dim = get_first_cross_attention(base_downblock).cross_attention_dim
1344
- upcast_attention = get_first_cross_attention(base_downblock).upcast_attention
1345
- else:
1346
- has_crossattn = False
1347
- transformer_layers_per_block = None
1348
- base_num_attention_heads = None
1349
- ctrl_num_attention_heads = None
1350
- cross_attention_dim = None
1351
- upcast_attention = None
1352
- add_downsample = base_downblock.downsamplers is not None
1353
-
1354
- # create model
1355
- model = cls(
1356
- base_in_channels=base_in_channels,
1357
- base_out_channels=base_out_channels,
1358
- ctrl_in_channels=ctrl_in_channels,
1359
- ctrl_out_channels=ctrl_out_channels,
1360
- temb_channels=temb_channels,
1361
- norm_num_groups=num_groups,
1362
- ctrl_max_norm_num_groups=ctrl_num_groups,
1363
- has_crossattn=has_crossattn,
1364
- transformer_layers_per_block=transformer_layers_per_block,
1365
- base_num_attention_heads=base_num_attention_heads,
1366
- ctrl_num_attention_heads=ctrl_num_attention_heads,
1367
- cross_attention_dim=cross_attention_dim,
1368
- add_downsample=add_downsample,
1369
- upcast_attention=upcast_attention,
1370
- )
1371
-
1372
- # # load weights
1373
- model.base_resnets.load_state_dict(base_downblock.resnets.state_dict())
1374
- model.ctrl_resnets.load_state_dict(ctrl_downblock.resnets.state_dict())
1375
- if has_crossattn:
1376
- model.base_attentions.load_state_dict(base_downblock.attentions.state_dict())
1377
- model.ctrl_attentions.load_state_dict(ctrl_downblock.attentions.state_dict())
1378
- if add_downsample:
1379
- model.base_downsamplers.load_state_dict(base_downblock.downsamplers[0].state_dict())
1380
- model.ctrl_downsamplers.load_state_dict(ctrl_downblock.downsamplers.state_dict())
1381
- model.base_to_ctrl.load_state_dict(ctrl_downblock.base_to_ctrl.state_dict())
1382
- model.ctrl_to_base.load_state_dict(ctrl_downblock.ctrl_to_base.state_dict())
1383
-
1384
- return model
1385
-
1386
- def freeze_base_params(self) -> None:
1387
- """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1388
- tuning."""
1389
- # Unfreeze everything
1390
- for param in self.parameters():
1391
- param.requires_grad = True
1392
-
1393
- # Freeze base part
1394
- base_parts = [self.base_resnets]
1395
- if isinstance(self.base_attentions, nn.ModuleList): # attentions can be a list of Nones
1396
- base_parts.append(self.base_attentions)
1397
- if self.base_downsamplers is not None:
1398
- base_parts.append(self.base_downsamplers)
1399
- for part in base_parts:
1400
- for param in part.parameters():
1401
- param.requires_grad = False
1402
-
1403
- def forward(
1404
- self,
1405
- hidden_states_base: FloatTensor,
1406
- temb: FloatTensor,
1407
- encoder_hidden_states: Optional[FloatTensor] = None,
1408
- hidden_states_ctrl: Optional[FloatTensor] = None,
1409
- conditioning_scale: Optional[float] = 1.0,
1410
- attention_mask: Optional[FloatTensor] = None,
1411
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1412
- encoder_attention_mask: Optional[FloatTensor] = None,
1413
- apply_control: bool = True,
1414
- ) -> Tuple[FloatTensor, FloatTensor, Tuple[FloatTensor, ...], Tuple[FloatTensor, ...]]:
1415
- if cross_attention_kwargs is not None:
1416
- if cross_attention_kwargs.get("scale", None) is not None:
1417
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1418
-
1419
- h_base = hidden_states_base
1420
- h_ctrl = hidden_states_ctrl
1421
-
1422
- base_output_states = ()
1423
- ctrl_output_states = ()
1424
-
1425
- base_blocks = list(zip(self.base_resnets, self.base_attentions))
1426
- ctrl_blocks = list(zip(self.ctrl_resnets, self.ctrl_attentions))
1427
-
1428
- def create_custom_forward(module, return_dict=None):
1429
- def custom_forward(*inputs):
1430
- if return_dict is not None:
1431
- return module(*inputs, return_dict=return_dict)
1432
- else:
1433
- return module(*inputs)
1434
-
1435
- return custom_forward
1436
-
1437
- for (b_res, b_attn), (c_res, c_attn), b2c, c2b in zip(
1438
- base_blocks, ctrl_blocks, self.base_to_ctrl, self.ctrl_to_base
1439
- ):
1440
- # concat base -> ctrl
1441
- if apply_control:
1442
- h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
1443
-
1444
- # apply base subblock
1445
- if self.training and self.gradient_checkpointing:
1446
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
1447
- h_base = torch.utils.checkpoint.checkpoint(
1448
- create_custom_forward(b_res),
1449
- h_base,
1450
- temb,
1451
- **ckpt_kwargs,
1452
- )
1453
- else:
1454
- h_base = b_res(h_base, temb)
1455
-
1456
- if b_attn is not None:
1457
- h_base = b_attn(
1458
- h_base,
1459
- encoder_hidden_states=encoder_hidden_states,
1460
- cross_attention_kwargs=cross_attention_kwargs,
1461
- attention_mask=attention_mask,
1462
- encoder_attention_mask=encoder_attention_mask,
1463
- return_dict=False,
1464
- )[0]
1465
-
1466
- # apply ctrl subblock
1467
- if apply_control:
1468
- if self.training and self.gradient_checkpointing:
1469
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
1470
- h_ctrl = torch.utils.checkpoint.checkpoint(
1471
- create_custom_forward(c_res),
1472
- h_ctrl,
1473
- temb,
1474
- **ckpt_kwargs,
1475
- )
1476
- else:
1477
- h_ctrl = c_res(h_ctrl, temb)
1478
- if c_attn is not None:
1479
- h_ctrl = c_attn(
1480
- h_ctrl,
1481
- encoder_hidden_states=encoder_hidden_states,
1482
- cross_attention_kwargs=cross_attention_kwargs,
1483
- attention_mask=attention_mask,
1484
- encoder_attention_mask=encoder_attention_mask,
1485
- return_dict=False,
1486
- )[0]
1487
-
1488
- # add ctrl -> base
1489
- if apply_control:
1490
- h_base = h_base + c2b(h_ctrl) * conditioning_scale
1491
-
1492
- base_output_states = base_output_states + (h_base,)
1493
- ctrl_output_states = ctrl_output_states + (h_ctrl,)
1494
-
1495
- if self.base_downsamplers is not None: # if we have a base_downsampler, then also a ctrl_downsampler
1496
- b2c = self.base_to_ctrl[-1]
1497
- c2b = self.ctrl_to_base[-1]
1498
-
1499
- # concat base -> ctrl
1500
- if apply_control:
1501
- h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
1502
- # apply base subblock
1503
- h_base = self.base_downsamplers(h_base)
1504
- # apply ctrl subblock
1505
- if apply_control:
1506
- h_ctrl = self.ctrl_downsamplers(h_ctrl)
1507
- # add ctrl -> base
1508
- if apply_control:
1509
- h_base = h_base + c2b(h_ctrl) * conditioning_scale
1510
-
1511
- base_output_states = base_output_states + (h_base,)
1512
- ctrl_output_states = ctrl_output_states + (h_ctrl,)
1513
-
1514
- return h_base, h_ctrl, base_output_states, ctrl_output_states
1515
-
1516
-
1517
- class ControlNetXSCrossAttnMidBlock2D(nn.Module):
1518
- def __init__(
1519
- self,
1520
- base_channels: int,
1521
- ctrl_channels: int,
1522
- temb_channels: Optional[int] = None,
1523
- norm_num_groups: int = 32,
1524
- ctrl_max_norm_num_groups: int = 32,
1525
- transformer_layers_per_block: int = 1,
1526
- base_num_attention_heads: Optional[int] = 1,
1527
- ctrl_num_attention_heads: Optional[int] = 1,
1528
- cross_attention_dim: Optional[int] = 1024,
1529
- upcast_attention: bool = False,
1530
- ):
1531
- super().__init__()
1532
-
1533
- # Before the midblock application, information is concatted from base to control.
1534
- # Concat doesn't require change in number of channels
1535
- self.base_to_ctrl = make_zero_conv(base_channels, base_channels)
1536
-
1537
- self.base_midblock = UNetMidBlock2DCrossAttn(
1538
- transformer_layers_per_block=transformer_layers_per_block,
1539
- in_channels=base_channels,
1540
- temb_channels=temb_channels,
1541
- resnet_groups=norm_num_groups,
1542
- cross_attention_dim=cross_attention_dim,
1543
- num_attention_heads=base_num_attention_heads,
1544
- use_linear_projection=True,
1545
- upcast_attention=upcast_attention,
1546
- )
1547
-
1548
- self.ctrl_midblock = UNetMidBlock2DCrossAttn(
1549
- transformer_layers_per_block=transformer_layers_per_block,
1550
- in_channels=ctrl_channels + base_channels,
1551
- out_channels=ctrl_channels,
1552
- temb_channels=temb_channels,
1553
- # number or norm groups must divide both in_channels and out_channels
1554
- resnet_groups=find_largest_factor(
1555
- gcd(ctrl_channels, ctrl_channels + base_channels), ctrl_max_norm_num_groups
1556
- ),
1557
- cross_attention_dim=cross_attention_dim,
1558
- num_attention_heads=ctrl_num_attention_heads,
1559
- use_linear_projection=True,
1560
- upcast_attention=upcast_attention,
1561
- )
1562
-
1563
- # After the midblock application, information is added from control to base
1564
- # Addition requires change in number of channels
1565
- self.ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
1566
-
1567
- self.gradient_checkpointing = False
1568
-
1569
- @classmethod
1570
- def from_modules(
1571
- cls,
1572
- base_midblock: UNetMidBlock2DCrossAttn,
1573
- ctrl_midblock: MidBlockControlNetXSAdapter,
1574
- ):
1575
- base_to_ctrl = ctrl_midblock.base_to_ctrl
1576
- ctrl_to_base = ctrl_midblock.ctrl_to_base
1577
- ctrl_midblock = ctrl_midblock.midblock
1578
-
1579
- # get params
1580
- def get_first_cross_attention(midblock):
1581
- return midblock.attentions[0].transformer_blocks[0].attn2
1582
-
1583
- base_channels = ctrl_to_base.out_channels
1584
- ctrl_channels = ctrl_to_base.in_channels
1585
- transformer_layers_per_block = len(base_midblock.attentions[0].transformer_blocks)
1586
- temb_channels = base_midblock.resnets[0].time_emb_proj.in_features
1587
- num_groups = base_midblock.resnets[0].norm1.num_groups
1588
- ctrl_num_groups = ctrl_midblock.resnets[0].norm1.num_groups
1589
- base_num_attention_heads = get_first_cross_attention(base_midblock).heads
1590
- ctrl_num_attention_heads = get_first_cross_attention(ctrl_midblock).heads
1591
- cross_attention_dim = get_first_cross_attention(base_midblock).cross_attention_dim
1592
- upcast_attention = get_first_cross_attention(base_midblock).upcast_attention
1593
-
1594
- # create model
1595
- model = cls(
1596
- base_channels=base_channels,
1597
- ctrl_channels=ctrl_channels,
1598
- temb_channels=temb_channels,
1599
- norm_num_groups=num_groups,
1600
- ctrl_max_norm_num_groups=ctrl_num_groups,
1601
- transformer_layers_per_block=transformer_layers_per_block,
1602
- base_num_attention_heads=base_num_attention_heads,
1603
- ctrl_num_attention_heads=ctrl_num_attention_heads,
1604
- cross_attention_dim=cross_attention_dim,
1605
- upcast_attention=upcast_attention,
1606
- )
1607
-
1608
- # load weights
1609
- model.base_to_ctrl.load_state_dict(base_to_ctrl.state_dict())
1610
- model.base_midblock.load_state_dict(base_midblock.state_dict())
1611
- model.ctrl_midblock.load_state_dict(ctrl_midblock.state_dict())
1612
- model.ctrl_to_base.load_state_dict(ctrl_to_base.state_dict())
1613
-
1614
- return model
1615
-
1616
- def freeze_base_params(self) -> None:
1617
- """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1618
- tuning."""
1619
- # Unfreeze everything
1620
- for param in self.parameters():
1621
- param.requires_grad = True
1622
-
1623
- # Freeze base part
1624
- for param in self.base_midblock.parameters():
1625
- param.requires_grad = False
1626
-
1627
- def forward(
1628
- self,
1629
- hidden_states_base: FloatTensor,
1630
- temb: FloatTensor,
1631
- encoder_hidden_states: FloatTensor,
1632
- hidden_states_ctrl: Optional[FloatTensor] = None,
1633
- conditioning_scale: Optional[float] = 1.0,
1634
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1635
- attention_mask: Optional[FloatTensor] = None,
1636
- encoder_attention_mask: Optional[FloatTensor] = None,
1637
- apply_control: bool = True,
1638
- ) -> Tuple[FloatTensor, FloatTensor]:
1639
- if cross_attention_kwargs is not None:
1640
- if cross_attention_kwargs.get("scale", None) is not None:
1641
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1642
-
1643
- h_base = hidden_states_base
1644
- h_ctrl = hidden_states_ctrl
1645
-
1646
- joint_args = {
1647
- "temb": temb,
1648
- "encoder_hidden_states": encoder_hidden_states,
1649
- "attention_mask": attention_mask,
1650
- "cross_attention_kwargs": cross_attention_kwargs,
1651
- "encoder_attention_mask": encoder_attention_mask,
1652
- }
1653
-
1654
- if apply_control:
1655
- h_ctrl = torch.cat([h_ctrl, self.base_to_ctrl(h_base)], dim=1) # concat base -> ctrl
1656
- h_base = self.base_midblock(h_base, **joint_args) # apply base mid block
1657
- if apply_control:
1658
- h_ctrl = self.ctrl_midblock(h_ctrl, **joint_args) # apply ctrl mid block
1659
- h_base = h_base + self.ctrl_to_base(h_ctrl) * conditioning_scale # add ctrl -> base
1660
-
1661
- return h_base, h_ctrl
1662
-
1663
-
1664
- class ControlNetXSCrossAttnUpBlock2D(nn.Module):
1665
- def __init__(
1666
- self,
1667
- in_channels: int,
1668
- out_channels: int,
1669
- prev_output_channel: int,
1670
- ctrl_skip_channels: List[int],
1671
- temb_channels: int,
1672
- norm_num_groups: int = 32,
1673
- resolution_idx: Optional[int] = None,
1674
- has_crossattn=True,
1675
- transformer_layers_per_block: int = 1,
1676
- num_attention_heads: int = 1,
1677
- cross_attention_dim: int = 1024,
1678
- add_upsample: bool = True,
1679
- upcast_attention: bool = False,
1680
- ):
1681
- super().__init__()
1682
- resnets = []
1683
- attentions = []
1684
- ctrl_to_base = []
1685
-
1686
- num_layers = 3 # only support sd + sdxl
1687
-
1688
- self.has_cross_attention = has_crossattn
1689
- self.num_attention_heads = num_attention_heads
1690
-
1691
- if isinstance(transformer_layers_per_block, int):
1692
- transformer_layers_per_block = [transformer_layers_per_block] * num_layers
1693
-
1694
- for i in range(num_layers):
1695
- res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
1696
- resnet_in_channels = prev_output_channel if i == 0 else out_channels
1697
-
1698
- ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
1699
-
1700
- resnets.append(
1701
- ResnetBlock2D(
1702
- in_channels=resnet_in_channels + res_skip_channels,
1703
- out_channels=out_channels,
1704
- temb_channels=temb_channels,
1705
- groups=norm_num_groups,
1706
- )
1707
- )
1708
-
1709
- if has_crossattn:
1710
- attentions.append(
1711
- Transformer2DModel(
1712
- num_attention_heads,
1713
- out_channels // num_attention_heads,
1714
- in_channels=out_channels,
1715
- num_layers=transformer_layers_per_block[i],
1716
- cross_attention_dim=cross_attention_dim,
1717
- use_linear_projection=True,
1718
- upcast_attention=upcast_attention,
1719
- norm_num_groups=norm_num_groups,
1720
- )
1721
- )
1722
-
1723
- self.resnets = nn.ModuleList(resnets)
1724
- self.attentions = nn.ModuleList(attentions) if has_crossattn else [None] * num_layers
1725
- self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
1726
-
1727
- if add_upsample:
1728
- self.upsamplers = Upsample2D(out_channels, use_conv=True, out_channels=out_channels)
1729
- else:
1730
- self.upsamplers = None
1731
-
1732
- self.gradient_checkpointing = False
1733
- self.resolution_idx = resolution_idx
1734
-
1735
- @classmethod
1736
- def from_modules(cls, base_upblock: CrossAttnUpBlock2D, ctrl_upblock: UpBlockControlNetXSAdapter):
1737
- ctrl_to_base_skip_connections = ctrl_upblock.ctrl_to_base
1738
-
1739
- # get params
1740
- def get_first_cross_attention(block):
1741
- return block.attentions[0].transformer_blocks[0].attn2
1742
-
1743
- out_channels = base_upblock.resnets[0].out_channels
1744
- in_channels = base_upblock.resnets[-1].in_channels - out_channels
1745
- prev_output_channels = base_upblock.resnets[0].in_channels - out_channels
1746
- ctrl_skip_channelss = [c.in_channels for c in ctrl_to_base_skip_connections]
1747
- temb_channels = base_upblock.resnets[0].time_emb_proj.in_features
1748
- num_groups = base_upblock.resnets[0].norm1.num_groups
1749
- resolution_idx = base_upblock.resolution_idx
1750
- if hasattr(base_upblock, "attentions"):
1751
- has_crossattn = True
1752
- transformer_layers_per_block = len(base_upblock.attentions[0].transformer_blocks)
1753
- num_attention_heads = get_first_cross_attention(base_upblock).heads
1754
- cross_attention_dim = get_first_cross_attention(base_upblock).cross_attention_dim
1755
- upcast_attention = get_first_cross_attention(base_upblock).upcast_attention
1756
- else:
1757
- has_crossattn = False
1758
- transformer_layers_per_block = None
1759
- num_attention_heads = None
1760
- cross_attention_dim = None
1761
- upcast_attention = None
1762
- add_upsample = base_upblock.upsamplers is not None
1763
-
1764
- # create model
1765
- model = cls(
1766
- in_channels=in_channels,
1767
- out_channels=out_channels,
1768
- prev_output_channel=prev_output_channels,
1769
- ctrl_skip_channels=ctrl_skip_channelss,
1770
- temb_channels=temb_channels,
1771
- norm_num_groups=num_groups,
1772
- resolution_idx=resolution_idx,
1773
- has_crossattn=has_crossattn,
1774
- transformer_layers_per_block=transformer_layers_per_block,
1775
- num_attention_heads=num_attention_heads,
1776
- cross_attention_dim=cross_attention_dim,
1777
- add_upsample=add_upsample,
1778
- upcast_attention=upcast_attention,
1779
- )
1780
-
1781
- # load weights
1782
- model.resnets.load_state_dict(base_upblock.resnets.state_dict())
1783
- if has_crossattn:
1784
- model.attentions.load_state_dict(base_upblock.attentions.state_dict())
1785
- if add_upsample:
1786
- model.upsamplers.load_state_dict(base_upblock.upsamplers[0].state_dict())
1787
- model.ctrl_to_base.load_state_dict(ctrl_to_base_skip_connections.state_dict())
1788
-
1789
- return model
1790
-
1791
- def freeze_base_params(self) -> None:
1792
- """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1793
- tuning."""
1794
- # Unfreeze everything
1795
- for param in self.parameters():
1796
- param.requires_grad = True
1797
-
1798
- # Freeze base part
1799
- base_parts = [self.resnets]
1800
- if isinstance(self.attentions, nn.ModuleList): # attentions can be a list of Nones
1801
- base_parts.append(self.attentions)
1802
- if self.upsamplers is not None:
1803
- base_parts.append(self.upsamplers)
1804
- for part in base_parts:
1805
- for param in part.parameters():
1806
- param.requires_grad = False
1807
-
1808
- def forward(
1809
- self,
1810
- hidden_states: FloatTensor,
1811
- res_hidden_states_tuple_base: Tuple[FloatTensor, ...],
1812
- res_hidden_states_tuple_ctrl: Tuple[FloatTensor, ...],
1813
- temb: FloatTensor,
1814
- encoder_hidden_states: Optional[FloatTensor] = None,
1815
- conditioning_scale: Optional[float] = 1.0,
1816
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1817
- attention_mask: Optional[FloatTensor] = None,
1818
- upsample_size: Optional[int] = None,
1819
- encoder_attention_mask: Optional[FloatTensor] = None,
1820
- apply_control: bool = True,
1821
- ) -> FloatTensor:
1822
- if cross_attention_kwargs is not None:
1823
- if cross_attention_kwargs.get("scale", None) is not None:
1824
- logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1825
-
1826
- is_freeu_enabled = (
1827
- getattr(self, "s1", None)
1828
- and getattr(self, "s2", None)
1829
- and getattr(self, "b1", None)
1830
- and getattr(self, "b2", None)
1831
- )
1832
-
1833
- def create_custom_forward(module, return_dict=None):
1834
- def custom_forward(*inputs):
1835
- if return_dict is not None:
1836
- return module(*inputs, return_dict=return_dict)
1837
- else:
1838
- return module(*inputs)
1839
-
1840
- return custom_forward
1841
-
1842
- def maybe_apply_freeu_to_subblock(hidden_states, res_h_base):
1843
- # FreeU: Only operate on the first two stages
1844
- if is_freeu_enabled:
1845
- return apply_freeu(
1846
- self.resolution_idx,
1847
- hidden_states,
1848
- res_h_base,
1849
- s1=self.s1,
1850
- s2=self.s2,
1851
- b1=self.b1,
1852
- b2=self.b2,
1853
- )
1854
- else:
1855
- return hidden_states, res_h_base
1856
-
1857
- for resnet, attn, c2b, res_h_base, res_h_ctrl in zip(
1858
- self.resnets,
1859
- self.attentions,
1860
- self.ctrl_to_base,
1861
- reversed(res_hidden_states_tuple_base),
1862
- reversed(res_hidden_states_tuple_ctrl),
1863
- ):
1864
- if apply_control:
1865
- hidden_states += c2b(res_h_ctrl) * conditioning_scale
1866
-
1867
- hidden_states, res_h_base = maybe_apply_freeu_to_subblock(hidden_states, res_h_base)
1868
- hidden_states = torch.cat([hidden_states, res_h_base], dim=1)
1869
-
1870
- if self.training and self.gradient_checkpointing:
1871
- ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
1872
- hidden_states = torch.utils.checkpoint.checkpoint(
1873
- create_custom_forward(resnet),
1874
- hidden_states,
1875
- temb,
1876
- **ckpt_kwargs,
1877
- )
1878
- else:
1879
- hidden_states = resnet(hidden_states, temb)
1880
-
1881
- if attn is not None:
1882
- hidden_states = attn(
1883
- hidden_states,
1884
- encoder_hidden_states=encoder_hidden_states,
1885
- cross_attention_kwargs=cross_attention_kwargs,
1886
- attention_mask=attention_mask,
1887
- encoder_attention_mask=encoder_attention_mask,
1888
- return_dict=False,
1889
- )[0]
1890
-
1891
- if self.upsamplers is not None:
1892
- hidden_states = self.upsamplers(hidden_states, upsample_size)
1893
-
1894
- return hidden_states
1895
-
1896
-
1897
- def make_zero_conv(in_channels, out_channels=None):
1898
- return zero_module(nn.Conv2d(in_channels, out_channels, 1, padding=0))
1899
-
1900
-
1901
- def zero_module(module):
1902
- for p in module.parameters():
1903
- nn.init.zeros_(p)
1904
- return module
1905
-
1906
-
1907
- def find_largest_factor(number, max_factor):
1908
- factor = max_factor
1909
- if factor >= number:
1910
- return number
1911
- while factor != 0:
1912
- residual = number % factor
1913
- if residual == 0:
1914
- return factor
1915
- factor -= 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/downsampling.py DELETED
@@ -1,333 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- from typing import Optional, Tuple
16
-
17
- import torch
18
- import torch.nn as nn
19
- import torch.nn.functional as F
20
-
21
- from ..utils import deprecate
22
- from .normalization import RMSNorm
23
- from .upsampling import upfirdn2d_native
24
-
25
-
26
- class Downsample1D(nn.Module):
27
- """A 1D downsampling layer with an optional convolution.
28
-
29
- Parameters:
30
- channels (`int`):
31
- number of channels in the inputs and outputs.
32
- use_conv (`bool`, default `False`):
33
- option to use a convolution.
34
- out_channels (`int`, optional):
35
- number of output channels. Defaults to `channels`.
36
- padding (`int`, default `1`):
37
- padding for the convolution.
38
- name (`str`, default `conv`):
39
- name of the downsampling 1D layer.
40
- """
41
-
42
- def __init__(
43
- self,
44
- channels: int,
45
- use_conv: bool = False,
46
- out_channels: Optional[int] = None,
47
- padding: int = 1,
48
- name: str = "conv",
49
- ):
50
- super().__init__()
51
- self.channels = channels
52
- self.out_channels = out_channels or channels
53
- self.use_conv = use_conv
54
- self.padding = padding
55
- stride = 2
56
- self.name = name
57
-
58
- if use_conv:
59
- self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
60
- else:
61
- assert self.channels == self.out_channels
62
- self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
63
-
64
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
65
- assert inputs.shape[1] == self.channels
66
- return self.conv(inputs)
67
-
68
-
69
- class Downsample2D(nn.Module):
70
- """A 2D downsampling layer with an optional convolution.
71
-
72
- Parameters:
73
- channels (`int`):
74
- number of channels in the inputs and outputs.
75
- use_conv (`bool`, default `False`):
76
- option to use a convolution.
77
- out_channels (`int`, optional):
78
- number of output channels. Defaults to `channels`.
79
- padding (`int`, default `1`):
80
- padding for the convolution.
81
- name (`str`, default `conv`):
82
- name of the downsampling 2D layer.
83
- """
84
-
85
- def __init__(
86
- self,
87
- channels: int,
88
- use_conv: bool = False,
89
- out_channels: Optional[int] = None,
90
- padding: int = 1,
91
- name: str = "conv",
92
- kernel_size=3,
93
- norm_type=None,
94
- eps=None,
95
- elementwise_affine=None,
96
- bias=True,
97
- ):
98
- super().__init__()
99
- self.channels = channels
100
- self.out_channels = out_channels or channels
101
- self.use_conv = use_conv
102
- self.padding = padding
103
- stride = 2
104
- self.name = name
105
-
106
- if norm_type == "ln_norm":
107
- self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
108
- elif norm_type == "rms_norm":
109
- self.norm = RMSNorm(channels, eps, elementwise_affine)
110
- elif norm_type is None:
111
- self.norm = None
112
- else:
113
- raise ValueError(f"unknown norm_type: {norm_type}")
114
-
115
- if use_conv:
116
- conv = nn.Conv2d(
117
- self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias
118
- )
119
- else:
120
- assert self.channels == self.out_channels
121
- conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
122
-
123
- # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
124
- if name == "conv":
125
- self.Conv2d_0 = conv
126
- self.conv = conv
127
- elif name == "Conv2d_0":
128
- self.conv = conv
129
- else:
130
- self.conv = conv
131
-
132
- def forward(self, hidden_states: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
133
- if len(args) > 0 or kwargs.get("scale", None) is not None:
134
- deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
135
- deprecate("scale", "1.0.0", deprecation_message)
136
- assert hidden_states.shape[1] == self.channels
137
-
138
- if self.norm is not None:
139
- hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
140
-
141
- if self.use_conv and self.padding == 0:
142
- pad = (0, 1, 0, 1)
143
- hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
144
-
145
- assert hidden_states.shape[1] == self.channels
146
-
147
- hidden_states = self.conv(hidden_states)
148
-
149
- return hidden_states
150
-
151
-
152
- class FirDownsample2D(nn.Module):
153
- """A 2D FIR downsampling layer with an optional convolution.
154
-
155
- Parameters:
156
- channels (`int`):
157
- number of channels in the inputs and outputs.
158
- use_conv (`bool`, default `False`):
159
- option to use a convolution.
160
- out_channels (`int`, optional):
161
- number of output channels. Defaults to `channels`.
162
- fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
163
- kernel for the FIR filter.
164
- """
165
-
166
- def __init__(
167
- self,
168
- channels: Optional[int] = None,
169
- out_channels: Optional[int] = None,
170
- use_conv: bool = False,
171
- fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
172
- ):
173
- super().__init__()
174
- out_channels = out_channels if out_channels else channels
175
- if use_conv:
176
- self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
177
- self.fir_kernel = fir_kernel
178
- self.use_conv = use_conv
179
- self.out_channels = out_channels
180
-
181
- def _downsample_2d(
182
- self,
183
- hidden_states: torch.FloatTensor,
184
- weight: Optional[torch.FloatTensor] = None,
185
- kernel: Optional[torch.FloatTensor] = None,
186
- factor: int = 2,
187
- gain: float = 1,
188
- ) -> torch.FloatTensor:
189
- """Fused `Conv2d()` followed by `downsample_2d()`.
190
- Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
191
- efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
192
- arbitrary order.
193
-
194
- Args:
195
- hidden_states (`torch.FloatTensor`):
196
- Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
197
- weight (`torch.FloatTensor`, *optional*):
198
- Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
199
- performed by `inChannels = x.shape[0] // numGroups`.
200
- kernel (`torch.FloatTensor`, *optional*):
201
- FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
202
- corresponds to average pooling.
203
- factor (`int`, *optional*, default to `2`):
204
- Integer downsampling factor.
205
- gain (`float`, *optional*, default to `1.0`):
206
- Scaling factor for signal magnitude.
207
-
208
- Returns:
209
- output (`torch.FloatTensor`):
210
- Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
211
- datatype as `x`.
212
- """
213
-
214
- assert isinstance(factor, int) and factor >= 1
215
- if kernel is None:
216
- kernel = [1] * factor
217
-
218
- # setup kernel
219
- kernel = torch.tensor(kernel, dtype=torch.float32)
220
- if kernel.ndim == 1:
221
- kernel = torch.outer(kernel, kernel)
222
- kernel /= torch.sum(kernel)
223
-
224
- kernel = kernel * gain
225
-
226
- if self.use_conv:
227
- _, _, convH, convW = weight.shape
228
- pad_value = (kernel.shape[0] - factor) + (convW - 1)
229
- stride_value = [factor, factor]
230
- upfirdn_input = upfirdn2d_native(
231
- hidden_states,
232
- torch.tensor(kernel, device=hidden_states.device),
233
- pad=((pad_value + 1) // 2, pad_value // 2),
234
- )
235
- output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
236
- else:
237
- pad_value = kernel.shape[0] - factor
238
- output = upfirdn2d_native(
239
- hidden_states,
240
- torch.tensor(kernel, device=hidden_states.device),
241
- down=factor,
242
- pad=((pad_value + 1) // 2, pad_value // 2),
243
- )
244
-
245
- return output
246
-
247
- def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
248
- if self.use_conv:
249
- downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
250
- hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
251
- else:
252
- hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
253
-
254
- return hidden_states
255
-
256
-
257
- # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
258
- class KDownsample2D(nn.Module):
259
- r"""A 2D K-downsampling layer.
260
-
261
- Parameters:
262
- pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
263
- """
264
-
265
- def __init__(self, pad_mode: str = "reflect"):
266
- super().__init__()
267
- self.pad_mode = pad_mode
268
- kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
269
- self.pad = kernel_1d.shape[1] // 2 - 1
270
- self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
271
-
272
- def forward(self, inputs: torch.Tensor) -> torch.Tensor:
273
- inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
274
- weight = inputs.new_zeros(
275
- [
276
- inputs.shape[1],
277
- inputs.shape[1],
278
- self.kernel.shape[0],
279
- self.kernel.shape[1],
280
- ]
281
- )
282
- indices = torch.arange(inputs.shape[1], device=inputs.device)
283
- kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
284
- weight[indices, indices] = kernel
285
- return F.conv2d(inputs, weight, stride=2)
286
-
287
-
288
- def downsample_2d(
289
- hidden_states: torch.FloatTensor,
290
- kernel: Optional[torch.FloatTensor] = None,
291
- factor: int = 2,
292
- gain: float = 1,
293
- ) -> torch.FloatTensor:
294
- r"""Downsample2D a batch of 2D images with the given filter.
295
- Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
296
- given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
297
- specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
298
- shape is a multiple of the downsampling factor.
299
-
300
- Args:
301
- hidden_states (`torch.FloatTensor`)
302
- Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
303
- kernel (`torch.FloatTensor`, *optional*):
304
- FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
305
- corresponds to average pooling.
306
- factor (`int`, *optional*, default to `2`):
307
- Integer downsampling factor.
308
- gain (`float`, *optional*, default to `1.0`):
309
- Scaling factor for signal magnitude.
310
-
311
- Returns:
312
- output (`torch.FloatTensor`):
313
- Tensor of the shape `[N, C, H // factor, W // factor]`
314
- """
315
-
316
- assert isinstance(factor, int) and factor >= 1
317
- if kernel is None:
318
- kernel = [1] * factor
319
-
320
- kernel = torch.tensor(kernel, dtype=torch.float32)
321
- if kernel.ndim == 1:
322
- kernel = torch.outer(kernel, kernel)
323
- kernel /= torch.sum(kernel)
324
-
325
- kernel = kernel * gain
326
- pad_value = kernel.shape[0] - factor
327
- output = upfirdn2d_native(
328
- hidden_states,
329
- kernel.to(device=hidden_states.device),
330
- down=factor,
331
- pad=((pad_value + 1) // 2, pad_value // 2),
332
- )
333
- return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/dual_transformer_2d.py DELETED
@@ -1,20 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- from ..utils import deprecate
15
- from .transformers.dual_transformer_2d import DualTransformer2DModel
16
-
17
-
18
- class DualTransformer2DModel(DualTransformer2DModel):
19
- deprecation_message = "Importing `DualTransformer2DModel` from `diffusers.models.dual_transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.transformers.dual_transformer_2d import DualTransformer2DModel`, instead."
20
- deprecate("DualTransformer2DModel", "0.29", deprecation_message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/embeddings.py DELETED
@@ -1,1037 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import math
15
- from typing import List, Optional, Tuple, Union
16
-
17
- import numpy as np
18
- import torch
19
- from torch import nn
20
-
21
- from ..utils import deprecate
22
- from .activations import get_activation
23
- from .attention_processor import Attention
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
- sample_proj_bias=True,
200
- ):
201
- super().__init__()
202
-
203
- self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
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 = nn.Linear(time_embed_dim, time_embed_dim_out, sample_proj_bias)
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 IPAdapterFullImageProjection(nn.Module):
464
- def __init__(self, image_embed_dim=1024, cross_attention_dim=1024):
465
- super().__init__()
466
- from .attention import FeedForward
467
-
468
- self.ff = FeedForward(image_embed_dim, cross_attention_dim, mult=1, activation_fn="gelu")
469
- self.norm = nn.LayerNorm(cross_attention_dim)
470
-
471
- def forward(self, image_embeds: torch.FloatTensor):
472
- return self.norm(self.ff(image_embeds))
473
-
474
-
475
- class IPAdapterFaceIDImageProjection(nn.Module):
476
- def __init__(self, image_embed_dim=1024, cross_attention_dim=1024, mult=1, num_tokens=1):
477
- super().__init__()
478
- from .attention import FeedForward
479
-
480
- self.num_tokens = num_tokens
481
- self.cross_attention_dim = cross_attention_dim
482
- self.ff = FeedForward(image_embed_dim, cross_attention_dim * num_tokens, mult=mult, activation_fn="gelu")
483
- self.norm = nn.LayerNorm(cross_attention_dim)
484
-
485
- def forward(self, image_embeds: torch.FloatTensor):
486
- x = self.ff(image_embeds)
487
- x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
488
- return self.norm(x)
489
-
490
-
491
- class CombinedTimestepLabelEmbeddings(nn.Module):
492
- def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
493
- super().__init__()
494
-
495
- self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1)
496
- self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
497
- self.class_embedder = LabelEmbedding(num_classes, embedding_dim, class_dropout_prob)
498
-
499
- def forward(self, timestep, class_labels, hidden_dtype=None):
500
- timesteps_proj = self.time_proj(timestep)
501
- timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
502
-
503
- class_labels = self.class_embedder(class_labels) # (N, D)
504
-
505
- conditioning = timesteps_emb + class_labels # (N, D)
506
-
507
- return conditioning
508
-
509
-
510
- class TextTimeEmbedding(nn.Module):
511
- def __init__(self, encoder_dim: int, time_embed_dim: int, num_heads: int = 64):
512
- super().__init__()
513
- self.norm1 = nn.LayerNorm(encoder_dim)
514
- self.pool = AttentionPooling(num_heads, encoder_dim)
515
- self.proj = nn.Linear(encoder_dim, time_embed_dim)
516
- self.norm2 = nn.LayerNorm(time_embed_dim)
517
-
518
- def forward(self, hidden_states):
519
- hidden_states = self.norm1(hidden_states)
520
- hidden_states = self.pool(hidden_states)
521
- hidden_states = self.proj(hidden_states)
522
- hidden_states = self.norm2(hidden_states)
523
- return hidden_states
524
-
525
-
526
- class TextImageTimeEmbedding(nn.Module):
527
- def __init__(self, text_embed_dim: int = 768, image_embed_dim: int = 768, time_embed_dim: int = 1536):
528
- super().__init__()
529
- self.text_proj = nn.Linear(text_embed_dim, time_embed_dim)
530
- self.text_norm = nn.LayerNorm(time_embed_dim)
531
- self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
532
-
533
- def forward(self, text_embeds: torch.FloatTensor, image_embeds: torch.FloatTensor):
534
- # text
535
- time_text_embeds = self.text_proj(text_embeds)
536
- time_text_embeds = self.text_norm(time_text_embeds)
537
-
538
- # image
539
- time_image_embeds = self.image_proj(image_embeds)
540
-
541
- return time_image_embeds + time_text_embeds
542
-
543
-
544
- class ImageTimeEmbedding(nn.Module):
545
- def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
546
- super().__init__()
547
- self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
548
- self.image_norm = nn.LayerNorm(time_embed_dim)
549
-
550
- def forward(self, image_embeds: torch.FloatTensor):
551
- # image
552
- time_image_embeds = self.image_proj(image_embeds)
553
- time_image_embeds = self.image_norm(time_image_embeds)
554
- return time_image_embeds
555
-
556
-
557
- class ImageHintTimeEmbedding(nn.Module):
558
- def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
559
- super().__init__()
560
- self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
561
- self.image_norm = nn.LayerNorm(time_embed_dim)
562
- self.input_hint_block = nn.Sequential(
563
- nn.Conv2d(3, 16, 3, padding=1),
564
- nn.SiLU(),
565
- nn.Conv2d(16, 16, 3, padding=1),
566
- nn.SiLU(),
567
- nn.Conv2d(16, 32, 3, padding=1, stride=2),
568
- nn.SiLU(),
569
- nn.Conv2d(32, 32, 3, padding=1),
570
- nn.SiLU(),
571
- nn.Conv2d(32, 96, 3, padding=1, stride=2),
572
- nn.SiLU(),
573
- nn.Conv2d(96, 96, 3, padding=1),
574
- nn.SiLU(),
575
- nn.Conv2d(96, 256, 3, padding=1, stride=2),
576
- nn.SiLU(),
577
- nn.Conv2d(256, 4, 3, padding=1),
578
- )
579
-
580
- def forward(self, image_embeds: torch.FloatTensor, hint: torch.FloatTensor):
581
- # image
582
- time_image_embeds = self.image_proj(image_embeds)
583
- time_image_embeds = self.image_norm(time_image_embeds)
584
- hint = self.input_hint_block(hint)
585
- return time_image_embeds, hint
586
-
587
-
588
- class AttentionPooling(nn.Module):
589
- # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54
590
-
591
- def __init__(self, num_heads, embed_dim, dtype=None):
592
- super().__init__()
593
- self.dtype = dtype
594
- self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5)
595
- self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
596
- self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
597
- self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
598
- self.num_heads = num_heads
599
- self.dim_per_head = embed_dim // self.num_heads
600
-
601
- def forward(self, x):
602
- bs, length, width = x.size()
603
-
604
- def shape(x):
605
- # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
606
- x = x.view(bs, -1, self.num_heads, self.dim_per_head)
607
- # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
608
- x = x.transpose(1, 2)
609
- # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
610
- x = x.reshape(bs * self.num_heads, -1, self.dim_per_head)
611
- # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
612
- x = x.transpose(1, 2)
613
- return x
614
-
615
- class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype)
616
- x = torch.cat([class_token, x], dim=1) # (bs, length+1, width)
617
-
618
- # (bs*n_heads, class_token_length, dim_per_head)
619
- q = shape(self.q_proj(class_token))
620
- # (bs*n_heads, length+class_token_length, dim_per_head)
621
- k = shape(self.k_proj(x))
622
- v = shape(self.v_proj(x))
623
-
624
- # (bs*n_heads, class_token_length, length+class_token_length):
625
- scale = 1 / math.sqrt(math.sqrt(self.dim_per_head))
626
- weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards
627
- weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
628
-
629
- # (bs*n_heads, dim_per_head, class_token_length)
630
- a = torch.einsum("bts,bcs->bct", weight, v)
631
-
632
- # (bs, length+1, width)
633
- a = a.reshape(bs, -1, 1).transpose(1, 2)
634
-
635
- return a[:, 0, :] # cls_token
636
-
637
-
638
- def get_fourier_embeds_from_boundingbox(embed_dim, box):
639
- """
640
- Args:
641
- embed_dim: int
642
- box: a 3-D tensor [B x N x 4] representing the bounding boxes for GLIGEN pipeline
643
- Returns:
644
- [B x N x embed_dim] tensor of positional embeddings
645
- """
646
-
647
- batch_size, num_boxes = box.shape[:2]
648
-
649
- emb = 100 ** (torch.arange(embed_dim) / embed_dim)
650
- emb = emb[None, None, None].to(device=box.device, dtype=box.dtype)
651
- emb = emb * box.unsqueeze(-1)
652
-
653
- emb = torch.stack((emb.sin(), emb.cos()), dim=-1)
654
- emb = emb.permute(0, 1, 3, 4, 2).reshape(batch_size, num_boxes, embed_dim * 2 * 4)
655
-
656
- return emb
657
-
658
-
659
- class GLIGENTextBoundingboxProjection(nn.Module):
660
- def __init__(self, positive_len, out_dim, feature_type="text-only", fourier_freqs=8):
661
- super().__init__()
662
- self.positive_len = positive_len
663
- self.out_dim = out_dim
664
-
665
- self.fourier_embedder_dim = fourier_freqs
666
- self.position_dim = fourier_freqs * 2 * 4 # 2: sin/cos, 4: xyxy
667
-
668
- if isinstance(out_dim, tuple):
669
- out_dim = out_dim[0]
670
-
671
- if feature_type == "text-only":
672
- self.linears = nn.Sequential(
673
- nn.Linear(self.positive_len + self.position_dim, 512),
674
- nn.SiLU(),
675
- nn.Linear(512, 512),
676
- nn.SiLU(),
677
- nn.Linear(512, out_dim),
678
- )
679
- self.null_positive_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
680
-
681
- elif feature_type == "text-image":
682
- self.linears_text = nn.Sequential(
683
- nn.Linear(self.positive_len + self.position_dim, 512),
684
- nn.SiLU(),
685
- nn.Linear(512, 512),
686
- nn.SiLU(),
687
- nn.Linear(512, out_dim),
688
- )
689
- self.linears_image = nn.Sequential(
690
- nn.Linear(self.positive_len + self.position_dim, 512),
691
- nn.SiLU(),
692
- nn.Linear(512, 512),
693
- nn.SiLU(),
694
- nn.Linear(512, out_dim),
695
- )
696
- self.null_text_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
697
- self.null_image_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
698
-
699
- self.null_position_feature = torch.nn.Parameter(torch.zeros([self.position_dim]))
700
-
701
- def forward(
702
- self,
703
- boxes,
704
- masks,
705
- positive_embeddings=None,
706
- phrases_masks=None,
707
- image_masks=None,
708
- phrases_embeddings=None,
709
- image_embeddings=None,
710
- ):
711
- masks = masks.unsqueeze(-1)
712
-
713
- # embedding position (it may includes padding as placeholder)
714
- xyxy_embedding = get_fourier_embeds_from_boundingbox(self.fourier_embedder_dim, boxes) # B*N*4 -> B*N*C
715
-
716
- # learnable null embedding
717
- xyxy_null = self.null_position_feature.view(1, 1, -1)
718
-
719
- # replace padding with learnable null embedding
720
- xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
721
-
722
- # positionet with text only information
723
- if positive_embeddings is not None:
724
- # learnable null embedding
725
- positive_null = self.null_positive_feature.view(1, 1, -1)
726
-
727
- # replace padding with learnable null embedding
728
- positive_embeddings = positive_embeddings * masks + (1 - masks) * positive_null
729
-
730
- objs = self.linears(torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
731
-
732
- # positionet with text and image infomation
733
- else:
734
- phrases_masks = phrases_masks.unsqueeze(-1)
735
- image_masks = image_masks.unsqueeze(-1)
736
-
737
- # learnable null embedding
738
- text_null = self.null_text_feature.view(1, 1, -1)
739
- image_null = self.null_image_feature.view(1, 1, -1)
740
-
741
- # replace padding with learnable null embedding
742
- phrases_embeddings = phrases_embeddings * phrases_masks + (1 - phrases_masks) * text_null
743
- image_embeddings = image_embeddings * image_masks + (1 - image_masks) * image_null
744
-
745
- objs_text = self.linears_text(torch.cat([phrases_embeddings, xyxy_embedding], dim=-1))
746
- objs_image = self.linears_image(torch.cat([image_embeddings, xyxy_embedding], dim=-1))
747
- objs = torch.cat([objs_text, objs_image], dim=1)
748
-
749
- return objs
750
-
751
-
752
- class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):
753
- """
754
- For PixArt-Alpha.
755
-
756
- Reference:
757
- https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
758
- """
759
-
760
- def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
761
- super().__init__()
762
-
763
- self.outdim = size_emb_dim
764
- self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
765
- self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
766
-
767
- self.use_additional_conditions = use_additional_conditions
768
- if use_additional_conditions:
769
- self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
770
- self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
771
- self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
772
-
773
- def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
774
- timesteps_proj = self.time_proj(timestep)
775
- timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
776
-
777
- if self.use_additional_conditions:
778
- resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
779
- resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
780
- aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
781
- aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
782
- conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
783
- else:
784
- conditioning = timesteps_emb
785
-
786
- return conditioning
787
-
788
-
789
- class PixArtAlphaTextProjection(nn.Module):
790
- """
791
- Projects caption embeddings. Also handles dropout for classifier-free guidance.
792
-
793
- Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
794
- """
795
-
796
- def __init__(self, in_features, hidden_size, num_tokens=120):
797
- super().__init__()
798
- self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
799
- self.act_1 = nn.GELU(approximate="tanh")
800
- self.linear_2 = nn.Linear(in_features=hidden_size, out_features=hidden_size, bias=True)
801
-
802
- def forward(self, caption):
803
- hidden_states = self.linear_1(caption)
804
- hidden_states = self.act_1(hidden_states)
805
- hidden_states = self.linear_2(hidden_states)
806
- return hidden_states
807
-
808
-
809
- class IPAdapterPlusImageProjection(nn.Module):
810
- """Resampler of IP-Adapter Plus.
811
-
812
- Args:
813
- embed_dims (int): The feature dimension. Defaults to 768. output_dims (int): The number of output channels,
814
- that is the same
815
- number of the channels in the `unet.config.cross_attention_dim`. Defaults to 1024.
816
- hidden_dims (int):
817
- The number of hidden channels. Defaults to 1280. depth (int): The number of blocks. Defaults
818
- to 8. dim_head (int): The number of head channels. Defaults to 64. heads (int): Parallel attention heads.
819
- Defaults to 16. num_queries (int):
820
- The number of queries. Defaults to 8. ffn_ratio (float): The expansion ratio
821
- of feedforward network hidden
822
- layer channels. Defaults to 4.
823
- """
824
-
825
- def __init__(
826
- self,
827
- embed_dims: int = 768,
828
- output_dims: int = 1024,
829
- hidden_dims: int = 1280,
830
- depth: int = 4,
831
- dim_head: int = 64,
832
- heads: int = 16,
833
- num_queries: int = 8,
834
- ffn_ratio: float = 4,
835
- ) -> None:
836
- super().__init__()
837
- from .attention import FeedForward # Lazy import to avoid circular import
838
-
839
- self.latents = nn.Parameter(torch.randn(1, num_queries, hidden_dims) / hidden_dims**0.5)
840
-
841
- self.proj_in = nn.Linear(embed_dims, hidden_dims)
842
-
843
- self.proj_out = nn.Linear(hidden_dims, output_dims)
844
- self.norm_out = nn.LayerNorm(output_dims)
845
-
846
- self.layers = nn.ModuleList([])
847
- for _ in range(depth):
848
- self.layers.append(
849
- nn.ModuleList(
850
- [
851
- nn.LayerNorm(hidden_dims),
852
- nn.LayerNorm(hidden_dims),
853
- Attention(
854
- query_dim=hidden_dims,
855
- dim_head=dim_head,
856
- heads=heads,
857
- out_bias=False,
858
- ),
859
- nn.Sequential(
860
- nn.LayerNorm(hidden_dims),
861
- FeedForward(hidden_dims, hidden_dims, activation_fn="gelu", mult=ffn_ratio, bias=False),
862
- ),
863
- ]
864
- )
865
- )
866
-
867
- def forward(self, x: torch.Tensor) -> torch.Tensor:
868
- """Forward pass.
869
-
870
- Args:
871
- x (torch.Tensor): Input Tensor.
872
- Returns:
873
- torch.Tensor: Output Tensor.
874
- """
875
- latents = self.latents.repeat(x.size(0), 1, 1)
876
-
877
- x = self.proj_in(x)
878
-
879
- for ln0, ln1, attn, ff in self.layers:
880
- residual = latents
881
-
882
- encoder_hidden_states = ln0(x)
883
- latents = ln1(latents)
884
- encoder_hidden_states = torch.cat([encoder_hidden_states, latents], dim=-2)
885
- latents = attn(latents, encoder_hidden_states) + residual
886
- latents = ff(latents) + latents
887
-
888
- latents = self.proj_out(latents)
889
- return self.norm_out(latents)
890
-
891
-
892
- class IPAdapterPlusImageProjectionBlock(nn.Module):
893
- def __init__(
894
- self,
895
- embed_dims: int = 768,
896
- dim_head: int = 64,
897
- heads: int = 16,
898
- ffn_ratio: float = 4,
899
- ) -> None:
900
- super().__init__()
901
- from .attention import FeedForward
902
-
903
- self.ln0 = nn.LayerNorm(embed_dims)
904
- self.ln1 = nn.LayerNorm(embed_dims)
905
- self.attn = Attention(
906
- query_dim=embed_dims,
907
- dim_head=dim_head,
908
- heads=heads,
909
- out_bias=False,
910
- )
911
- self.ff = nn.Sequential(
912
- nn.LayerNorm(embed_dims),
913
- FeedForward(embed_dims, embed_dims, activation_fn="gelu", mult=ffn_ratio, bias=False),
914
- )
915
-
916
- def forward(self, x, latents, residual):
917
- encoder_hidden_states = self.ln0(x)
918
- latents = self.ln1(latents)
919
- encoder_hidden_states = torch.cat([encoder_hidden_states, latents], dim=-2)
920
- latents = self.attn(latents, encoder_hidden_states) + residual
921
- latents = self.ff(latents) + latents
922
- return latents
923
-
924
-
925
- class IPAdapterFaceIDPlusImageProjection(nn.Module):
926
- """FacePerceiverResampler of IP-Adapter Plus.
927
-
928
- Args:
929
- embed_dims (int): The feature dimension. Defaults to 768. output_dims (int): The number of output channels,
930
- that is the same
931
- number of the channels in the `unet.config.cross_attention_dim`. Defaults to 1024.
932
- hidden_dims (int):
933
- The number of hidden channels. Defaults to 1280. depth (int): The number of blocks. Defaults
934
- to 8. dim_head (int): The number of head channels. Defaults to 64. heads (int): Parallel attention heads.
935
- Defaults to 16. num_tokens (int): Number of tokens num_queries (int): The number of queries. Defaults to 8.
936
- ffn_ratio (float): The expansion ratio of feedforward network hidden
937
- layer channels. Defaults to 4.
938
- ffproj_ratio (float): The expansion ratio of feedforward network hidden
939
- layer channels (for ID embeddings). Defaults to 4.
940
- """
941
-
942
- def __init__(
943
- self,
944
- embed_dims: int = 768,
945
- output_dims: int = 768,
946
- hidden_dims: int = 1280,
947
- id_embeddings_dim: int = 512,
948
- depth: int = 4,
949
- dim_head: int = 64,
950
- heads: int = 16,
951
- num_tokens: int = 4,
952
- num_queries: int = 8,
953
- ffn_ratio: float = 4,
954
- ffproj_ratio: int = 2,
955
- ) -> None:
956
- super().__init__()
957
- from .attention import FeedForward
958
-
959
- self.num_tokens = num_tokens
960
- self.embed_dim = embed_dims
961
- self.clip_embeds = None
962
- self.shortcut = False
963
- self.shortcut_scale = 1.0
964
-
965
- self.proj = FeedForward(id_embeddings_dim, embed_dims * num_tokens, activation_fn="gelu", mult=ffproj_ratio)
966
- self.norm = nn.LayerNorm(embed_dims)
967
-
968
- self.proj_in = nn.Linear(hidden_dims, embed_dims)
969
-
970
- self.proj_out = nn.Linear(embed_dims, output_dims)
971
- self.norm_out = nn.LayerNorm(output_dims)
972
-
973
- self.layers = nn.ModuleList(
974
- [IPAdapterPlusImageProjectionBlock(embed_dims, dim_head, heads, ffn_ratio) for _ in range(depth)]
975
- )
976
-
977
- def forward(self, id_embeds: torch.Tensor) -> torch.Tensor:
978
- """Forward pass.
979
-
980
- Args:
981
- id_embeds (torch.Tensor): Input Tensor (ID embeds).
982
- Returns:
983
- torch.Tensor: Output Tensor.
984
- """
985
- id_embeds = id_embeds.to(self.clip_embeds.dtype)
986
- id_embeds = self.proj(id_embeds)
987
- id_embeds = id_embeds.reshape(-1, self.num_tokens, self.embed_dim)
988
- id_embeds = self.norm(id_embeds)
989
- latents = id_embeds
990
-
991
- clip_embeds = self.proj_in(self.clip_embeds)
992
- x = clip_embeds.reshape(-1, clip_embeds.shape[2], clip_embeds.shape[3])
993
-
994
- for block in self.layers:
995
- residual = latents
996
- latents = block(x, latents, residual)
997
-
998
- latents = self.proj_out(latents)
999
- out = self.norm_out(latents)
1000
- if self.shortcut:
1001
- out = id_embeds + self.shortcut_scale * out
1002
- return out
1003
-
1004
-
1005
- class MultiIPAdapterImageProjection(nn.Module):
1006
- def __init__(self, IPAdapterImageProjectionLayers: Union[List[nn.Module], Tuple[nn.Module]]):
1007
- super().__init__()
1008
- self.image_projection_layers = nn.ModuleList(IPAdapterImageProjectionLayers)
1009
-
1010
- def forward(self, image_embeds: List[torch.FloatTensor]):
1011
- projected_image_embeds = []
1012
-
1013
- # currently, we accept `image_embeds` as
1014
- # 1. a tensor (deprecated) with shape [batch_size, embed_dim] or [batch_size, sequence_length, embed_dim]
1015
- # 2. list of `n` tensors where `n` is number of ip-adapters, each tensor can hae shape [batch_size, num_images, embed_dim] or [batch_size, num_images, sequence_length, embed_dim]
1016
- if not isinstance(image_embeds, list):
1017
- deprecation_message = (
1018
- "You have passed a tensor as `image_embeds`.This is deprecated and will be removed in a future release."
1019
- " Please make sure to update your script to pass `image_embeds` as a list of tensors to supress this warning."
1020
- )
1021
- deprecate("image_embeds not a list", "1.0.0", deprecation_message, standard_warn=False)
1022
- image_embeds = [image_embeds.unsqueeze(1)]
1023
-
1024
- if len(image_embeds) != len(self.image_projection_layers):
1025
- raise ValueError(
1026
- f"image_embeds must have the same length as image_projection_layers, got {len(image_embeds)} and {len(self.image_projection_layers)}"
1027
- )
1028
-
1029
- for image_embed, image_projection_layer in zip(image_embeds, self.image_projection_layers):
1030
- batch_size, num_images = image_embed.shape[0], image_embed.shape[1]
1031
- image_embed = image_embed.reshape((batch_size * num_images,) + image_embed.shape[2:])
1032
- image_embed = image_projection_layer(image_embed)
1033
- image_embed = image_embed.reshape((batch_size, num_images) + image_embed.shape[1:])
1034
-
1035
- projected_image_embeds.append(image_embed)
1036
-
1037
- return projected_image_embeds
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/embeddings_flax.py DELETED
@@ -1,97 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
- import 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 DELETED
@@ -1,457 +0,0 @@
1
- # Copyright 2024 The HuggingFace Team. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
-
16
- # 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 deprecate, 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
- deprecation_message = "Use of `PatchedLoraProjection` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
86
- deprecate("PatchedLoraProjection", "1.0.0", deprecation_message)
87
-
88
- super().__init__()
89
- from ..models.lora import LoRALinearLayer
90
-
91
- self.regular_linear_layer = regular_linear_layer
92
-
93
- device = self.regular_linear_layer.weight.device
94
-
95
- if dtype is None:
96
- dtype = self.regular_linear_layer.weight.dtype
97
-
98
- self.lora_linear_layer = LoRALinearLayer(
99
- self.regular_linear_layer.in_features,
100
- self.regular_linear_layer.out_features,
101
- network_alpha=network_alpha,
102
- device=device,
103
- dtype=dtype,
104
- rank=rank,
105
- )
106
-
107
- self.lora_scale = lora_scale
108
-
109
- # overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved
110
- # when saving the whole text encoder model and when LoRA is unloaded or fused
111
- def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
112
- if self.lora_linear_layer is None:
113
- return self.regular_linear_layer.state_dict(
114
- *args, destination=destination, prefix=prefix, keep_vars=keep_vars
115
- )
116
-
117
- return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
118
-
119
- def _fuse_lora(self, lora_scale=1.0, safe_fusing=False):
120
- if self.lora_linear_layer is None:
121
- return
122
-
123
- dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device
124
-
125
- w_orig = self.regular_linear_layer.weight.data.float()
126
- w_up = self.lora_linear_layer.up.weight.data.float()
127
- w_down = self.lora_linear_layer.down.weight.data.float()
128
-
129
- if self.lora_linear_layer.network_alpha is not None:
130
- w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank
131
-
132
- fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
133
-
134
- if safe_fusing and torch.isnan(fused_weight).any().item():
135
- raise ValueError(
136
- "This LoRA weight seems to be broken. "
137
- f"Encountered NaN values when trying to fuse LoRA weights for {self}."
138
- "LoRA weights will not be fused."
139
- )
140
-
141
- self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype)
142
-
143
- # we can drop the lora layer now
144
- self.lora_linear_layer = None
145
-
146
- # offload the up and down matrices to CPU to not blow the memory
147
- self.w_up = w_up.cpu()
148
- self.w_down = w_down.cpu()
149
- self.lora_scale = lora_scale
150
-
151
- def _unfuse_lora(self):
152
- if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
153
- return
154
-
155
- fused_weight = self.regular_linear_layer.weight.data
156
- dtype, device = fused_weight.dtype, fused_weight.device
157
-
158
- w_up = self.w_up.to(device=device).float()
159
- w_down = self.w_down.to(device).float()
160
-
161
- unfused_weight = fused_weight.float() - (self.lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
162
- self.regular_linear_layer.weight.data = unfused_weight.to(device=device, dtype=dtype)
163
-
164
- self.w_up = None
165
- self.w_down = None
166
-
167
- def forward(self, input):
168
- if self.lora_scale is None:
169
- self.lora_scale = 1.0
170
- if self.lora_linear_layer is None:
171
- return self.regular_linear_layer(input)
172
- return self.regular_linear_layer(input) + (self.lora_scale * self.lora_linear_layer(input))
173
-
174
-
175
- class LoRALinearLayer(nn.Module):
176
- r"""
177
- A linear layer that is used with LoRA.
178
-
179
- Parameters:
180
- in_features (`int`):
181
- Number of input features.
182
- out_features (`int`):
183
- Number of output features.
184
- rank (`int`, `optional`, defaults to 4):
185
- The rank of the LoRA layer.
186
- network_alpha (`float`, `optional`, defaults to `None`):
187
- The value of the network alpha used for stable learning and preventing underflow. This value has the same
188
- meaning as the `--network_alpha` option in the kohya-ss trainer script. See
189
- https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
190
- device (`torch.device`, `optional`, defaults to `None`):
191
- The device to use for the layer's weights.
192
- dtype (`torch.dtype`, `optional`, defaults to `None`):
193
- The dtype to use for the layer's weights.
194
- """
195
-
196
- def __init__(
197
- self,
198
- in_features: int,
199
- out_features: int,
200
- rank: int = 4,
201
- network_alpha: Optional[float] = None,
202
- device: Optional[Union[torch.device, str]] = None,
203
- dtype: Optional[torch.dtype] = None,
204
- ):
205
- super().__init__()
206
-
207
- deprecation_message = "Use of `LoRALinearLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
208
- deprecate("LoRALinearLayer", "1.0.0", deprecation_message)
209
-
210
- self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
211
- self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
212
- # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
213
- # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
214
- self.network_alpha = network_alpha
215
- self.rank = rank
216
- self.out_features = out_features
217
- self.in_features = in_features
218
-
219
- nn.init.normal_(self.down.weight, std=1 / rank)
220
- nn.init.zeros_(self.up.weight)
221
-
222
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
223
- orig_dtype = hidden_states.dtype
224
- dtype = self.down.weight.dtype
225
-
226
- down_hidden_states = self.down(hidden_states.to(dtype))
227
- up_hidden_states = self.up(down_hidden_states)
228
-
229
- if self.network_alpha is not None:
230
- up_hidden_states *= self.network_alpha / self.rank
231
-
232
- return up_hidden_states.to(orig_dtype)
233
-
234
-
235
- class LoRAConv2dLayer(nn.Module):
236
- r"""
237
- A convolutional layer that is used with LoRA.
238
-
239
- Parameters:
240
- in_features (`int`):
241
- Number of input features.
242
- out_features (`int`):
243
- Number of output features.
244
- rank (`int`, `optional`, defaults to 4):
245
- The rank of the LoRA layer.
246
- kernel_size (`int` or `tuple` of two `int`, `optional`, defaults to 1):
247
- The kernel size of the convolution.
248
- stride (`int` or `tuple` of two `int`, `optional`, defaults to 1):
249
- The stride of the convolution.
250
- padding (`int` or `tuple` of two `int` or `str`, `optional`, defaults to 0):
251
- The padding of the convolution.
252
- network_alpha (`float`, `optional`, defaults to `None`):
253
- The value of the network alpha used for stable learning and preventing underflow. This value has the same
254
- meaning as the `--network_alpha` option in the kohya-ss trainer script. See
255
- https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
256
- """
257
-
258
- def __init__(
259
- self,
260
- in_features: int,
261
- out_features: int,
262
- rank: int = 4,
263
- kernel_size: Union[int, Tuple[int, int]] = (1, 1),
264
- stride: Union[int, Tuple[int, int]] = (1, 1),
265
- padding: Union[int, Tuple[int, int], str] = 0,
266
- network_alpha: Optional[float] = None,
267
- ):
268
- super().__init__()
269
-
270
- deprecation_message = "Use of `LoRAConv2dLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
271
- deprecate("LoRAConv2dLayer", "1.0.0", deprecation_message)
272
-
273
- self.down = nn.Conv2d(in_features, rank, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
274
- # according to the official kohya_ss trainer kernel_size are always fixed for the up layer
275
- # # see: https://github.com/bmaltais/kohya_ss/blob/2accb1305979ba62f5077a23aabac23b4c37e935/networks/lora_diffusers.py#L129
276
- self.up = nn.Conv2d(rank, out_features, kernel_size=(1, 1), stride=(1, 1), bias=False)
277
-
278
- # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
279
- # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
280
- self.network_alpha = network_alpha
281
- self.rank = rank
282
-
283
- nn.init.normal_(self.down.weight, std=1 / rank)
284
- nn.init.zeros_(self.up.weight)
285
-
286
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
287
- orig_dtype = hidden_states.dtype
288
- dtype = self.down.weight.dtype
289
-
290
- down_hidden_states = self.down(hidden_states.to(dtype))
291
- up_hidden_states = self.up(down_hidden_states)
292
-
293
- if self.network_alpha is not None:
294
- up_hidden_states *= self.network_alpha / self.rank
295
-
296
- return up_hidden_states.to(orig_dtype)
297
-
298
-
299
- class LoRACompatibleConv(nn.Conv2d):
300
- """
301
- A convolutional layer that can be used with LoRA.
302
- """
303
-
304
- def __init__(self, *args, lora_layer: Optional[LoRAConv2dLayer] = None, **kwargs):
305
- deprecation_message = "Use of `LoRACompatibleConv` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
306
- deprecate("LoRACompatibleConv", "1.0.0", deprecation_message)
307
-
308
- super().__init__(*args, **kwargs)
309
- self.lora_layer = lora_layer
310
-
311
- def set_lora_layer(self, lora_layer: Optional[LoRAConv2dLayer]):
312
- deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
313
- deprecate("set_lora_layer", "1.0.0", deprecation_message)
314
-
315
- self.lora_layer = lora_layer
316
-
317
- def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
318
- if self.lora_layer is None:
319
- return
320
-
321
- dtype, device = self.weight.data.dtype, self.weight.data.device
322
-
323
- w_orig = self.weight.data.float()
324
- w_up = self.lora_layer.up.weight.data.float()
325
- w_down = self.lora_layer.down.weight.data.float()
326
-
327
- if self.lora_layer.network_alpha is not None:
328
- w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
329
-
330
- fusion = torch.mm(w_up.flatten(start_dim=1), w_down.flatten(start_dim=1))
331
- fusion = fusion.reshape((w_orig.shape))
332
- fused_weight = w_orig + (lora_scale * fusion)
333
-
334
- if safe_fusing and torch.isnan(fused_weight).any().item():
335
- raise ValueError(
336
- "This LoRA weight seems to be broken. "
337
- f"Encountered NaN values when trying to fuse LoRA weights for {self}."
338
- "LoRA weights will not be fused."
339
- )
340
-
341
- self.weight.data = fused_weight.to(device=device, dtype=dtype)
342
-
343
- # we can drop the lora layer now
344
- self.lora_layer = None
345
-
346
- # offload the up and down matrices to CPU to not blow the memory
347
- self.w_up = w_up.cpu()
348
- self.w_down = w_down.cpu()
349
- self._lora_scale = lora_scale
350
-
351
- def _unfuse_lora(self):
352
- if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
353
- return
354
-
355
- fused_weight = self.weight.data
356
- dtype, device = fused_weight.data.dtype, fused_weight.data.device
357
-
358
- self.w_up = self.w_up.to(device=device).float()
359
- self.w_down = self.w_down.to(device).float()
360
-
361
- fusion = torch.mm(self.w_up.flatten(start_dim=1), self.w_down.flatten(start_dim=1))
362
- fusion = fusion.reshape((fused_weight.shape))
363
- unfused_weight = fused_weight.float() - (self._lora_scale * fusion)
364
- self.weight.data = unfused_weight.to(device=device, dtype=dtype)
365
-
366
- self.w_up = None
367
- self.w_down = None
368
-
369
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
370
- if self.padding_mode != "zeros":
371
- hidden_states = F.pad(hidden_states, self._reversed_padding_repeated_twice, mode=self.padding_mode)
372
- padding = (0, 0)
373
- else:
374
- padding = self.padding
375
-
376
- original_outputs = F.conv2d(
377
- hidden_states, self.weight, self.bias, self.stride, padding, self.dilation, self.groups
378
- )
379
-
380
- if self.lora_layer is None:
381
- return original_outputs
382
- else:
383
- return original_outputs + (scale * self.lora_layer(hidden_states))
384
-
385
-
386
- class LoRACompatibleLinear(nn.Linear):
387
- """
388
- A Linear layer that can be used with LoRA.
389
- """
390
-
391
- def __init__(self, *args, lora_layer: Optional[LoRALinearLayer] = None, **kwargs):
392
- deprecation_message = "Use of `LoRACompatibleLinear` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
393
- deprecate("LoRACompatibleLinear", "1.0.0", deprecation_message)
394
-
395
- super().__init__(*args, **kwargs)
396
- self.lora_layer = lora_layer
397
-
398
- def set_lora_layer(self, lora_layer: Optional[LoRALinearLayer]):
399
- deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
400
- deprecate("set_lora_layer", "1.0.0", deprecation_message)
401
- self.lora_layer = lora_layer
402
-
403
- def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
404
- if self.lora_layer is None:
405
- return
406
-
407
- dtype, device = self.weight.data.dtype, self.weight.data.device
408
-
409
- w_orig = self.weight.data.float()
410
- w_up = self.lora_layer.up.weight.data.float()
411
- w_down = self.lora_layer.down.weight.data.float()
412
-
413
- if self.lora_layer.network_alpha is not None:
414
- w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
415
-
416
- fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
417
-
418
- if safe_fusing and torch.isnan(fused_weight).any().item():
419
- raise ValueError(
420
- "This LoRA weight seems to be broken. "
421
- f"Encountered NaN values when trying to fuse LoRA weights for {self}."
422
- "LoRA weights will not be fused."
423
- )
424
-
425
- self.weight.data = fused_weight.to(device=device, dtype=dtype)
426
-
427
- # we can drop the lora layer now
428
- self.lora_layer = None
429
-
430
- # offload the up and down matrices to CPU to not blow the memory
431
- self.w_up = w_up.cpu()
432
- self.w_down = w_down.cpu()
433
- self._lora_scale = lora_scale
434
-
435
- def _unfuse_lora(self):
436
- if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
437
- return
438
-
439
- fused_weight = self.weight.data
440
- dtype, device = fused_weight.dtype, fused_weight.device
441
-
442
- w_up = self.w_up.to(device=device).float()
443
- w_down = self.w_down.to(device).float()
444
-
445
- unfused_weight = fused_weight.float() - (self._lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
446
- self.weight.data = unfused_weight.to(device=device, dtype=dtype)
447
-
448
- self.w_up = None
449
- self.w_down = None
450
-
451
- def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
452
- if self.lora_layer is None:
453
- out = super().forward(hidden_states)
454
- return out
455
- else:
456
- out = super().forward(hidden_states) + (scale * self.lora_layer(hidden_states))
457
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diffusers/models/modeling_flax_pytorch_utils.py DELETED
@@ -1,135 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024 The HuggingFace Inc. team.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """PyTorch - Flax general utilities."""
16
-
17
- import re
18
-
19
- import jax.numpy as jnp
20
- from flax.traverse_util import flatten_dict, unflatten_dict
21
- from jax.random import PRNGKey
22
-
23
- from ..utils import logging
24
-
25
-
26
- logger = logging.get_logger(__name__)
27
-
28
-
29
- def rename_key(key):
30
- regex = r"\w+[.]\d+"
31
- pats = re.findall(regex, key)
32
- for pat in pats:
33
- key = key.replace(pat, "_".join(pat.split(".")))
34
- return key
35
-
36
-
37
- #####################
38
- # PyTorch => Flax #
39
- #####################
40
-
41
-
42
- # Adapted from https://github.com/huggingface/transformers/blob/c603c80f46881ae18b2ca50770ef65fa4033eacd/src/transformers/modeling_flax_pytorch_utils.py#L69
43
- # and https://github.com/patil-suraj/stable-diffusion-jax/blob/main/stable_diffusion_jax/convert_diffusers_to_jax.py
44
- def rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict):
45
- """Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
46
- # conv norm or layer norm
47
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
48
-
49
- # rename attention layers
50
- if len(pt_tuple_key) > 1:
51
- for rename_from, rename_to in (
52
- ("to_out_0", "proj_attn"),
53
- ("to_k", "key"),
54
- ("to_v", "value"),
55
- ("to_q", "query"),
56
- ):
57
- if pt_tuple_key[-2] == rename_from:
58
- weight_name = pt_tuple_key[-1]
59
- weight_name = "kernel" if weight_name == "weight" else weight_name
60
- renamed_pt_tuple_key = pt_tuple_key[:-2] + (rename_to, weight_name)
61
- if renamed_pt_tuple_key in random_flax_state_dict:
62
- assert random_flax_state_dict[renamed_pt_tuple_key].shape == pt_tensor.T.shape
63
- return renamed_pt_tuple_key, pt_tensor.T
64
-
65
- if (
66
- any("norm" in str_ for str_ in pt_tuple_key)
67
- and (pt_tuple_key[-1] == "bias")
68
- and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
69
- and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
70
- ):
71
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
72
- return renamed_pt_tuple_key, pt_tensor
73
- elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
74
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
75
- return renamed_pt_tuple_key, pt_tensor
76
-
77
- # embedding
78
- if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
79
- pt_tuple_key = pt_tuple_key[:-1] + ("embedding",)
80
- return renamed_pt_tuple_key, pt_tensor
81
-
82
- # conv layer
83
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
84
- if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
85
- pt_tensor = pt_tensor.transpose(2, 3, 1, 0)
86
- return renamed_pt_tuple_key, pt_tensor
87
-
88
- # linear layer
89
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
90
- if pt_tuple_key[-1] == "weight":
91
- pt_tensor = pt_tensor.T
92
- return renamed_pt_tuple_key, pt_tensor
93
-
94
- # old PyTorch layer norm weight
95
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",)
96
- if pt_tuple_key[-1] == "gamma":
97
- return renamed_pt_tuple_key, pt_tensor
98
-
99
- # old PyTorch layer norm bias
100
- renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",)
101
- if pt_tuple_key[-1] == "beta":
102
- return renamed_pt_tuple_key, pt_tensor
103
-
104
- return pt_tuple_key, pt_tensor
105
-
106
-
107
- def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model, init_key=42):
108
- # Step 1: Convert pytorch tensor to numpy
109
- pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
110
-
111
- # Step 2: Since the model is stateless, get random Flax params
112
- random_flax_params = flax_model.init_weights(PRNGKey(init_key))
113
-
114
- random_flax_state_dict = flatten_dict(random_flax_params)
115
- flax_state_dict = {}
116
-
117
- # Need to change some parameters name to match Flax names
118
- for pt_key, pt_tensor in pt_state_dict.items():
119
- renamed_pt_key = rename_key(pt_key)
120
- pt_tuple_key = tuple(renamed_pt_key.split("."))
121
-
122
- # Correctly rename weight parameters
123
- flax_key, flax_tensor = rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict)
124
-
125
- if flax_key in random_flax_state_dict:
126
- if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
127
- raise ValueError(
128
- f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
129
- f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
130
- )
131
-
132
- # also add unexpected weight so that warning is thrown
133
- flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
134
-
135
- return unflatten_dict(flax_state_dict)