jiuface commited on
Commit
0611e52
1 Parent(s): 96564c7
Files changed (37) hide show
  1. __pycache__/controlnet_flux.cpython-310.pyc +0 -0
  2. __pycache__/cv_utils.cpython-310.pyc +0 -0
  3. __pycache__/depth_estimator.cpython-310.pyc +0 -0
  4. __pycache__/image_segmentor.cpython-310.pyc +0 -0
  5. __pycache__/pipeline_flux_controlnet_inpaint.cpython-310.pyc +0 -0
  6. __pycache__/preprocessor.cpython-310.pyc +0 -0
  7. __pycache__/transformer_flux.cpython-310.pyc +0 -0
  8. app.py +80 -31
  9. controlnet_flux.py +0 -418
  10. depth_anything_v2/__pycache__/dinov2.cpython-310.pyc +0 -0
  11. depth_anything_v2/__pycache__/dpt.cpython-310.pyc +0 -0
  12. depth_anything_v2/dinov2.py +415 -0
  13. depth_anything_v2/dinov2_layers/__init__.py +11 -0
  14. depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-310.pyc +0 -0
  15. depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-310.pyc +0 -0
  16. depth_anything_v2/dinov2_layers/__pycache__/block.cpython-310.pyc +0 -0
  17. depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-310.pyc +0 -0
  18. depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-310.pyc +0 -0
  19. depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-310.pyc +0 -0
  20. depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-310.pyc +0 -0
  21. depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-310.pyc +0 -0
  22. depth_anything_v2/dinov2_layers/attention.py +81 -0
  23. depth_anything_v2/dinov2_layers/block.py +252 -0
  24. depth_anything_v2/dinov2_layers/drop_path.py +35 -0
  25. depth_anything_v2/dinov2_layers/layer_scale.py +28 -0
  26. depth_anything_v2/dinov2_layers/mlp.py +41 -0
  27. depth_anything_v2/dinov2_layers/patch_embed.py +88 -0
  28. depth_anything_v2/dinov2_layers/swiglu_ffn.py +63 -0
  29. depth_anything_v2/dpt.py +221 -0
  30. depth_anything_v2/util/__pycache__/blocks.cpython-310.pyc +0 -0
  31. depth_anything_v2/util/__pycache__/transform.cpython-310.pyc +0 -0
  32. depth_anything_v2/util/blocks.py +144 -0
  33. depth_anything_v2/util/transform.py +157 -0
  34. pipeline_flux_controlnet_inpaint.py +0 -1046
  35. preprocessor.py +1 -1
  36. requirements.txt +1 -1
  37. transformer_flux.py +0 -525
__pycache__/controlnet_flux.cpython-310.pyc CHANGED
Binary files a/__pycache__/controlnet_flux.cpython-310.pyc and b/__pycache__/controlnet_flux.cpython-310.pyc differ
 
__pycache__/cv_utils.cpython-310.pyc CHANGED
Binary files a/__pycache__/cv_utils.cpython-310.pyc and b/__pycache__/cv_utils.cpython-310.pyc differ
 
__pycache__/depth_estimator.cpython-310.pyc CHANGED
Binary files a/__pycache__/depth_estimator.cpython-310.pyc and b/__pycache__/depth_estimator.cpython-310.pyc differ
 
__pycache__/image_segmentor.cpython-310.pyc CHANGED
Binary files a/__pycache__/image_segmentor.cpython-310.pyc and b/__pycache__/image_segmentor.cpython-310.pyc differ
 
__pycache__/pipeline_flux_controlnet_inpaint.cpython-310.pyc CHANGED
Binary files a/__pycache__/pipeline_flux_controlnet_inpaint.cpython-310.pyc and b/__pycache__/pipeline_flux_controlnet_inpaint.cpython-310.pyc differ
 
__pycache__/preprocessor.cpython-310.pyc CHANGED
Binary files a/__pycache__/preprocessor.cpython-310.pyc and b/__pycache__/preprocessor.cpython-310.pyc differ
 
__pycache__/transformer_flux.cpython-310.pyc CHANGED
Binary files a/__pycache__/transformer_flux.cpython-310.pyc and b/__pycache__/transformer_flux.cpython-310.pyc differ
 
app.py CHANGED
@@ -5,9 +5,12 @@ import numpy as np
5
  import random
6
  import spaces
7
  import cv2
 
 
8
  import torch
9
  from PIL import Image, ImageFilter
10
  from huggingface_hub import login
 
11
  from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
12
  import copy
13
  import random
@@ -16,56 +19,60 @@ import boto3
16
  from io import BytesIO
17
  from datetime import datetime
18
  from diffusers.utils import load_image, make_image_grid
19
- import json
20
- from controlnet_flux import FluxControlNetModel
21
- from transformer_flux import FluxTransformer2DModel
22
- from pipeline_flux_controlnet_inpaint import FluxControlNetInpaintingPipeline
23
 
 
 
 
 
24
 
25
  HF_TOKEN = os.environ.get("HF_TOKEN")
26
 
27
  login(token=HF_TOKEN)
28
 
29
  MAX_SEED = np.iinfo(np.int32).max
30
- IMAGE_SIZE = 1024
31
 
32
  # init
33
  device = "cuda" if torch.cuda.is_available() else "cpu"
34
  base_model = "black-forest-labs/FLUX.1-dev"
35
 
36
- controlnet = FluxControlNetModel.from_pretrained("alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Alpha", torch_dtype=torch.bfloat16)
37
- transformer = FluxTransformer2DModel.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder='transformer', torch_dytpe=torch.bfloat16)
 
 
 
38
 
39
- pipe = FluxControlNetInpaintingPipeline.from_pretrained(
40
- base_model,
41
- controlnet=controlnet,
42
- transformer=transformer,
43
- torch_dtype=torch.bfloat16).to(device)
44
 
 
 
 
 
 
 
 
 
 
45
 
46
  def clear_cuda_cache():
47
  torch.cuda.empty_cache()
48
 
 
49
  class calculateDuration:
50
  def __init__(self, activity_name=""):
51
  self.activity_name = activity_name
52
 
53
  def __enter__(self):
54
  self.start_time = time.time()
55
- self.start_time_formatted = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.start_time))
56
- print(f"Activity: {self.activity_name}, Start time: {self.start_time_formatted}")
57
  return self
58
 
59
  def __exit__(self, exc_type, exc_value, traceback):
60
  self.end_time = time.time()
61
  self.elapsed_time = self.end_time - self.start_time
62
- self.end_time_formatted = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(self.end_time))
63
-
64
  if self.activity_name:
65
  print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
66
  else:
67
  print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
68
-
69
 
70
 
71
  def calculate_image_dimensions_for_flux(
@@ -140,6 +147,8 @@ def upload_image_to_r2(image, account_id, access_key, secret_key, bucket_name):
140
  def run_flux(
141
  image: Image.Image,
142
  mask: Image.Image,
 
 
143
  prompt: str,
144
  seed_slicer: int,
145
  randomize_seed_checkbox: bool,
@@ -148,37 +157,41 @@ def run_flux(
148
  resolution_wh: Tuple[int, int],
149
  progress
150
  ) -> Image.Image:
 
 
 
 
 
151
 
152
  with calculateDuration("run pipe"):
153
- print("start to run pipe", prompt, control_mode)
154
- # pipe.to(device)
155
- width, height = resolution_wh
156
- if randomize_seed_checkbox:
157
- seed_slicer = random.randint(0, MAX_SEED)
158
- generator = torch.Generator().manual_seed(seed_slicer)
159
  with torch.inference_mode():
160
  generated_image = pipe(
161
  prompt=prompt,
 
162
  mask_image=mask,
163
- control_image=image,
164
- controlnet_conditioning_scale=0.9,
 
165
  width=width,
166
  height=height,
167
- strength=0.7,
168
- guidance_scale=3.5,
169
  generator=generator,
170
- num_inference_steps=28,
171
  ).images[0]
172
  progress(99, "Generate image success!")
173
  return generated_image
174
 
175
 
176
  def load_loras(lora_strings_json:str):
 
177
  if lora_strings_json:
178
  try:
179
  lora_configs = json.loads(lora_strings_json)
180
  except:
181
- lora_configs = None
 
182
  if lora_configs:
183
  with calculateDuration("Loading LoRA weights"):
184
  pipe.unload_lora_weights()
@@ -198,12 +211,43 @@ def load_loras(lora_strings_json:str):
198
  pipe.set_adapters(adapter_names, adapter_weights=adapter_weights)
199
 
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  def process(
202
  image_url: str,
203
  mask_url: str,
204
  inpainting_prompt_text: str,
205
  mask_inflation_slider: int,
206
  mask_blur_slider: int,
 
207
  seed_slicer: int,
208
  randomize_seed_checkbox: bool,
209
  strength_slider: float,
@@ -245,13 +289,18 @@ def process(
245
  mask = mask.resize((width, height), Image.LANCZOS)
246
  mask = process_mask(mask, mask_inflation=mask_inflation_slider, mask_blur=mask_blur_slider)
247
 
248
- # load loras
 
 
 
249
  load_loras(lora_strings_json=lora_strings_json)
250
 
251
  try:
252
  generated_image = run_flux(
253
  image=image,
254
  mask=mask,
 
 
255
  prompt=inpainting_prompt_text,
256
  seed_slicer=seed_slicer,
257
  randomize_seed_checkbox=randomize_seed_checkbox,
@@ -422,4 +471,4 @@ with gr.Blocks() as demo:
422
  )
423
 
424
  demo.queue(api_open=False)
425
- demo.launch()
 
5
  import random
6
  import spaces
7
  import cv2
8
+ from diffusers import DiffusionPipeline
9
+ from diffusers import FluxInpaintPipeline
10
  import torch
11
  from PIL import Image, ImageFilter
12
  from huggingface_hub import login
13
+ from diffusers import AutoencoderTiny, AutoencoderKL
14
  from huggingface_hub import hf_hub_download, HfFileSystem, ModelCard, snapshot_download
15
  import copy
16
  import random
 
19
  from io import BytesIO
20
  from datetime import datetime
21
  from diffusers.utils import load_image, make_image_grid
 
 
 
 
22
 
23
+ import json
24
+ from preprocessor import Preprocessor
25
+ from diffusers import FluxControlNetInpaintPipeline
26
+ from diffusers.models import FluxControlNetModel
27
 
28
  HF_TOKEN = os.environ.get("HF_TOKEN")
29
 
30
  login(token=HF_TOKEN)
31
 
32
  MAX_SEED = np.iinfo(np.int32).max
33
+ IMAGE_SIZE = 512
34
 
35
  # init
36
  device = "cuda" if torch.cuda.is_available() else "cpu"
37
  base_model = "black-forest-labs/FLUX.1-dev"
38
 
39
+ controlnet_model = 'InstantX/FLUX.1-dev-Controlnet-Union'
40
+ controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
41
+
42
+
43
+ pipe = FluxControlNetInpaintPipeline.from_pretrained(base_model, controlnet=controlnet, torch_dtype=torch.bfloat16).to(device)
44
 
45
+ # pipe.enable_model_cpu_offload() # for saving memory
 
 
 
 
46
 
47
+ control_mode_ids = {
48
+ "canny": 0, # supported
49
+ "tile": 1, # supported
50
+ "depth": 2, # supported
51
+ "blur": 3, # supported
52
+ "pose": 4, # supported
53
+ "gray": 5, # supported
54
+ "lq": 6, # supported
55
+ }
56
 
57
  def clear_cuda_cache():
58
  torch.cuda.empty_cache()
59
 
60
+
61
  class calculateDuration:
62
  def __init__(self, activity_name=""):
63
  self.activity_name = activity_name
64
 
65
  def __enter__(self):
66
  self.start_time = time.time()
 
 
67
  return self
68
 
69
  def __exit__(self, exc_type, exc_value, traceback):
70
  self.end_time = time.time()
71
  self.elapsed_time = self.end_time - self.start_time
 
 
72
  if self.activity_name:
73
  print(f"Elapsed time for {self.activity_name}: {self.elapsed_time:.6f} seconds")
74
  else:
75
  print(f"Elapsed time: {self.elapsed_time:.6f} seconds")
 
76
 
77
 
78
  def calculate_image_dimensions_for_flux(
 
147
  def run_flux(
148
  image: Image.Image,
149
  mask: Image.Image,
150
+ control_image: Image.Image,
151
+ control_mode: int,
152
  prompt: str,
153
  seed_slicer: int,
154
  randomize_seed_checkbox: bool,
 
157
  resolution_wh: Tuple[int, int],
158
  progress
159
  ) -> Image.Image:
160
+ print("Running FLUX...")
161
+ width, height = resolution_wh
162
+ if randomize_seed_checkbox:
163
+ seed_slicer = random.randint(0, MAX_SEED)
164
+ generator = torch.Generator().manual_seed(seed_slicer)
165
 
166
  with calculateDuration("run pipe"):
167
+ print("start to run pipe", prompt)
168
+
 
 
 
 
169
  with torch.inference_mode():
170
  generated_image = pipe(
171
  prompt=prompt,
172
+ image=image,
173
  mask_image=mask,
174
+ control_image=control_image,
175
+ control_mode=control_mode,
176
+ controlnet_conditioning_scale=0.55,
177
  width=width,
178
  height=height,
179
+ strength=strength_slider,
 
180
  generator=generator,
181
+ num_inference_steps=num_inference_steps_slider,
182
  ).images[0]
183
  progress(99, "Generate image success!")
184
  return generated_image
185
 
186
 
187
  def load_loras(lora_strings_json:str):
188
+ lora_configs = None
189
  if lora_strings_json:
190
  try:
191
  lora_configs = json.loads(lora_strings_json)
192
  except:
193
+ print("parse lora failed")
194
+
195
  if lora_configs:
196
  with calculateDuration("Loading LoRA weights"):
197
  pipe.unload_lora_weights()
 
211
  pipe.set_adapters(adapter_names, adapter_weights=adapter_weights)
212
 
213
 
214
+ def generate_control_image(image, mask, control_mode, width, height):
215
+ # generated control_
216
+ with calculateDuration("Generate control image"):
217
+ preprocessor = Preprocessor()
218
+ if control_mode == "depth":
219
+ preprocessor.load("Midas")
220
+ control_image = preprocessor(
221
+ image=image,
222
+ image_resolution=width,
223
+ detect_resolution=512,
224
+ )
225
+ if control_mode == "pose":
226
+ preprocessor.load("Openpose")
227
+ control_image = preprocessor(
228
+ image=image,
229
+ hand_and_face=False,
230
+ image_resolution=width,
231
+ detect_resolution=512,
232
+ )
233
+ if control_mode == "canny":
234
+ preprocessor.load("Canny")
235
+ control_image = preprocessor(
236
+ image=image,
237
+ image_resolution=width,
238
+ detect_resolution=512,
239
+ )
240
+
241
+ control_image = control_image.resize((width, height), Image.LANCZOS)
242
+ return control_image
243
+
244
  def process(
245
  image_url: str,
246
  mask_url: str,
247
  inpainting_prompt_text: str,
248
  mask_inflation_slider: int,
249
  mask_blur_slider: int,
250
+ control_mode: str,
251
  seed_slicer: int,
252
  randomize_seed_checkbox: bool,
253
  strength_slider: float,
 
289
  mask = mask.resize((width, height), Image.LANCZOS)
290
  mask = process_mask(mask, mask_inflation=mask_inflation_slider, mask_blur=mask_blur_slider)
291
 
292
+ control_image = generate_control_image(image, mask, control_mode, width, height)
293
+ control_mode_id = control_mode_ids[control_mode]
294
+ clear_cuda_cache()
295
+
296
  load_loras(lora_strings_json=lora_strings_json)
297
 
298
  try:
299
  generated_image = run_flux(
300
  image=image,
301
  mask=mask,
302
+ control_image=control_image,
303
+ control_mode=control_mode_id,
304
  prompt=inpainting_prompt_text,
305
  seed_slicer=seed_slicer,
306
  randomize_seed_checkbox=randomize_seed_checkbox,
 
471
  )
472
 
473
  demo.queue(api_open=False)
474
+ demo.launch()
controlnet_flux.py DELETED
@@ -1,418 +0,0 @@
1
- from dataclasses import dataclass
2
- from typing import Any, Dict, List, Optional, Tuple, Union
3
-
4
- import torch
5
- import torch.nn as nn
6
-
7
- from diffusers.configuration_utils import ConfigMixin, register_to_config
8
- from diffusers.loaders import PeftAdapterMixin
9
- from diffusers.models.modeling_utils import ModelMixin
10
- from diffusers.models.attention_processor import AttentionProcessor
11
- from diffusers.utils import (
12
- USE_PEFT_BACKEND,
13
- is_torch_version,
14
- logging,
15
- scale_lora_layers,
16
- unscale_lora_layers,
17
- )
18
- from diffusers.models.controlnet import BaseOutput, zero_module
19
- from diffusers.models.embeddings import (
20
- CombinedTimestepGuidanceTextProjEmbeddings,
21
- CombinedTimestepTextProjEmbeddings,
22
- )
23
- from diffusers.models.modeling_outputs import Transformer2DModelOutput
24
- from transformer_flux import (
25
- EmbedND,
26
- FluxSingleTransformerBlock,
27
- FluxTransformerBlock,
28
- )
29
-
30
-
31
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
32
-
33
-
34
- @dataclass
35
- class FluxControlNetOutput(BaseOutput):
36
- controlnet_block_samples: Tuple[torch.Tensor]
37
- controlnet_single_block_samples: Tuple[torch.Tensor]
38
-
39
-
40
- class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
41
- _supports_gradient_checkpointing = True
42
-
43
- @register_to_config
44
- def __init__(
45
- self,
46
- patch_size: int = 1,
47
- in_channels: int = 64,
48
- num_layers: int = 19,
49
- num_single_layers: int = 38,
50
- attention_head_dim: int = 128,
51
- num_attention_heads: int = 24,
52
- joint_attention_dim: int = 4096,
53
- pooled_projection_dim: int = 768,
54
- guidance_embeds: bool = False,
55
- axes_dims_rope: List[int] = [16, 56, 56],
56
- extra_condition_channels: int = 1 * 4,
57
- ):
58
- super().__init__()
59
- self.out_channels = in_channels
60
- self.inner_dim = num_attention_heads * attention_head_dim
61
-
62
- self.pos_embed = EmbedND(
63
- dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope
64
- )
65
- text_time_guidance_cls = (
66
- CombinedTimestepGuidanceTextProjEmbeddings
67
- if guidance_embeds
68
- else CombinedTimestepTextProjEmbeddings
69
- )
70
- self.time_text_embed = text_time_guidance_cls(
71
- embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
72
- )
73
-
74
- self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
75
- self.x_embedder = nn.Linear(in_channels, self.inner_dim)
76
-
77
- self.transformer_blocks = nn.ModuleList(
78
- [
79
- FluxTransformerBlock(
80
- dim=self.inner_dim,
81
- num_attention_heads=num_attention_heads,
82
- attention_head_dim=attention_head_dim,
83
- )
84
- for _ in range(num_layers)
85
- ]
86
- )
87
-
88
- self.single_transformer_blocks = nn.ModuleList(
89
- [
90
- FluxSingleTransformerBlock(
91
- dim=self.inner_dim,
92
- num_attention_heads=num_attention_heads,
93
- attention_head_dim=attention_head_dim,
94
- )
95
- for _ in range(num_single_layers)
96
- ]
97
- )
98
-
99
- # controlnet_blocks
100
- self.controlnet_blocks = nn.ModuleList([])
101
- for _ in range(len(self.transformer_blocks)):
102
- self.controlnet_blocks.append(
103
- zero_module(nn.Linear(self.inner_dim, self.inner_dim))
104
- )
105
-
106
- self.controlnet_single_blocks = nn.ModuleList([])
107
- for _ in range(len(self.single_transformer_blocks)):
108
- self.controlnet_single_blocks.append(
109
- zero_module(nn.Linear(self.inner_dim, self.inner_dim))
110
- )
111
-
112
- self.controlnet_x_embedder = zero_module(
113
- torch.nn.Linear(in_channels + extra_condition_channels, self.inner_dim)
114
- )
115
-
116
- self.gradient_checkpointing = False
117
-
118
- @property
119
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
120
- def attn_processors(self):
121
- r"""
122
- Returns:
123
- `dict` of attention processors: A dictionary containing all attention processors used in the model with
124
- indexed by its weight name.
125
- """
126
- # set recursively
127
- processors = {}
128
-
129
- def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
130
- if hasattr(module, "get_processor"):
131
- processors[f"{name}.processor"] = module.get_processor()
132
-
133
- for sub_name, child in module.named_children():
134
- fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
135
-
136
- return processors
137
-
138
- for name, module in self.named_children():
139
- fn_recursive_add_processors(name, module, processors)
140
-
141
- return processors
142
-
143
- # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
144
- def set_attn_processor(self, processor):
145
- r"""
146
- Sets the attention processor to use to compute attention.
147
-
148
- Parameters:
149
- processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
150
- The instantiated processor class or a dictionary of processor classes that will be set as the processor
151
- for **all** `Attention` layers.
152
-
153
- If `processor` is a dict, the key needs to define the path to the corresponding cross attention
154
- processor. This is strongly recommended when setting trainable attention processors.
155
-
156
- """
157
- count = len(self.attn_processors.keys())
158
-
159
- if isinstance(processor, dict) and len(processor) != count:
160
- raise ValueError(
161
- f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
162
- f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
163
- )
164
-
165
- def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
166
- if hasattr(module, "set_processor"):
167
- if not isinstance(processor, dict):
168
- module.set_processor(processor)
169
- else:
170
- module.set_processor(processor.pop(f"{name}.processor"))
171
-
172
- for sub_name, child in module.named_children():
173
- fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
174
-
175
- for name, module in self.named_children():
176
- fn_recursive_attn_processor(name, module, processor)
177
-
178
- def _set_gradient_checkpointing(self, module, value=False):
179
- if hasattr(module, "gradient_checkpointing"):
180
- module.gradient_checkpointing = value
181
-
182
- @classmethod
183
- def from_transformer(
184
- cls,
185
- transformer,
186
- num_layers: int = 4,
187
- num_single_layers: int = 10,
188
- attention_head_dim: int = 128,
189
- num_attention_heads: int = 24,
190
- load_weights_from_transformer=True,
191
- ):
192
- config = transformer.config
193
- config["num_layers"] = num_layers
194
- config["num_single_layers"] = num_single_layers
195
- config["attention_head_dim"] = attention_head_dim
196
- config["num_attention_heads"] = num_attention_heads
197
-
198
- controlnet = cls(**config)
199
-
200
- if load_weights_from_transformer:
201
- controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
202
- controlnet.time_text_embed.load_state_dict(
203
- transformer.time_text_embed.state_dict()
204
- )
205
- controlnet.context_embedder.load_state_dict(
206
- transformer.context_embedder.state_dict()
207
- )
208
- controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict())
209
- controlnet.transformer_blocks.load_state_dict(
210
- transformer.transformer_blocks.state_dict(), strict=False
211
- )
212
- controlnet.single_transformer_blocks.load_state_dict(
213
- transformer.single_transformer_blocks.state_dict(), strict=False
214
- )
215
-
216
- controlnet.controlnet_x_embedder = zero_module(
217
- controlnet.controlnet_x_embedder
218
- )
219
-
220
- return controlnet
221
-
222
- def forward(
223
- self,
224
- hidden_states: torch.Tensor,
225
- controlnet_cond: torch.Tensor,
226
- conditioning_scale: float = 1.0,
227
- encoder_hidden_states: torch.Tensor = None,
228
- pooled_projections: torch.Tensor = None,
229
- timestep: torch.LongTensor = None,
230
- img_ids: torch.Tensor = None,
231
- txt_ids: torch.Tensor = None,
232
- guidance: torch.Tensor = None,
233
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
234
- return_dict: bool = True,
235
- ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
236
- """
237
- The [`FluxTransformer2DModel`] forward method.
238
-
239
- Args:
240
- hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
241
- Input `hidden_states`.
242
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
243
- Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
244
- pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
245
- from the embeddings of input conditions.
246
- timestep ( `torch.LongTensor`):
247
- Used to indicate denoising step.
248
- block_controlnet_hidden_states: (`list` of `torch.Tensor`):
249
- A list of tensors that if specified are added to the residuals of transformer blocks.
250
- joint_attention_kwargs (`dict`, *optional*):
251
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
252
- `self.processor` in
253
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
254
- return_dict (`bool`, *optional*, defaults to `True`):
255
- Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
256
- tuple.
257
-
258
- Returns:
259
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
260
- `tuple` where the first element is the sample tensor.
261
- """
262
- if joint_attention_kwargs is not None:
263
- joint_attention_kwargs = joint_attention_kwargs.copy()
264
- lora_scale = joint_attention_kwargs.pop("scale", 1.0)
265
- else:
266
- lora_scale = 1.0
267
-
268
- if USE_PEFT_BACKEND:
269
- # weight the lora layers by setting `lora_scale` for each PEFT layer
270
- scale_lora_layers(self, lora_scale)
271
- else:
272
- if (
273
- joint_attention_kwargs is not None
274
- and joint_attention_kwargs.get("scale", None) is not None
275
- ):
276
- logger.warning(
277
- "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
278
- )
279
- hidden_states = self.x_embedder(hidden_states)
280
-
281
- # add condition
282
- hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
283
-
284
- timestep = timestep.to(hidden_states.dtype) * 1000
285
- if guidance is not None:
286
- guidance = guidance.to(hidden_states.dtype) * 1000
287
- else:
288
- guidance = None
289
- temb = (
290
- self.time_text_embed(timestep, pooled_projections)
291
- if guidance is None
292
- else self.time_text_embed(timestep, guidance, pooled_projections)
293
- )
294
- encoder_hidden_states = self.context_embedder(encoder_hidden_states)
295
-
296
- txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
297
- ids = torch.cat((txt_ids, img_ids), dim=1)
298
- image_rotary_emb = self.pos_embed(ids)
299
-
300
- block_samples = ()
301
- for _, block in enumerate(self.transformer_blocks):
302
- if self.training and self.gradient_checkpointing:
303
-
304
- def create_custom_forward(module, return_dict=None):
305
- def custom_forward(*inputs):
306
- if return_dict is not None:
307
- return module(*inputs, return_dict=return_dict)
308
- else:
309
- return module(*inputs)
310
-
311
- return custom_forward
312
-
313
- ckpt_kwargs: Dict[str, Any] = (
314
- {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
315
- )
316
- (
317
- encoder_hidden_states,
318
- hidden_states,
319
- ) = torch.utils.checkpoint.checkpoint(
320
- create_custom_forward(block),
321
- hidden_states,
322
- encoder_hidden_states,
323
- temb,
324
- image_rotary_emb,
325
- **ckpt_kwargs,
326
- )
327
-
328
- else:
329
- encoder_hidden_states, hidden_states = block(
330
- hidden_states=hidden_states,
331
- encoder_hidden_states=encoder_hidden_states,
332
- temb=temb,
333
- image_rotary_emb=image_rotary_emb,
334
- )
335
- block_samples = block_samples + (hidden_states,)
336
-
337
- hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
338
-
339
- single_block_samples = ()
340
- for _, block in enumerate(self.single_transformer_blocks):
341
- if self.training and self.gradient_checkpointing:
342
-
343
- def create_custom_forward(module, return_dict=None):
344
- def custom_forward(*inputs):
345
- if return_dict is not None:
346
- return module(*inputs, return_dict=return_dict)
347
- else:
348
- return module(*inputs)
349
-
350
- return custom_forward
351
-
352
- ckpt_kwargs: Dict[str, Any] = (
353
- {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
354
- )
355
- hidden_states = torch.utils.checkpoint.checkpoint(
356
- create_custom_forward(block),
357
- hidden_states,
358
- temb,
359
- image_rotary_emb,
360
- **ckpt_kwargs,
361
- )
362
-
363
- else:
364
- hidden_states = block(
365
- hidden_states=hidden_states,
366
- temb=temb,
367
- image_rotary_emb=image_rotary_emb,
368
- )
369
- single_block_samples = single_block_samples + (
370
- hidden_states[:, encoder_hidden_states.shape[1] :],
371
- )
372
-
373
- # controlnet block
374
- controlnet_block_samples = ()
375
- for block_sample, controlnet_block in zip(
376
- block_samples, self.controlnet_blocks
377
- ):
378
- block_sample = controlnet_block(block_sample)
379
- controlnet_block_samples = controlnet_block_samples + (block_sample,)
380
-
381
- controlnet_single_block_samples = ()
382
- for single_block_sample, controlnet_block in zip(
383
- single_block_samples, self.controlnet_single_blocks
384
- ):
385
- single_block_sample = controlnet_block(single_block_sample)
386
- controlnet_single_block_samples = controlnet_single_block_samples + (
387
- single_block_sample,
388
- )
389
-
390
- # scaling
391
- controlnet_block_samples = [
392
- sample * conditioning_scale for sample in controlnet_block_samples
393
- ]
394
- controlnet_single_block_samples = [
395
- sample * conditioning_scale for sample in controlnet_single_block_samples
396
- ]
397
-
398
- #
399
- controlnet_block_samples = (
400
- None if len(controlnet_block_samples) == 0 else controlnet_block_samples
401
- )
402
- controlnet_single_block_samples = (
403
- None
404
- if len(controlnet_single_block_samples) == 0
405
- else controlnet_single_block_samples
406
- )
407
-
408
- if USE_PEFT_BACKEND:
409
- # remove `lora_scale` from each PEFT layer
410
- unscale_lora_layers(self, lora_scale)
411
-
412
- if not return_dict:
413
- return (controlnet_block_samples, controlnet_single_block_samples)
414
-
415
- return FluxControlNetOutput(
416
- controlnet_block_samples=controlnet_block_samples,
417
- controlnet_single_block_samples=controlnet_single_block_samples,
418
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
depth_anything_v2/__pycache__/dinov2.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
depth_anything_v2/__pycache__/dpt.cpython-310.pyc ADDED
Binary file (5.93 kB). View file
 
depth_anything_v2/dinov2.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+ from functools import partial
11
+ import math
12
+ import logging
13
+ from typing import Sequence, Tuple, Union, Callable
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ import torch.utils.checkpoint
18
+ from torch.nn.init import trunc_normal_
19
+
20
+ from .dinov2_layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
21
+
22
+
23
+ logger = logging.getLogger("dinov2")
24
+
25
+
26
+ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
27
+ if not depth_first and include_root:
28
+ fn(module=module, name=name)
29
+ for child_name, child_module in module.named_children():
30
+ child_name = ".".join((name, child_name)) if name else child_name
31
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
32
+ if depth_first and include_root:
33
+ fn(module=module, name=name)
34
+ return module
35
+
36
+
37
+ class BlockChunk(nn.ModuleList):
38
+ def forward(self, x):
39
+ for b in self:
40
+ x = b(x)
41
+ return x
42
+
43
+
44
+ class DinoVisionTransformer(nn.Module):
45
+ def __init__(
46
+ self,
47
+ img_size=224,
48
+ patch_size=16,
49
+ in_chans=3,
50
+ embed_dim=768,
51
+ depth=12,
52
+ num_heads=12,
53
+ mlp_ratio=4.0,
54
+ qkv_bias=True,
55
+ ffn_bias=True,
56
+ proj_bias=True,
57
+ drop_path_rate=0.0,
58
+ drop_path_uniform=False,
59
+ init_values=None, # for layerscale: None or 0 => no layerscale
60
+ embed_layer=PatchEmbed,
61
+ act_layer=nn.GELU,
62
+ block_fn=Block,
63
+ ffn_layer="mlp",
64
+ block_chunks=1,
65
+ num_register_tokens=0,
66
+ interpolate_antialias=False,
67
+ interpolate_offset=0.1,
68
+ ):
69
+ """
70
+ Args:
71
+ img_size (int, tuple): input image size
72
+ patch_size (int, tuple): patch size
73
+ in_chans (int): number of input channels
74
+ embed_dim (int): embedding dimension
75
+ depth (int): depth of transformer
76
+ num_heads (int): number of attention heads
77
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
78
+ qkv_bias (bool): enable bias for qkv if True
79
+ proj_bias (bool): enable bias for proj in attn if True
80
+ ffn_bias (bool): enable bias for ffn if True
81
+ drop_path_rate (float): stochastic depth rate
82
+ drop_path_uniform (bool): apply uniform drop rate across blocks
83
+ weight_init (str): weight init scheme
84
+ init_values (float): layer-scale init values
85
+ embed_layer (nn.Module): patch embedding layer
86
+ act_layer (nn.Module): MLP activation layer
87
+ block_fn (nn.Module): transformer block class
88
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
89
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
90
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
91
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
92
+ interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
93
+ """
94
+ super().__init__()
95
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
96
+
97
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
98
+ self.num_tokens = 1
99
+ self.n_blocks = depth
100
+ self.num_heads = num_heads
101
+ self.patch_size = patch_size
102
+ self.num_register_tokens = num_register_tokens
103
+ self.interpolate_antialias = interpolate_antialias
104
+ self.interpolate_offset = interpolate_offset
105
+
106
+ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
107
+ num_patches = self.patch_embed.num_patches
108
+
109
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
110
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
111
+ assert num_register_tokens >= 0
112
+ self.register_tokens = (
113
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
114
+ )
115
+
116
+ if drop_path_uniform is True:
117
+ dpr = [drop_path_rate] * depth
118
+ else:
119
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
120
+
121
+ if ffn_layer == "mlp":
122
+ logger.info("using MLP layer as FFN")
123
+ ffn_layer = Mlp
124
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
125
+ logger.info("using SwiGLU layer as FFN")
126
+ ffn_layer = SwiGLUFFNFused
127
+ elif ffn_layer == "identity":
128
+ logger.info("using Identity layer as FFN")
129
+
130
+ def f(*args, **kwargs):
131
+ return nn.Identity()
132
+
133
+ ffn_layer = f
134
+ else:
135
+ raise NotImplementedError
136
+
137
+ blocks_list = [
138
+ block_fn(
139
+ dim=embed_dim,
140
+ num_heads=num_heads,
141
+ mlp_ratio=mlp_ratio,
142
+ qkv_bias=qkv_bias,
143
+ proj_bias=proj_bias,
144
+ ffn_bias=ffn_bias,
145
+ drop_path=dpr[i],
146
+ norm_layer=norm_layer,
147
+ act_layer=act_layer,
148
+ ffn_layer=ffn_layer,
149
+ init_values=init_values,
150
+ )
151
+ for i in range(depth)
152
+ ]
153
+ if block_chunks > 0:
154
+ self.chunked_blocks = True
155
+ chunked_blocks = []
156
+ chunksize = depth // block_chunks
157
+ for i in range(0, depth, chunksize):
158
+ # this is to keep the block index consistent if we chunk the block list
159
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
160
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
161
+ else:
162
+ self.chunked_blocks = False
163
+ self.blocks = nn.ModuleList(blocks_list)
164
+
165
+ self.norm = norm_layer(embed_dim)
166
+ self.head = nn.Identity()
167
+
168
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
169
+
170
+ self.init_weights()
171
+
172
+ def init_weights(self):
173
+ trunc_normal_(self.pos_embed, std=0.02)
174
+ nn.init.normal_(self.cls_token, std=1e-6)
175
+ if self.register_tokens is not None:
176
+ nn.init.normal_(self.register_tokens, std=1e-6)
177
+ named_apply(init_weights_vit_timm, self)
178
+
179
+ def interpolate_pos_encoding(self, x, w, h):
180
+ previous_dtype = x.dtype
181
+ npatch = x.shape[1] - 1
182
+ N = self.pos_embed.shape[1] - 1
183
+ if npatch == N and w == h:
184
+ return self.pos_embed
185
+ pos_embed = self.pos_embed.float()
186
+ class_pos_embed = pos_embed[:, 0]
187
+ patch_pos_embed = pos_embed[:, 1:]
188
+ dim = x.shape[-1]
189
+ w0 = w // self.patch_size
190
+ h0 = h // self.patch_size
191
+ # we add a small number to avoid floating point error in the interpolation
192
+ # see discussion at https://github.com/facebookresearch/dino/issues/8
193
+ # DINOv2 with register modify the interpolate_offset from 0.1 to 0.0
194
+ w0, h0 = w0 + self.interpolate_offset, h0 + self.interpolate_offset
195
+ # w0, h0 = w0 + 0.1, h0 + 0.1
196
+
197
+ sqrt_N = math.sqrt(N)
198
+ sx, sy = float(w0) / sqrt_N, float(h0) / sqrt_N
199
+ patch_pos_embed = nn.functional.interpolate(
200
+ patch_pos_embed.reshape(1, int(sqrt_N), int(sqrt_N), dim).permute(0, 3, 1, 2),
201
+ scale_factor=(sx, sy),
202
+ # (int(w0), int(h0)), # to solve the upsampling shape issue
203
+ mode="bicubic",
204
+ antialias=self.interpolate_antialias
205
+ )
206
+
207
+ assert int(w0) == patch_pos_embed.shape[-2]
208
+ assert int(h0) == patch_pos_embed.shape[-1]
209
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
210
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
211
+
212
+ def prepare_tokens_with_masks(self, x, masks=None):
213
+ B, nc, w, h = x.shape
214
+ x = self.patch_embed(x)
215
+ if masks is not None:
216
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
217
+
218
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
219
+ x = x + self.interpolate_pos_encoding(x, w, h)
220
+
221
+ if self.register_tokens is not None:
222
+ x = torch.cat(
223
+ (
224
+ x[:, :1],
225
+ self.register_tokens.expand(x.shape[0], -1, -1),
226
+ x[:, 1:],
227
+ ),
228
+ dim=1,
229
+ )
230
+
231
+ return x
232
+
233
+ def forward_features_list(self, x_list, masks_list):
234
+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
235
+ for blk in self.blocks:
236
+ x = blk(x)
237
+
238
+ all_x = x
239
+ output = []
240
+ for x, masks in zip(all_x, masks_list):
241
+ x_norm = self.norm(x)
242
+ output.append(
243
+ {
244
+ "x_norm_clstoken": x_norm[:, 0],
245
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
246
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
247
+ "x_prenorm": x,
248
+ "masks": masks,
249
+ }
250
+ )
251
+ return output
252
+
253
+ def forward_features(self, x, masks=None):
254
+ if isinstance(x, list):
255
+ return self.forward_features_list(x, masks)
256
+
257
+ x = self.prepare_tokens_with_masks(x, masks)
258
+
259
+ for blk in self.blocks:
260
+ x = blk(x)
261
+
262
+ x_norm = self.norm(x)
263
+ return {
264
+ "x_norm_clstoken": x_norm[:, 0],
265
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
266
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
267
+ "x_prenorm": x,
268
+ "masks": masks,
269
+ }
270
+
271
+ def _get_intermediate_layers_not_chunked(self, x, n=1):
272
+ x = self.prepare_tokens_with_masks(x)
273
+ # If n is an int, take the n last blocks. If it's a list, take them
274
+ output, total_block_len = [], len(self.blocks)
275
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
276
+ for i, blk in enumerate(self.blocks):
277
+ x = blk(x)
278
+ if i in blocks_to_take:
279
+ output.append(x)
280
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
281
+ return output
282
+
283
+ def _get_intermediate_layers_chunked(self, x, n=1):
284
+ x = self.prepare_tokens_with_masks(x)
285
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
286
+ # If n is an int, take the n last blocks. If it's a list, take them
287
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
288
+ for block_chunk in self.blocks:
289
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
290
+ x = blk(x)
291
+ if i in blocks_to_take:
292
+ output.append(x)
293
+ i += 1
294
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
295
+ return output
296
+
297
+ def get_intermediate_layers(
298
+ self,
299
+ x: torch.Tensor,
300
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
301
+ reshape: bool = False,
302
+ return_class_token: bool = False,
303
+ norm=True
304
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
305
+ if self.chunked_blocks:
306
+ outputs = self._get_intermediate_layers_chunked(x, n)
307
+ else:
308
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
309
+ if norm:
310
+ outputs = [self.norm(out) for out in outputs]
311
+ class_tokens = [out[:, 0] for out in outputs]
312
+ outputs = [out[:, 1 + self.num_register_tokens:] for out in outputs]
313
+ if reshape:
314
+ B, _, w, h = x.shape
315
+ outputs = [
316
+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
317
+ for out in outputs
318
+ ]
319
+ if return_class_token:
320
+ return tuple(zip(outputs, class_tokens))
321
+ return tuple(outputs)
322
+
323
+ def forward(self, *args, is_training=False, **kwargs):
324
+ ret = self.forward_features(*args, **kwargs)
325
+ if is_training:
326
+ return ret
327
+ else:
328
+ return self.head(ret["x_norm_clstoken"])
329
+
330
+
331
+ def init_weights_vit_timm(module: nn.Module, name: str = ""):
332
+ """ViT weight initialization, original timm impl (for reproducibility)"""
333
+ if isinstance(module, nn.Linear):
334
+ trunc_normal_(module.weight, std=0.02)
335
+ if module.bias is not None:
336
+ nn.init.zeros_(module.bias)
337
+
338
+
339
+ def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
340
+ model = DinoVisionTransformer(
341
+ patch_size=patch_size,
342
+ embed_dim=384,
343
+ depth=12,
344
+ num_heads=6,
345
+ mlp_ratio=4,
346
+ block_fn=partial(Block, attn_class=MemEffAttention),
347
+ num_register_tokens=num_register_tokens,
348
+ **kwargs,
349
+ )
350
+ return model
351
+
352
+
353
+ def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
354
+ model = DinoVisionTransformer(
355
+ patch_size=patch_size,
356
+ embed_dim=768,
357
+ depth=12,
358
+ num_heads=12,
359
+ mlp_ratio=4,
360
+ block_fn=partial(Block, attn_class=MemEffAttention),
361
+ num_register_tokens=num_register_tokens,
362
+ **kwargs,
363
+ )
364
+ return model
365
+
366
+
367
+ def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
368
+ model = DinoVisionTransformer(
369
+ patch_size=patch_size,
370
+ embed_dim=1024,
371
+ depth=24,
372
+ num_heads=16,
373
+ mlp_ratio=4,
374
+ block_fn=partial(Block, attn_class=MemEffAttention),
375
+ num_register_tokens=num_register_tokens,
376
+ **kwargs,
377
+ )
378
+ return model
379
+
380
+
381
+ def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
382
+ """
383
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
384
+ """
385
+ model = DinoVisionTransformer(
386
+ patch_size=patch_size,
387
+ embed_dim=1536,
388
+ depth=40,
389
+ num_heads=24,
390
+ mlp_ratio=4,
391
+ block_fn=partial(Block, attn_class=MemEffAttention),
392
+ num_register_tokens=num_register_tokens,
393
+ **kwargs,
394
+ )
395
+ return model
396
+
397
+
398
+ def DINOv2(model_name):
399
+ model_zoo = {
400
+ "vits": vit_small,
401
+ "vitb": vit_base,
402
+ "vitl": vit_large,
403
+ "vitg": vit_giant2
404
+ }
405
+
406
+ return model_zoo[model_name](
407
+ img_size=518,
408
+ patch_size=14,
409
+ init_values=1.0,
410
+ ffn_layer="mlp" if model_name != "vitg" else "swiglufused",
411
+ block_chunks=0,
412
+ num_register_tokens=0,
413
+ interpolate_antialias=False,
414
+ interpolate_offset=0.1
415
+ )
depth_anything_v2/dinov2_layers/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .mlp import Mlp
8
+ from .patch_embed import PatchEmbed
9
+ from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused
10
+ from .block import NestedTensorBlock
11
+ from .attention import MemEffAttention
depth_anything_v2/dinov2_layers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (393 Bytes). View file
 
depth_anything_v2/dinov2_layers/__pycache__/attention.cpython-310.pyc ADDED
Binary file (2.36 kB). View file
 
depth_anything_v2/dinov2_layers/__pycache__/block.cpython-310.pyc ADDED
Binary file (7.97 kB). View file
 
depth_anything_v2/dinov2_layers/__pycache__/drop_path.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
depth_anything_v2/dinov2_layers/__pycache__/layer_scale.cpython-310.pyc ADDED
Binary file (997 Bytes). View file
 
depth_anything_v2/dinov2_layers/__pycache__/mlp.cpython-310.pyc ADDED
Binary file (1.19 kB). View file
 
depth_anything_v2/dinov2_layers/__pycache__/patch_embed.cpython-310.pyc ADDED
Binary file (2.63 kB). View file
 
depth_anything_v2/dinov2_layers/__pycache__/swiglu_ffn.cpython-310.pyc ADDED
Binary file (1.99 kB). View file
 
depth_anything_v2/dinov2_layers/attention.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
10
+
11
+ import logging
12
+
13
+ from torch import Tensor
14
+ from torch import nn
15
+
16
+
17
+ logger = logging.getLogger("dinov2")
18
+
19
+
20
+ try:
21
+ from xformers.ops import memory_efficient_attention, unbind, fmha
22
+
23
+ XFORMERS_AVAILABLE = True
24
+ except ImportError:
25
+ logger.warning("xFormers not available")
26
+ XFORMERS_AVAILABLE = False
27
+
28
+
29
+ class Attention(nn.Module):
30
+ def __init__(
31
+ self,
32
+ dim: int,
33
+ num_heads: int = 8,
34
+ qkv_bias: bool = False,
35
+ proj_bias: bool = True,
36
+ attn_drop: float = 0.0,
37
+ proj_drop: float = 0.0,
38
+ ) -> None:
39
+ super().__init__()
40
+ self.num_heads = num_heads
41
+ head_dim = dim // num_heads
42
+ self.scale = head_dim**-0.5
43
+
44
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
45
+ self.attn_drop = nn.Dropout(attn_drop)
46
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
47
+ self.proj_drop = nn.Dropout(proj_drop)
48
+
49
+ def forward(self, x: Tensor) -> Tensor:
50
+ B, N, C = x.shape
51
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
52
+
53
+ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
54
+ attn = q @ k.transpose(-2, -1)
55
+
56
+ attn = attn.softmax(dim=-1)
57
+ attn = self.attn_drop(attn)
58
+
59
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
60
+ x = self.proj(x)
61
+ x = self.proj_drop(x)
62
+ return x
63
+
64
+
65
+ class MemEffAttention(Attention):
66
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
67
+ if not XFORMERS_AVAILABLE:
68
+ assert attn_bias is None, "xFormers is required for nested tensors usage"
69
+ return super().forward(x)
70
+
71
+ B, N, C = x.shape
72
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
73
+
74
+ q, k, v = unbind(qkv, 2)
75
+
76
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
77
+ x = x.reshape([B, N, C])
78
+
79
+ x = self.proj(x)
80
+ x = self.proj_drop(x)
81
+ return x
depth_anything_v2/dinov2_layers/block.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ import logging
12
+ from typing import Callable, List, Any, Tuple, Dict
13
+
14
+ import torch
15
+ from torch import nn, Tensor
16
+
17
+ from .attention import Attention, MemEffAttention
18
+ from .drop_path import DropPath
19
+ from .layer_scale import LayerScale
20
+ from .mlp import Mlp
21
+
22
+
23
+ logger = logging.getLogger("dinov2")
24
+
25
+
26
+ try:
27
+ from xformers.ops import fmha
28
+ from xformers.ops import scaled_index_add, index_select_cat
29
+
30
+ XFORMERS_AVAILABLE = True
31
+ except ImportError:
32
+ logger.warning("xFormers not available")
33
+ XFORMERS_AVAILABLE = False
34
+
35
+
36
+ class Block(nn.Module):
37
+ def __init__(
38
+ self,
39
+ dim: int,
40
+ num_heads: int,
41
+ mlp_ratio: float = 4.0,
42
+ qkv_bias: bool = False,
43
+ proj_bias: bool = True,
44
+ ffn_bias: bool = True,
45
+ drop: float = 0.0,
46
+ attn_drop: float = 0.0,
47
+ init_values=None,
48
+ drop_path: float = 0.0,
49
+ act_layer: Callable[..., nn.Module] = nn.GELU,
50
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
51
+ attn_class: Callable[..., nn.Module] = Attention,
52
+ ffn_layer: Callable[..., nn.Module] = Mlp,
53
+ ) -> None:
54
+ super().__init__()
55
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
56
+ self.norm1 = norm_layer(dim)
57
+ self.attn = attn_class(
58
+ dim,
59
+ num_heads=num_heads,
60
+ qkv_bias=qkv_bias,
61
+ proj_bias=proj_bias,
62
+ attn_drop=attn_drop,
63
+ proj_drop=drop,
64
+ )
65
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
66
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
67
+
68
+ self.norm2 = norm_layer(dim)
69
+ mlp_hidden_dim = int(dim * mlp_ratio)
70
+ self.mlp = ffn_layer(
71
+ in_features=dim,
72
+ hidden_features=mlp_hidden_dim,
73
+ act_layer=act_layer,
74
+ drop=drop,
75
+ bias=ffn_bias,
76
+ )
77
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
78
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
79
+
80
+ self.sample_drop_ratio = drop_path
81
+
82
+ def forward(self, x: Tensor) -> Tensor:
83
+ def attn_residual_func(x: Tensor) -> Tensor:
84
+ return self.ls1(self.attn(self.norm1(x)))
85
+
86
+ def ffn_residual_func(x: Tensor) -> Tensor:
87
+ return self.ls2(self.mlp(self.norm2(x)))
88
+
89
+ if self.training and self.sample_drop_ratio > 0.1:
90
+ # the overhead is compensated only for a drop path rate larger than 0.1
91
+ x = drop_add_residual_stochastic_depth(
92
+ x,
93
+ residual_func=attn_residual_func,
94
+ sample_drop_ratio=self.sample_drop_ratio,
95
+ )
96
+ x = drop_add_residual_stochastic_depth(
97
+ x,
98
+ residual_func=ffn_residual_func,
99
+ sample_drop_ratio=self.sample_drop_ratio,
100
+ )
101
+ elif self.training and self.sample_drop_ratio > 0.0:
102
+ x = x + self.drop_path1(attn_residual_func(x))
103
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
104
+ else:
105
+ x = x + attn_residual_func(x)
106
+ x = x + ffn_residual_func(x)
107
+ return x
108
+
109
+
110
+ def drop_add_residual_stochastic_depth(
111
+ x: Tensor,
112
+ residual_func: Callable[[Tensor], Tensor],
113
+ sample_drop_ratio: float = 0.0,
114
+ ) -> Tensor:
115
+ # 1) extract subset using permutation
116
+ b, n, d = x.shape
117
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
118
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
119
+ x_subset = x[brange]
120
+
121
+ # 2) apply residual_func to get residual
122
+ residual = residual_func(x_subset)
123
+
124
+ x_flat = x.flatten(1)
125
+ residual = residual.flatten(1)
126
+
127
+ residual_scale_factor = b / sample_subset_size
128
+
129
+ # 3) add the residual
130
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
131
+ return x_plus_residual.view_as(x)
132
+
133
+
134
+ def get_branges_scales(x, sample_drop_ratio=0.0):
135
+ b, n, d = x.shape
136
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
137
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
138
+ residual_scale_factor = b / sample_subset_size
139
+ return brange, residual_scale_factor
140
+
141
+
142
+ def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
143
+ if scaling_vector is None:
144
+ x_flat = x.flatten(1)
145
+ residual = residual.flatten(1)
146
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
147
+ else:
148
+ x_plus_residual = scaled_index_add(
149
+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
150
+ )
151
+ return x_plus_residual
152
+
153
+
154
+ attn_bias_cache: Dict[Tuple, Any] = {}
155
+
156
+
157
+ def get_attn_bias_and_cat(x_list, branges=None):
158
+ """
159
+ this will perform the index select, cat the tensors, and provide the attn_bias from cache
160
+ """
161
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
162
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
163
+ if all_shapes not in attn_bias_cache.keys():
164
+ seqlens = []
165
+ for b, x in zip(batch_sizes, x_list):
166
+ for _ in range(b):
167
+ seqlens.append(x.shape[1])
168
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
169
+ attn_bias._batch_sizes = batch_sizes
170
+ attn_bias_cache[all_shapes] = attn_bias
171
+
172
+ if branges is not None:
173
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
174
+ else:
175
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
176
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
177
+
178
+ return attn_bias_cache[all_shapes], cat_tensors
179
+
180
+
181
+ def drop_add_residual_stochastic_depth_list(
182
+ x_list: List[Tensor],
183
+ residual_func: Callable[[Tensor, Any], Tensor],
184
+ sample_drop_ratio: float = 0.0,
185
+ scaling_vector=None,
186
+ ) -> Tensor:
187
+ # 1) generate random set of indices for dropping samples in the batch
188
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
189
+ branges = [s[0] for s in branges_scales]
190
+ residual_scale_factors = [s[1] for s in branges_scales]
191
+
192
+ # 2) get attention bias and index+concat the tensors
193
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
194
+
195
+ # 3) apply residual_func to get residual, and split the result
196
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
197
+
198
+ outputs = []
199
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
200
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
201
+ return outputs
202
+
203
+
204
+ class NestedTensorBlock(Block):
205
+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
206
+ """
207
+ x_list contains a list of tensors to nest together and run
208
+ """
209
+ assert isinstance(self.attn, MemEffAttention)
210
+
211
+ if self.training and self.sample_drop_ratio > 0.0:
212
+
213
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
214
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
215
+
216
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
217
+ return self.mlp(self.norm2(x))
218
+
219
+ x_list = drop_add_residual_stochastic_depth_list(
220
+ x_list,
221
+ residual_func=attn_residual_func,
222
+ sample_drop_ratio=self.sample_drop_ratio,
223
+ scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
224
+ )
225
+ x_list = drop_add_residual_stochastic_depth_list(
226
+ x_list,
227
+ residual_func=ffn_residual_func,
228
+ sample_drop_ratio=self.sample_drop_ratio,
229
+ scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
230
+ )
231
+ return x_list
232
+ else:
233
+
234
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
235
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
236
+
237
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
238
+ return self.ls2(self.mlp(self.norm2(x)))
239
+
240
+ attn_bias, x = get_attn_bias_and_cat(x_list)
241
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
242
+ x = x + ffn_residual_func(x)
243
+ return attn_bias.split(x)
244
+
245
+ def forward(self, x_or_x_list):
246
+ if isinstance(x_or_x_list, Tensor):
247
+ return super().forward(x_or_x_list)
248
+ elif isinstance(x_or_x_list, list):
249
+ assert XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage"
250
+ return self.forward_nested(x_or_x_list)
251
+ else:
252
+ raise AssertionError
depth_anything_v2/dinov2_layers/drop_path.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
10
+
11
+
12
+ from torch import nn
13
+
14
+
15
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
16
+ if drop_prob == 0.0 or not training:
17
+ return x
18
+ keep_prob = 1 - drop_prob
19
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
20
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
21
+ if keep_prob > 0.0:
22
+ random_tensor.div_(keep_prob)
23
+ output = x * random_tensor
24
+ return output
25
+
26
+
27
+ class DropPath(nn.Module):
28
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
29
+
30
+ def __init__(self, drop_prob=None):
31
+ super(DropPath, self).__init__()
32
+ self.drop_prob = drop_prob
33
+
34
+ def forward(self, x):
35
+ return drop_path(x, self.drop_prob, self.training)
depth_anything_v2/dinov2_layers/layer_scale.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
8
+
9
+ from typing import Union
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ from torch import nn
14
+
15
+
16
+ class LayerScale(nn.Module):
17
+ def __init__(
18
+ self,
19
+ dim: int,
20
+ init_values: Union[float, Tensor] = 1e-5,
21
+ inplace: bool = False,
22
+ ) -> None:
23
+ super().__init__()
24
+ self.inplace = inplace
25
+ self.gamma = nn.Parameter(init_values * torch.ones(dim))
26
+
27
+ def forward(self, x: Tensor) -> Tensor:
28
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
depth_anything_v2/dinov2_layers/mlp.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
10
+
11
+
12
+ from typing import Callable, Optional
13
+
14
+ from torch import Tensor, nn
15
+
16
+
17
+ class Mlp(nn.Module):
18
+ def __init__(
19
+ self,
20
+ in_features: int,
21
+ hidden_features: Optional[int] = None,
22
+ out_features: Optional[int] = None,
23
+ act_layer: Callable[..., nn.Module] = nn.GELU,
24
+ drop: float = 0.0,
25
+ bias: bool = True,
26
+ ) -> None:
27
+ super().__init__()
28
+ out_features = out_features or in_features
29
+ hidden_features = hidden_features or in_features
30
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
31
+ self.act = act_layer()
32
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
33
+ self.drop = nn.Dropout(drop)
34
+
35
+ def forward(self, x: Tensor) -> Tensor:
36
+ x = self.fc1(x)
37
+ x = self.act(x)
38
+ x = self.drop(x)
39
+ x = self.fc2(x)
40
+ x = self.drop(x)
41
+ return x
depth_anything_v2/dinov2_layers/patch_embed.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # References:
8
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
9
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
10
+
11
+ from typing import Callable, Optional, Tuple, Union
12
+
13
+ from torch import Tensor
14
+ import torch.nn as nn
15
+
16
+
17
+ def make_2tuple(x):
18
+ if isinstance(x, tuple):
19
+ assert len(x) == 2
20
+ return x
21
+
22
+ assert isinstance(x, int)
23
+ return (x, x)
24
+
25
+
26
+ class PatchEmbed(nn.Module):
27
+ """
28
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
29
+ Args:
30
+ img_size: Image size.
31
+ patch_size: Patch token size.
32
+ in_chans: Number of input image channels.
33
+ embed_dim: Number of linear projection output channels.
34
+ norm_layer: Normalization layer.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ img_size: Union[int, Tuple[int, int]] = 224,
40
+ patch_size: Union[int, Tuple[int, int]] = 16,
41
+ in_chans: int = 3,
42
+ embed_dim: int = 768,
43
+ norm_layer: Optional[Callable] = None,
44
+ flatten_embedding: bool = True,
45
+ ) -> None:
46
+ super().__init__()
47
+
48
+ image_HW = make_2tuple(img_size)
49
+ patch_HW = make_2tuple(patch_size)
50
+ patch_grid_size = (
51
+ image_HW[0] // patch_HW[0],
52
+ image_HW[1] // patch_HW[1],
53
+ )
54
+
55
+ self.img_size = image_HW
56
+ self.patch_size = patch_HW
57
+ self.patches_resolution = patch_grid_size
58
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
59
+
60
+ self.in_chans = in_chans
61
+ self.embed_dim = embed_dim
62
+
63
+ self.flatten_embedding = flatten_embedding
64
+
65
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
66
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
67
+
68
+ def forward(self, x: Tensor) -> Tensor:
69
+ _, _, H, W = x.shape
70
+ patch_H, patch_W = self.patch_size
71
+
72
+ assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
73
+ assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
74
+
75
+ x = self.proj(x) # B C H W
76
+ H, W = x.size(2), x.size(3)
77
+ x = x.flatten(2).transpose(1, 2) # B HW C
78
+ x = self.norm(x)
79
+ if not self.flatten_embedding:
80
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
81
+ return x
82
+
83
+ def flops(self) -> float:
84
+ Ho, Wo = self.patches_resolution
85
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
86
+ if self.norm is not None:
87
+ flops += Ho * Wo * self.embed_dim
88
+ return flops
depth_anything_v2/dinov2_layers/swiglu_ffn.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Callable, Optional
8
+
9
+ from torch import Tensor, nn
10
+ import torch.nn.functional as F
11
+
12
+
13
+ class SwiGLUFFN(nn.Module):
14
+ def __init__(
15
+ self,
16
+ in_features: int,
17
+ hidden_features: Optional[int] = None,
18
+ out_features: Optional[int] = None,
19
+ act_layer: Callable[..., nn.Module] = None,
20
+ drop: float = 0.0,
21
+ bias: bool = True,
22
+ ) -> None:
23
+ super().__init__()
24
+ out_features = out_features or in_features
25
+ hidden_features = hidden_features or in_features
26
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
27
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
28
+
29
+ def forward(self, x: Tensor) -> Tensor:
30
+ x12 = self.w12(x)
31
+ x1, x2 = x12.chunk(2, dim=-1)
32
+ hidden = F.silu(x1) * x2
33
+ return self.w3(hidden)
34
+
35
+
36
+ try:
37
+ from xformers.ops import SwiGLU
38
+
39
+ XFORMERS_AVAILABLE = True
40
+ except ImportError:
41
+ SwiGLU = SwiGLUFFN
42
+ XFORMERS_AVAILABLE = False
43
+
44
+
45
+ class SwiGLUFFNFused(SwiGLU):
46
+ def __init__(
47
+ self,
48
+ in_features: int,
49
+ hidden_features: Optional[int] = None,
50
+ out_features: Optional[int] = None,
51
+ act_layer: Callable[..., nn.Module] = None,
52
+ drop: float = 0.0,
53
+ bias: bool = True,
54
+ ) -> None:
55
+ out_features = out_features or in_features
56
+ hidden_features = hidden_features or in_features
57
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
58
+ super().__init__(
59
+ in_features=in_features,
60
+ hidden_features=hidden_features,
61
+ out_features=out_features,
62
+ bias=bias,
63
+ )
depth_anything_v2/dpt.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ from torchvision.transforms import Compose
6
+
7
+ from .dinov2 import DINOv2
8
+ from .util.blocks import FeatureFusionBlock, _make_scratch
9
+ from .util.transform import Resize, NormalizeImage, PrepareForNet
10
+
11
+
12
+ def _make_fusion_block(features, use_bn, size=None):
13
+ return FeatureFusionBlock(
14
+ features,
15
+ nn.ReLU(False),
16
+ deconv=False,
17
+ bn=use_bn,
18
+ expand=False,
19
+ align_corners=True,
20
+ size=size,
21
+ )
22
+
23
+
24
+ class ConvBlock(nn.Module):
25
+ def __init__(self, in_feature, out_feature):
26
+ super().__init__()
27
+
28
+ self.conv_block = nn.Sequential(
29
+ nn.Conv2d(in_feature, out_feature, kernel_size=3, stride=1, padding=1),
30
+ nn.BatchNorm2d(out_feature),
31
+ nn.ReLU(True)
32
+ )
33
+
34
+ def forward(self, x):
35
+ return self.conv_block(x)
36
+
37
+
38
+ class DPTHead(nn.Module):
39
+ def __init__(
40
+ self,
41
+ in_channels,
42
+ features=256,
43
+ use_bn=False,
44
+ out_channels=[256, 512, 1024, 1024],
45
+ use_clstoken=False
46
+ ):
47
+ super(DPTHead, self).__init__()
48
+
49
+ self.use_clstoken = use_clstoken
50
+
51
+ self.projects = nn.ModuleList([
52
+ nn.Conv2d(
53
+ in_channels=in_channels,
54
+ out_channels=out_channel,
55
+ kernel_size=1,
56
+ stride=1,
57
+ padding=0,
58
+ ) for out_channel in out_channels
59
+ ])
60
+
61
+ self.resize_layers = nn.ModuleList([
62
+ nn.ConvTranspose2d(
63
+ in_channels=out_channels[0],
64
+ out_channels=out_channels[0],
65
+ kernel_size=4,
66
+ stride=4,
67
+ padding=0),
68
+ nn.ConvTranspose2d(
69
+ in_channels=out_channels[1],
70
+ out_channels=out_channels[1],
71
+ kernel_size=2,
72
+ stride=2,
73
+ padding=0),
74
+ nn.Identity(),
75
+ nn.Conv2d(
76
+ in_channels=out_channels[3],
77
+ out_channels=out_channels[3],
78
+ kernel_size=3,
79
+ stride=2,
80
+ padding=1)
81
+ ])
82
+
83
+ if use_clstoken:
84
+ self.readout_projects = nn.ModuleList()
85
+ for _ in range(len(self.projects)):
86
+ self.readout_projects.append(
87
+ nn.Sequential(
88
+ nn.Linear(2 * in_channels, in_channels),
89
+ nn.GELU()))
90
+
91
+ self.scratch = _make_scratch(
92
+ out_channels,
93
+ features,
94
+ groups=1,
95
+ expand=False,
96
+ )
97
+
98
+ self.scratch.stem_transpose = None
99
+
100
+ self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
101
+ self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
102
+ self.scratch.refinenet3 = _make_fusion_block(features, use_bn)
103
+ self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
104
+
105
+ head_features_1 = features
106
+ head_features_2 = 32
107
+
108
+ self.scratch.output_conv1 = nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1)
109
+ self.scratch.output_conv2 = nn.Sequential(
110
+ nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
111
+ nn.ReLU(True),
112
+ nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
113
+ nn.ReLU(True),
114
+ nn.Identity(),
115
+ )
116
+
117
+ def forward(self, out_features, patch_h, patch_w):
118
+ out = []
119
+ for i, x in enumerate(out_features):
120
+ if self.use_clstoken:
121
+ x, cls_token = x[0], x[1]
122
+ readout = cls_token.unsqueeze(1).expand_as(x)
123
+ x = self.readout_projects[i](torch.cat((x, readout), -1))
124
+ else:
125
+ x = x[0]
126
+
127
+ x = x.permute(0, 2, 1).reshape((x.shape[0], x.shape[-1], patch_h, patch_w))
128
+
129
+ x = self.projects[i](x)
130
+ x = self.resize_layers[i](x)
131
+
132
+ out.append(x)
133
+
134
+ layer_1, layer_2, layer_3, layer_4 = out
135
+
136
+ layer_1_rn = self.scratch.layer1_rn(layer_1)
137
+ layer_2_rn = self.scratch.layer2_rn(layer_2)
138
+ layer_3_rn = self.scratch.layer3_rn(layer_3)
139
+ layer_4_rn = self.scratch.layer4_rn(layer_4)
140
+
141
+ path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
142
+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
143
+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
144
+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
145
+
146
+ out = self.scratch.output_conv1(path_1)
147
+ out = F.interpolate(out, (int(patch_h * 14), int(patch_w * 14)), mode="bilinear", align_corners=True)
148
+ out = self.scratch.output_conv2(out)
149
+
150
+ return out
151
+
152
+
153
+ class DepthAnythingV2(nn.Module):
154
+ def __init__(
155
+ self,
156
+ encoder='vitl',
157
+ features=256,
158
+ out_channels=[256, 512, 1024, 1024],
159
+ use_bn=False,
160
+ use_clstoken=False
161
+ ):
162
+ super(DepthAnythingV2, self).__init__()
163
+
164
+ self.intermediate_layer_idx = {
165
+ 'vits': [2, 5, 8, 11],
166
+ 'vitb': [2, 5, 8, 11],
167
+ 'vitl': [4, 11, 17, 23],
168
+ 'vitg': [9, 19, 29, 39]
169
+ }
170
+
171
+ self.encoder = encoder
172
+ self.pretrained = DINOv2(model_name=encoder)
173
+
174
+ self.depth_head = DPTHead(self.pretrained.embed_dim, features, use_bn, out_channels=out_channels, use_clstoken=use_clstoken)
175
+
176
+ def forward(self, x):
177
+ patch_h, patch_w = x.shape[-2] // 14, x.shape[-1] // 14
178
+
179
+ features = self.pretrained.get_intermediate_layers(x, self.intermediate_layer_idx[self.encoder], return_class_token=True)
180
+
181
+ depth = self.depth_head(features, patch_h, patch_w)
182
+ depth = F.relu(depth)
183
+
184
+ return depth.squeeze(1)
185
+
186
+ @torch.no_grad()
187
+ def infer_image(self, raw_image, input_size=518):
188
+ image, (h, w) = self.image2tensor(raw_image, input_size)
189
+
190
+ depth = self.forward(image)
191
+
192
+ depth = F.interpolate(depth[:, None], (h, w), mode="bilinear", align_corners=True)[0, 0]
193
+
194
+ return depth.cpu().numpy()
195
+
196
+ def image2tensor(self, raw_image, input_size=518):
197
+ transform = Compose([
198
+ Resize(
199
+ width=input_size,
200
+ height=input_size,
201
+ resize_target=False,
202
+ keep_aspect_ratio=True,
203
+ ensure_multiple_of=14,
204
+ resize_method='lower_bound',
205
+ image_interpolation_method=cv2.INTER_CUBIC,
206
+ ),
207
+ NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
208
+ PrepareForNet(),
209
+ ])
210
+
211
+ h, w = raw_image.shape[:2]
212
+
213
+ image = cv2.cvtColor(raw_image, cv2.COLOR_BGR2RGB) / 255.0
214
+
215
+ image = transform({'image': image})['image']
216
+ image = torch.from_numpy(image).unsqueeze(0)
217
+
218
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
219
+ image = image.to(DEVICE)
220
+
221
+ return image, (h, w)
depth_anything_v2/util/__pycache__/blocks.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
depth_anything_v2/util/__pycache__/transform.cpython-310.pyc ADDED
Binary file (4.7 kB). View file
 
depth_anything_v2/util/blocks.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+
3
+
4
+ def _make_scratch(in_shape, out_shape, groups=1, expand=False):
5
+ scratch = nn.Module()
6
+
7
+ out_shape1 = out_shape
8
+ out_shape2 = out_shape
9
+ out_shape3 = out_shape
10
+ if len(in_shape) >= 4:
11
+ out_shape4 = out_shape
12
+
13
+ if expand:
14
+ out_shape1 = out_shape
15
+ out_shape2 = out_shape * 2
16
+ out_shape3 = out_shape * 4
17
+ if len(in_shape) >= 4:
18
+ out_shape4 = out_shape * 8
19
+
20
+ scratch.layer1_rn = nn.Conv2d(in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
21
+ scratch.layer2_rn = nn.Conv2d(in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
22
+ scratch.layer3_rn = nn.Conv2d(in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
23
+ if len(in_shape) >= 4:
24
+ scratch.layer4_rn = nn.Conv2d(in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)
25
+
26
+ return scratch
27
+
28
+
29
+ class ResidualConvUnit(nn.Module):
30
+ """Residual convolution module.
31
+ """
32
+
33
+ def __init__(self, features, activation, bn):
34
+ """Init.
35
+ Args:
36
+ features (int): number of features
37
+ """
38
+ super().__init__()
39
+
40
+ self.bn = bn
41
+
42
+ self.groups=1
43
+
44
+ self.conv1 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
45
+
46
+ self.conv2 = nn.Conv2d(features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups)
47
+
48
+ if self.bn == True:
49
+ self.bn1 = nn.BatchNorm2d(features)
50
+ self.bn2 = nn.BatchNorm2d(features)
51
+
52
+ self.activation = activation
53
+
54
+ self.skip_add = nn.quantized.FloatFunctional()
55
+
56
+ def forward(self, x):
57
+ """Forward pass.
58
+ Args:
59
+ x (tensor): input
60
+ Returns:
61
+ tensor: output
62
+ """
63
+
64
+ out = self.activation(x)
65
+ out = self.conv1(out)
66
+ if self.bn == True:
67
+ out = self.bn1(out)
68
+
69
+ out = self.activation(out)
70
+ out = self.conv2(out)
71
+ if self.bn == True:
72
+ out = self.bn2(out)
73
+
74
+ if self.groups > 1:
75
+ out = self.conv_merge(out)
76
+
77
+ return self.skip_add.add(out, x)
78
+
79
+
80
+ class FeatureFusionBlock(nn.Module):
81
+ """Feature fusion block.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ features,
87
+ activation,
88
+ deconv=False,
89
+ bn=False,
90
+ expand=False,
91
+ align_corners=True,
92
+ size=None
93
+ ):
94
+ """Init.
95
+
96
+ Args:
97
+ features (int): number of features
98
+ """
99
+ super(FeatureFusionBlock, self).__init__()
100
+
101
+ self.deconv = deconv
102
+ self.align_corners = align_corners
103
+
104
+ self.groups=1
105
+
106
+ self.expand = expand
107
+ out_features = features
108
+ if self.expand == True:
109
+ out_features = features // 2
110
+
111
+ self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
112
+
113
+ self.resConfUnit1 = ResidualConvUnit(features, activation, bn)
114
+ self.resConfUnit2 = ResidualConvUnit(features, activation, bn)
115
+
116
+ self.skip_add = nn.quantized.FloatFunctional()
117
+
118
+ self.size=size
119
+
120
+ def forward(self, *xs, size=None):
121
+ """Forward pass.
122
+ Returns:
123
+ tensor: output
124
+ """
125
+ output = xs[0]
126
+
127
+ if len(xs) == 2:
128
+ res = self.resConfUnit1(xs[1])
129
+ output = self.skip_add.add(output, res)
130
+
131
+ output = self.resConfUnit2(output)
132
+
133
+ if (size is None) and (self.size is None):
134
+ modifier = {"scale_factor": 2}
135
+ elif size is None:
136
+ modifier = {"size": self.size}
137
+ else:
138
+ modifier = {"size": size}
139
+
140
+ output = nn.functional.interpolate(output, **modifier, mode="bilinear", align_corners=self.align_corners)
141
+
142
+ output = self.out_conv(output)
143
+
144
+ return output
depth_anything_v2/util/transform.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+
4
+
5
+ class Resize(object):
6
+ """Resize sample to given size (width, height).
7
+ """
8
+
9
+ def __init__(
10
+ self,
11
+ width,
12
+ height,
13
+ resize_target=True,
14
+ keep_aspect_ratio=False,
15
+ ensure_multiple_of=1,
16
+ resize_method="lower_bound",
17
+ image_interpolation_method=cv2.INTER_AREA,
18
+ ):
19
+ """Init.
20
+ Args:
21
+ width (int): desired output width
22
+ height (int): desired output height
23
+ resize_target (bool, optional):
24
+ True: Resize the full sample (image, mask, target).
25
+ False: Resize image only.
26
+ Defaults to True.
27
+ keep_aspect_ratio (bool, optional):
28
+ True: Keep the aspect ratio of the input sample.
29
+ Output sample might not have the given width and height, and
30
+ resize behaviour depends on the parameter 'resize_method'.
31
+ Defaults to False.
32
+ ensure_multiple_of (int, optional):
33
+ Output width and height is constrained to be multiple of this parameter.
34
+ Defaults to 1.
35
+ resize_method (str, optional):
36
+ "lower_bound": Output will be at least as large as the given size.
37
+ "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
38
+ "minimal": Scale as least as possible. (Output size might be smaller than given size.)
39
+ Defaults to "lower_bound".
40
+ """
41
+ self.__width = width
42
+ self.__height = height
43
+
44
+ self.__resize_target = resize_target
45
+ self.__keep_aspect_ratio = keep_aspect_ratio
46
+ self.__multiple_of = ensure_multiple_of
47
+ self.__resize_method = resize_method
48
+ self.__image_interpolation_method = image_interpolation_method
49
+
50
+ def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
51
+ y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
52
+
53
+ if max_val is not None and y > max_val:
54
+ y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
55
+
56
+ if y < min_val:
57
+ y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
58
+
59
+ return y
60
+
61
+ def get_size(self, width, height):
62
+ # determine new height and width
63
+ scale_height = self.__height / height
64
+ scale_width = self.__width / width
65
+
66
+ if self.__keep_aspect_ratio:
67
+ if self.__resize_method == "lower_bound":
68
+ # scale such that output size is lower bound
69
+ if scale_width > scale_height:
70
+ # fit width
71
+ scale_height = scale_width
72
+ else:
73
+ # fit height
74
+ scale_width = scale_height
75
+ elif self.__resize_method == "upper_bound":
76
+ # scale such that output size is upper bound
77
+ if scale_width < scale_height:
78
+ # fit width
79
+ scale_height = scale_width
80
+ else:
81
+ # fit height
82
+ scale_width = scale_height
83
+ elif self.__resize_method == "minimal":
84
+ # scale as least as possbile
85
+ if abs(1 - scale_width) < abs(1 - scale_height):
86
+ # fit width
87
+ scale_height = scale_width
88
+ else:
89
+ # fit height
90
+ scale_width = scale_height
91
+ else:
92
+ raise ValueError(f"resize_method {self.__resize_method} not implemented")
93
+
94
+ if self.__resize_method == "lower_bound":
95
+ new_height = self.constrain_to_multiple_of(scale_height * height, min_val=self.__height)
96
+ new_width = self.constrain_to_multiple_of(scale_width * width, min_val=self.__width)
97
+ elif self.__resize_method == "upper_bound":
98
+ new_height = self.constrain_to_multiple_of(scale_height * height, max_val=self.__height)
99
+ new_width = self.constrain_to_multiple_of(scale_width * width, max_val=self.__width)
100
+ elif self.__resize_method == "minimal":
101
+ new_height = self.constrain_to_multiple_of(scale_height * height)
102
+ new_width = self.constrain_to_multiple_of(scale_width * width)
103
+ else:
104
+ raise ValueError(f"resize_method {self.__resize_method} not implemented")
105
+
106
+ return (new_width, new_height)
107
+
108
+ def __call__(self, sample):
109
+ width, height = self.get_size(sample["image"].shape[1], sample["image"].shape[0])
110
+
111
+ # resize sample
112
+ sample["image"] = cv2.resize(sample["image"], (width, height), interpolation=self.__image_interpolation_method)
113
+
114
+ if self.__resize_target:
115
+ if "depth" in sample:
116
+ sample["depth"] = cv2.resize(sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST)
117
+
118
+ if "mask" in sample:
119
+ sample["mask"] = cv2.resize(sample["mask"].astype(np.float32), (width, height), interpolation=cv2.INTER_NEAREST)
120
+
121
+ return sample
122
+
123
+
124
+ class NormalizeImage(object):
125
+ """Normlize image by given mean and std.
126
+ """
127
+
128
+ def __init__(self, mean, std):
129
+ self.__mean = mean
130
+ self.__std = std
131
+
132
+ def __call__(self, sample):
133
+ sample["image"] = (sample["image"] - self.__mean) / self.__std
134
+
135
+ return sample
136
+
137
+
138
+ class PrepareForNet(object):
139
+ """Prepare sample for usage as network input.
140
+ """
141
+
142
+ def __init__(self):
143
+ pass
144
+
145
+ def __call__(self, sample):
146
+ image = np.transpose(sample["image"], (2, 0, 1))
147
+ sample["image"] = np.ascontiguousarray(image).astype(np.float32)
148
+
149
+ if "depth" in sample:
150
+ depth = sample["depth"].astype(np.float32)
151
+ sample["depth"] = np.ascontiguousarray(depth)
152
+
153
+ if "mask" in sample:
154
+ sample["mask"] = sample["mask"].astype(np.float32)
155
+ sample["mask"] = np.ascontiguousarray(sample["mask"])
156
+
157
+ return sample
pipeline_flux_controlnet_inpaint.py DELETED
@@ -1,1046 +0,0 @@
1
- import inspect
2
- from typing import Any, Callable, Dict, List, Optional, Union
3
-
4
- import numpy as np
5
- import torch
6
- from transformers import (
7
- CLIPTextModel,
8
- CLIPTokenizer,
9
- T5EncoderModel,
10
- T5TokenizerFast,
11
- )
12
-
13
- from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
14
- from diffusers.loaders import FluxLoraLoaderMixin
15
- from diffusers.models.autoencoders import AutoencoderKL
16
-
17
- from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
18
- from diffusers.utils import (
19
- USE_PEFT_BACKEND,
20
- is_torch_xla_available,
21
- logging,
22
- replace_example_docstring,
23
- scale_lora_layers,
24
- unscale_lora_layers,
25
- )
26
- from diffusers.utils.torch_utils import randn_tensor
27
- from diffusers.pipelines.pipeline_utils import DiffusionPipeline
28
- from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
29
-
30
- from transformer_flux import FluxTransformer2DModel
31
- from controlnet_flux import FluxControlNetModel
32
-
33
- if is_torch_xla_available():
34
- import torch_xla.core.xla_model as xm
35
-
36
- XLA_AVAILABLE = True
37
- else:
38
- XLA_AVAILABLE = False
39
-
40
-
41
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
-
43
- EXAMPLE_DOC_STRING = """
44
- Examples:
45
- ```py
46
- >>> import torch
47
- >>> from diffusers.utils import load_image
48
- >>> from diffusers import FluxControlNetPipeline
49
- >>> from diffusers import FluxControlNetModel
50
-
51
- >>> controlnet_model = "InstantX/FLUX.1-dev-controlnet-canny-alpha"
52
- >>> controlnet = FluxControlNetModel.from_pretrained(controlnet_model, torch_dtype=torch.bfloat16)
53
- >>> pipe = FluxControlNetPipeline.from_pretrained(
54
- ... base_model, controlnet=controlnet, torch_dtype=torch.bfloat16
55
- ... )
56
- >>> pipe.to("cuda")
57
- >>> control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
58
- >>> control_mask = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
59
- >>> prompt = "A girl in city, 25 years old, cool, futuristic"
60
- >>> image = pipe(
61
- ... prompt,
62
- ... control_image=control_image,
63
- ... controlnet_conditioning_scale=0.6,
64
- ... num_inference_steps=28,
65
- ... guidance_scale=3.5,
66
- ... ).images[0]
67
- >>> image.save("flux.png")
68
- ```
69
- """
70
-
71
-
72
- # Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
73
- def calculate_shift(
74
- image_seq_len,
75
- base_seq_len: int = 256,
76
- max_seq_len: int = 4096,
77
- base_shift: float = 0.5,
78
- max_shift: float = 1.16,
79
- ):
80
- m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
81
- b = base_shift - m * base_seq_len
82
- mu = image_seq_len * m + b
83
- return mu
84
-
85
-
86
- # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
87
- def retrieve_timesteps(
88
- scheduler,
89
- num_inference_steps: Optional[int] = None,
90
- device: Optional[Union[str, torch.device]] = None,
91
- timesteps: Optional[List[int]] = None,
92
- sigmas: Optional[List[float]] = None,
93
- **kwargs,
94
- ):
95
- """
96
- Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
97
- custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
98
-
99
- Args:
100
- scheduler (`SchedulerMixin`):
101
- The scheduler to get timesteps from.
102
- num_inference_steps (`int`):
103
- The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
104
- must be `None`.
105
- device (`str` or `torch.device`, *optional*):
106
- The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
107
- timesteps (`List[int]`, *optional*):
108
- Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
109
- `num_inference_steps` and `sigmas` must be `None`.
110
- sigmas (`List[float]`, *optional*):
111
- Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
112
- `num_inference_steps` and `timesteps` must be `None`.
113
-
114
- Returns:
115
- `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
116
- second element is the number of inference steps.
117
- """
118
- if timesteps is not None and sigmas is not None:
119
- raise ValueError(
120
- "Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values"
121
- )
122
- if timesteps is not None:
123
- accepts_timesteps = "timesteps" in set(
124
- inspect.signature(scheduler.set_timesteps).parameters.keys()
125
- )
126
- if not accepts_timesteps:
127
- raise ValueError(
128
- f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
129
- f" timestep schedules. Please check whether you are using the correct scheduler."
130
- )
131
- scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
132
- timesteps = scheduler.timesteps
133
- num_inference_steps = len(timesteps)
134
- elif sigmas is not None:
135
- accept_sigmas = "sigmas" in set(
136
- inspect.signature(scheduler.set_timesteps).parameters.keys()
137
- )
138
- if not accept_sigmas:
139
- raise ValueError(
140
- f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
141
- f" sigmas schedules. Please check whether you are using the correct scheduler."
142
- )
143
- scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
144
- timesteps = scheduler.timesteps
145
- num_inference_steps = len(timesteps)
146
- else:
147
- scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
148
- timesteps = scheduler.timesteps
149
- return timesteps, num_inference_steps
150
-
151
-
152
- class FluxControlNetInpaintingPipeline(DiffusionPipeline, FluxLoraLoaderMixin):
153
- r"""
154
- The Flux pipeline for text-to-image generation.
155
-
156
- Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
157
-
158
- Args:
159
- transformer ([`FluxTransformer2DModel`]):
160
- Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
161
- scheduler ([`FlowMatchEulerDiscreteScheduler`]):
162
- A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
163
- vae ([`AutoencoderKL`]):
164
- Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
165
- text_encoder ([`CLIPTextModel`]):
166
- [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
167
- the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
168
- text_encoder_2 ([`T5EncoderModel`]):
169
- [T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
170
- the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
171
- tokenizer (`CLIPTokenizer`):
172
- Tokenizer of class
173
- [CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
174
- tokenizer_2 (`T5TokenizerFast`):
175
- Second Tokenizer of class
176
- [T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
177
- """
178
-
179
- model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
180
- _optional_components = []
181
- _callback_tensor_inputs = ["latents", "prompt_embeds"]
182
-
183
- def __init__(
184
- self,
185
- scheduler: FlowMatchEulerDiscreteScheduler,
186
- vae: AutoencoderKL,
187
- text_encoder: CLIPTextModel,
188
- tokenizer: CLIPTokenizer,
189
- text_encoder_2: T5EncoderModel,
190
- tokenizer_2: T5TokenizerFast,
191
- transformer: FluxTransformer2DModel,
192
- controlnet: FluxControlNetModel,
193
- ):
194
- super().__init__()
195
-
196
- self.register_modules(
197
- vae=vae,
198
- text_encoder=text_encoder,
199
- text_encoder_2=text_encoder_2,
200
- tokenizer=tokenizer,
201
- tokenizer_2=tokenizer_2,
202
- transformer=transformer,
203
- scheduler=scheduler,
204
- controlnet=controlnet,
205
- )
206
- self.vae_scale_factor = (
207
- 2 ** (len(self.vae.config.block_out_channels))
208
- if hasattr(self, "vae") and self.vae is not None
209
- else 16
210
- )
211
- self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_resize=True, do_convert_rgb=True, do_normalize=True)
212
- self.mask_processor = VaeImageProcessor(
213
- vae_scale_factor=self.vae_scale_factor,
214
- do_resize=True,
215
- do_convert_grayscale=True,
216
- do_normalize=False,
217
- do_binarize=True,
218
- )
219
- self.tokenizer_max_length = (
220
- self.tokenizer.model_max_length
221
- if hasattr(self, "tokenizer") and self.tokenizer is not None
222
- else 77
223
- )
224
- self.default_sample_size = 64
225
-
226
- @property
227
- def do_classifier_free_guidance(self):
228
- return self._guidance_scale > 1
229
-
230
- def _get_t5_prompt_embeds(
231
- self,
232
- prompt: Union[str, List[str]] = None,
233
- num_images_per_prompt: int = 1,
234
- max_sequence_length: int = 512,
235
- device: Optional[torch.device] = None,
236
- dtype: Optional[torch.dtype] = None,
237
- ):
238
- device = device or self._execution_device
239
- dtype = dtype or self.text_encoder.dtype
240
-
241
- prompt = [prompt] if isinstance(prompt, str) else prompt
242
- batch_size = len(prompt)
243
-
244
- text_inputs = self.tokenizer_2(
245
- prompt,
246
- padding="max_length",
247
- max_length=max_sequence_length,
248
- truncation=True,
249
- return_length=False,
250
- return_overflowing_tokens=False,
251
- return_tensors="pt",
252
- )
253
- text_input_ids = text_inputs.input_ids
254
- untruncated_ids = self.tokenizer_2(
255
- prompt, padding="longest", return_tensors="pt"
256
- ).input_ids
257
-
258
- if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
259
- text_input_ids, untruncated_ids
260
- ):
261
- removed_text = self.tokenizer_2.batch_decode(
262
- untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
263
- )
264
- logger.warning(
265
- "The following part of your input was truncated because `max_sequence_length` is set to "
266
- f" {max_sequence_length} tokens: {removed_text}"
267
- )
268
-
269
- prompt_embeds = self.text_encoder_2(
270
- text_input_ids.to(device), output_hidden_states=False
271
- )[0]
272
-
273
- dtype = self.text_encoder_2.dtype
274
- prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
275
-
276
- _, seq_len, _ = prompt_embeds.shape
277
-
278
- # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
279
- prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
280
- prompt_embeds = prompt_embeds.view(
281
- batch_size * num_images_per_prompt, seq_len, -1
282
- )
283
-
284
- return prompt_embeds
285
-
286
- def _get_clip_prompt_embeds(
287
- self,
288
- prompt: Union[str, List[str]],
289
- num_images_per_prompt: int = 1,
290
- device: Optional[torch.device] = None,
291
- ):
292
- device = device or self._execution_device
293
-
294
- prompt = [prompt] if isinstance(prompt, str) else prompt
295
- batch_size = len(prompt)
296
-
297
- text_inputs = self.tokenizer(
298
- prompt,
299
- padding="max_length",
300
- max_length=self.tokenizer_max_length,
301
- truncation=True,
302
- return_overflowing_tokens=False,
303
- return_length=False,
304
- return_tensors="pt",
305
- )
306
-
307
- text_input_ids = text_inputs.input_ids
308
- untruncated_ids = self.tokenizer(
309
- prompt, padding="longest", return_tensors="pt"
310
- ).input_ids
311
- if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
312
- text_input_ids, untruncated_ids
313
- ):
314
- removed_text = self.tokenizer.batch_decode(
315
- untruncated_ids[:, self.tokenizer_max_length - 1 : -1]
316
- )
317
- logger.warning(
318
- "The following part of your input was truncated because CLIP can only handle sequences up to"
319
- f" {self.tokenizer_max_length} tokens: {removed_text}"
320
- )
321
- prompt_embeds = self.text_encoder(
322
- text_input_ids.to(device), output_hidden_states=False
323
- )
324
-
325
- # Use pooled output of CLIPTextModel
326
- prompt_embeds = prompt_embeds.pooler_output
327
- prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
328
-
329
- # duplicate text embeddings for each generation per prompt, using mps friendly method
330
- prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
331
- prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
332
-
333
- return prompt_embeds
334
-
335
- def encode_prompt(
336
- self,
337
- prompt: Union[str, List[str]],
338
- prompt_2: Union[str, List[str]],
339
- device: Optional[torch.device] = None,
340
- num_images_per_prompt: int = 1,
341
- do_classifier_free_guidance: bool = True,
342
- negative_prompt: Optional[Union[str, List[str]]] = None,
343
- negative_prompt_2: Optional[Union[str, List[str]]] = None,
344
- prompt_embeds: Optional[torch.FloatTensor] = None,
345
- pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
346
- max_sequence_length: int = 512,
347
- lora_scale: Optional[float] = None,
348
- ):
349
- r"""
350
-
351
- Args:
352
- prompt (`str` or `List[str]`, *optional*):
353
- prompt to be encoded
354
- prompt_2 (`str` or `List[str]`, *optional*):
355
- The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
356
- used in all text-encoders
357
- device: (`torch.device`):
358
- torch device
359
- num_images_per_prompt (`int`):
360
- number of images that should be generated per prompt
361
- do_classifier_free_guidance (`bool`):
362
- whether to use classifier-free guidance or not
363
- negative_prompt (`str` or `List[str]`, *optional*):
364
- negative prompt to be encoded
365
- negative_prompt_2 (`str` or `List[str]`, *optional*):
366
- negative prompt to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `negative_prompt` is
367
- used in all text-encoders
368
- prompt_embeds (`torch.FloatTensor`, *optional*):
369
- Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
370
- provided, text embeddings will be generated from `prompt` input argument.
371
- pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
372
- Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
373
- If not provided, pooled text embeddings will be generated from `prompt` input argument.
374
- clip_skip (`int`, *optional*):
375
- Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
376
- the output of the pre-final layer will be used for computing the prompt embeddings.
377
- lora_scale (`float`, *optional*):
378
- A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
379
- """
380
- device = device or self._execution_device
381
-
382
- # set lora scale so that monkey patched LoRA
383
- # function of text encoder can correctly access it
384
- if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
385
- self._lora_scale = lora_scale
386
-
387
- # dynamically adjust the LoRA scale
388
- if self.text_encoder is not None and USE_PEFT_BACKEND:
389
- scale_lora_layers(self.text_encoder, lora_scale)
390
- if self.text_encoder_2 is not None and USE_PEFT_BACKEND:
391
- scale_lora_layers(self.text_encoder_2, lora_scale)
392
-
393
- prompt = [prompt] if isinstance(prompt, str) else prompt
394
- if prompt is not None:
395
- batch_size = len(prompt)
396
- else:
397
- batch_size = prompt_embeds.shape[0]
398
-
399
- if prompt_embeds is None:
400
- prompt_2 = prompt_2 or prompt
401
- prompt_2 = [prompt_2] if isinstance(prompt_2, str) else prompt_2
402
-
403
- # We only use the pooled prompt output from the CLIPTextModel
404
- pooled_prompt_embeds = self._get_clip_prompt_embeds(
405
- prompt=prompt,
406
- device=device,
407
- num_images_per_prompt=num_images_per_prompt,
408
- )
409
- prompt_embeds = self._get_t5_prompt_embeds(
410
- prompt=prompt_2,
411
- num_images_per_prompt=num_images_per_prompt,
412
- max_sequence_length=max_sequence_length,
413
- device=device,
414
- )
415
-
416
- if do_classifier_free_guidance:
417
- # 处理 negative prompt
418
- negative_prompt = negative_prompt or ""
419
- negative_prompt_2 = negative_prompt_2 or negative_prompt
420
-
421
- negative_pooled_prompt_embeds = self._get_clip_prompt_embeds(
422
- negative_prompt,
423
- device=device,
424
- num_images_per_prompt=num_images_per_prompt,
425
- )
426
- negative_prompt_embeds = self._get_t5_prompt_embeds(
427
- negative_prompt_2,
428
- num_images_per_prompt=num_images_per_prompt,
429
- max_sequence_length=max_sequence_length,
430
- device=device,
431
- )
432
-
433
- if self.text_encoder is not None:
434
- if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
435
- # Retrieve the original scale by scaling back the LoRA layers
436
- unscale_lora_layers(self.text_encoder, lora_scale)
437
-
438
- if self.text_encoder_2 is not None:
439
- if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
440
- # Retrieve the original scale by scaling back the LoRA layers
441
- unscale_lora_layers(self.text_encoder_2, lora_scale)
442
-
443
- text_ids = torch.zeros(batch_size, prompt_embeds.shape[1], 3).to(
444
- device=device, dtype=self.text_encoder.dtype
445
- )
446
-
447
- return prompt_embeds, pooled_prompt_embeds, negative_prompt_embeds, negative_pooled_prompt_embeds,text_ids
448
-
449
- def check_inputs(
450
- self,
451
- prompt,
452
- prompt_2,
453
- height,
454
- width,
455
- prompt_embeds=None,
456
- pooled_prompt_embeds=None,
457
- callback_on_step_end_tensor_inputs=None,
458
- max_sequence_length=None,
459
- ):
460
- if height % 8 != 0 or width % 8 != 0:
461
- raise ValueError(
462
- f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
463
- )
464
-
465
- if callback_on_step_end_tensor_inputs is not None and not all(
466
- k in self._callback_tensor_inputs
467
- for k in callback_on_step_end_tensor_inputs
468
- ):
469
- raise ValueError(
470
- f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
471
- )
472
-
473
- if prompt is not None and prompt_embeds is not None:
474
- raise ValueError(
475
- f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
476
- " only forward one of the two."
477
- )
478
- elif prompt_2 is not None and prompt_embeds is not None:
479
- raise ValueError(
480
- f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
481
- " only forward one of the two."
482
- )
483
- elif prompt is None and prompt_embeds is None:
484
- raise ValueError(
485
- "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
486
- )
487
- elif prompt is not None and (
488
- not isinstance(prompt, str) and not isinstance(prompt, list)
489
- ):
490
- raise ValueError(
491
- f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
492
- )
493
- elif prompt_2 is not None and (
494
- not isinstance(prompt_2, str) and not isinstance(prompt_2, list)
495
- ):
496
- raise ValueError(
497
- f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}"
498
- )
499
-
500
- if prompt_embeds is not None and pooled_prompt_embeds is None:
501
- raise ValueError(
502
- "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
503
- )
504
-
505
- if max_sequence_length is not None and max_sequence_length > 512:
506
- raise ValueError(
507
- f"`max_sequence_length` cannot be greater than 512 but is {max_sequence_length}"
508
- )
509
-
510
- # Copied from diffusers.pipelines.flux.pipeline_flux._prepare_latent_image_ids
511
- @staticmethod
512
- def _prepare_latent_image_ids(batch_size, height, width, device, dtype):
513
- latent_image_ids = torch.zeros(height // 2, width // 2, 3)
514
- latent_image_ids[..., 1] = (
515
- latent_image_ids[..., 1] + torch.arange(height // 2)[:, None]
516
- )
517
- latent_image_ids[..., 2] = (
518
- latent_image_ids[..., 2] + torch.arange(width // 2)[None, :]
519
- )
520
-
521
- (
522
- latent_image_id_height,
523
- latent_image_id_width,
524
- latent_image_id_channels,
525
- ) = latent_image_ids.shape
526
-
527
- latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1)
528
- latent_image_ids = latent_image_ids.reshape(
529
- batch_size,
530
- latent_image_id_height * latent_image_id_width,
531
- latent_image_id_channels,
532
- )
533
-
534
- return latent_image_ids.to(device=device, dtype=dtype)
535
-
536
- # Copied from diffusers.pipelines.flux.pipeline_flux._pack_latents
537
- @staticmethod
538
- def _pack_latents(latents, batch_size, num_channels_latents, height, width):
539
- latents = latents.view(
540
- batch_size, num_channels_latents, height // 2, 2, width // 2, 2
541
- )
542
- latents = latents.permute(0, 2, 4, 1, 3, 5)
543
- latents = latents.reshape(
544
- batch_size, (height // 2) * (width // 2), num_channels_latents * 4
545
- )
546
-
547
- return latents
548
-
549
- # Copied from diffusers.pipelines.flux.pipeline_flux._unpack_latents
550
- @staticmethod
551
- def _unpack_latents(latents, height, width, vae_scale_factor):
552
- batch_size, num_patches, channels = latents.shape
553
-
554
- height = height // vae_scale_factor
555
- width = width // vae_scale_factor
556
-
557
- latents = latents.view(batch_size, height, width, channels // 4, 2, 2)
558
- latents = latents.permute(0, 3, 1, 4, 2, 5)
559
-
560
- latents = latents.reshape(
561
- batch_size, channels // (2 * 2), height * 2, width * 2
562
- )
563
-
564
- return latents
565
-
566
- # Copied from diffusers.pipelines.flux.pipeline_flux.prepare_latents
567
- def prepare_latents(
568
- self,
569
- batch_size,
570
- num_channels_latents,
571
- height,
572
- width,
573
- dtype,
574
- device,
575
- generator,
576
- latents=None,
577
- ):
578
- height = 2 * (int(height) // self.vae_scale_factor)
579
- width = 2 * (int(width) // self.vae_scale_factor)
580
-
581
- shape = (batch_size, num_channels_latents, height, width)
582
-
583
- if latents is not None:
584
- latent_image_ids = self._prepare_latent_image_ids(
585
- batch_size, height, width, device, dtype
586
- )
587
- return latents.to(device=device, dtype=dtype), latent_image_ids
588
-
589
- if isinstance(generator, list) and len(generator) != batch_size:
590
- raise ValueError(
591
- f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
592
- f" size of {batch_size}. Make sure the batch size matches the length of the generators."
593
- )
594
-
595
- latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
596
- latents = self._pack_latents(
597
- latents, batch_size, num_channels_latents, height, width
598
- )
599
-
600
- latent_image_ids = self._prepare_latent_image_ids(
601
- batch_size, height, width, device, dtype
602
- )
603
-
604
- return latents, latent_image_ids
605
-
606
- # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image
607
- def prepare_image(
608
- self,
609
- image,
610
- width,
611
- height,
612
- batch_size,
613
- num_images_per_prompt,
614
- device,
615
- dtype,
616
- ):
617
- if isinstance(image, torch.Tensor):
618
- pass
619
- else:
620
- image = self.image_processor.preprocess(image, height=height, width=width)
621
-
622
- image_batch_size = image.shape[0]
623
-
624
- if image_batch_size == 1:
625
- repeat_by = batch_size
626
- else:
627
- # image batch size is the same as prompt batch size
628
- repeat_by = num_images_per_prompt
629
-
630
- image = image.repeat_interleave(repeat_by, dim=0)
631
-
632
- image = image.to(device=device, dtype=dtype)
633
-
634
- return image
635
-
636
- def prepare_image_with_mask(
637
- self,
638
- image,
639
- mask,
640
- width,
641
- height,
642
- batch_size,
643
- num_images_per_prompt,
644
- device,
645
- dtype,
646
- do_classifier_free_guidance = False,
647
- ):
648
- # Prepare image
649
- if isinstance(image, torch.Tensor):
650
- pass
651
- else:
652
- image = self.image_processor.preprocess(image, height=height, width=width)
653
-
654
- image_batch_size = image.shape[0]
655
- if image_batch_size == 1:
656
- repeat_by = batch_size
657
- else:
658
- # image batch size is the same as prompt batch size
659
- repeat_by = num_images_per_prompt
660
- image = image.repeat_interleave(repeat_by, dim=0)
661
- image = image.to(device=device, dtype=dtype)
662
-
663
- # Prepare mask
664
- if isinstance(mask, torch.Tensor):
665
- pass
666
- else:
667
- mask = self.mask_processor.preprocess(mask, height=height, width=width)
668
- mask = mask.repeat_interleave(repeat_by, dim=0)
669
- mask = mask.to(device=device, dtype=dtype)
670
-
671
- # Get masked image
672
- masked_image = image.clone()
673
- masked_image[(mask > 0.5).repeat(1, 3, 1, 1)] = -1
674
-
675
- # Encode to latents
676
- image_latents = self.vae.encode(masked_image.to(self.vae.dtype)).latent_dist.sample()
677
- image_latents = (
678
- image_latents - self.vae.config.shift_factor
679
- ) * self.vae.config.scaling_factor
680
- image_latents = image_latents.to(dtype)
681
-
682
- mask = torch.nn.functional.interpolate(
683
- mask, size=(height // self.vae_scale_factor * 2, width // self.vae_scale_factor * 2)
684
- )
685
- mask = 1 - mask
686
-
687
- control_image = torch.cat([image_latents, mask], dim=1)
688
-
689
- # Pack cond latents
690
- packed_control_image = self._pack_latents(
691
- control_image,
692
- batch_size * num_images_per_prompt,
693
- control_image.shape[1],
694
- control_image.shape[2],
695
- control_image.shape[3],
696
- )
697
-
698
- if do_classifier_free_guidance:
699
- packed_control_image = torch.cat([packed_control_image] * 2)
700
-
701
- return packed_control_image, height, width
702
-
703
- @property
704
- def guidance_scale(self):
705
- return self._guidance_scale
706
-
707
- @property
708
- def joint_attention_kwargs(self):
709
- return self._joint_attention_kwargs
710
-
711
- @property
712
- def num_timesteps(self):
713
- return self._num_timesteps
714
-
715
- @property
716
- def interrupt(self):
717
- return self._interrupt
718
-
719
- @torch.no_grad()
720
- @replace_example_docstring(EXAMPLE_DOC_STRING)
721
- def __call__(
722
- self,
723
- prompt: Union[str, List[str]] = None,
724
- prompt_2: Optional[Union[str, List[str]]] = None,
725
- height: Optional[int] = None,
726
- width: Optional[int] = None,
727
- num_inference_steps: int = 28,
728
- timesteps: List[int] = None,
729
- guidance_scale: float = 7.0,
730
- true_guidance_scale: float = 3.5 ,
731
- negative_prompt: Optional[Union[str, List[str]]] = None,
732
- negative_prompt_2: Optional[Union[str, List[str]]] = None,
733
- control_image: PipelineImageInput = None,
734
- control_mask: PipelineImageInput = None,
735
- controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
736
- num_images_per_prompt: Optional[int] = 1,
737
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
738
- latents: Optional[torch.FloatTensor] = None,
739
- prompt_embeds: Optional[torch.FloatTensor] = None,
740
- pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
741
- output_type: Optional[str] = "pil",
742
- return_dict: bool = True,
743
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
744
- callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
745
- callback_on_step_end_tensor_inputs: List[str] = ["latents"],
746
- max_sequence_length: int = 512,
747
- ):
748
- r"""
749
- Function invoked when calling the pipeline for generation.
750
-
751
- Args:
752
- prompt (`str` or `List[str]`, *optional*):
753
- The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
754
- instead.
755
- prompt_2 (`str` or `List[str]`, *optional*):
756
- The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
757
- will be used instead
758
- height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
759
- The height in pixels of the generated image. This is set to 1024 by default for the best results.
760
- width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
761
- The width in pixels of the generated image. This is set to 1024 by default for the best results.
762
- num_inference_steps (`int`, *optional*, defaults to 50):
763
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
764
- expense of slower inference.
765
- timesteps (`List[int]`, *optional*):
766
- Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
767
- in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
768
- passed will be used. Must be in descending order.
769
- guidance_scale (`float`, *optional*, defaults to 7.0):
770
- Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
771
- `guidance_scale` is defined as `w` of equation 2. of [Imagen
772
- Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
773
- 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
774
- usually at the expense of lower image quality.
775
- num_images_per_prompt (`int`, *optional*, defaults to 1):
776
- The number of images to generate per prompt.
777
- generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
778
- One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
779
- to make generation deterministic.
780
- latents (`torch.FloatTensor`, *optional*):
781
- Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
782
- generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
783
- tensor will ge generated by sampling using the supplied random `generator`.
784
- prompt_embeds (`torch.FloatTensor`, *optional*):
785
- Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
786
- provided, text embeddings will be generated from `prompt` input argument.
787
- pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
788
- Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
789
- If not provided, pooled text embeddings will be generated from `prompt` input argument.
790
- output_type (`str`, *optional*, defaults to `"pil"`):
791
- The output format of the generate image. Choose between
792
- [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
793
- return_dict (`bool`, *optional*, defaults to `True`):
794
- Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
795
- joint_attention_kwargs (`dict`, *optional*):
796
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
797
- `self.processor` in
798
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
799
- callback_on_step_end (`Callable`, *optional*):
800
- A function that calls at the end of each denoising steps during the inference. The function is called
801
- with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
802
- callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
803
- `callback_on_step_end_tensor_inputs`.
804
- callback_on_step_end_tensor_inputs (`List`, *optional*):
805
- The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
806
- will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
807
- `._callback_tensor_inputs` attribute of your pipeline class.
808
- max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
809
-
810
- Examples:
811
-
812
- Returns:
813
- [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
814
- is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
815
- images.
816
- """
817
-
818
- height = height or self.default_sample_size * self.vae_scale_factor
819
- width = width or self.default_sample_size * self.vae_scale_factor
820
-
821
- # 1. Check inputs. Raise error if not correct
822
- self.check_inputs(
823
- prompt,
824
- prompt_2,
825
- height,
826
- width,
827
- prompt_embeds=prompt_embeds,
828
- pooled_prompt_embeds=pooled_prompt_embeds,
829
- callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
830
- max_sequence_length=max_sequence_length,
831
- )
832
-
833
- self._guidance_scale = true_guidance_scale
834
- self._joint_attention_kwargs = joint_attention_kwargs
835
- self._interrupt = False
836
-
837
- # 2. Define call parameters
838
- if prompt is not None and isinstance(prompt, str):
839
- batch_size = 1
840
- elif prompt is not None and isinstance(prompt, list):
841
- batch_size = len(prompt)
842
- else:
843
- batch_size = prompt_embeds.shape[0]
844
-
845
- device = self._execution_device
846
- dtype = self.transformer.dtype
847
-
848
- lora_scale = (
849
- self.joint_attention_kwargs.get("scale", None)
850
- if self.joint_attention_kwargs is not None
851
- else None
852
- )
853
- (
854
- prompt_embeds,
855
- pooled_prompt_embeds,
856
- negative_prompt_embeds,
857
- negative_pooled_prompt_embeds,
858
- text_ids
859
- ) = self.encode_prompt(
860
- prompt=prompt,
861
- prompt_2=prompt_2,
862
- prompt_embeds=prompt_embeds,
863
- pooled_prompt_embeds=pooled_prompt_embeds,
864
- do_classifier_free_guidance = self.do_classifier_free_guidance,
865
- negative_prompt = negative_prompt,
866
- negative_prompt_2 = negative_prompt_2,
867
- device=device,
868
- num_images_per_prompt=num_images_per_prompt,
869
- max_sequence_length=max_sequence_length,
870
- lora_scale=lora_scale,
871
- )
872
-
873
- # 在 encode_prompt 之后
874
- if self.do_classifier_free_guidance:
875
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim = 0)
876
- pooled_prompt_embeds = torch.cat([negative_pooled_prompt_embeds, pooled_prompt_embeds], dim = 0)
877
- text_ids = torch.cat([text_ids, text_ids], dim = 0)
878
-
879
- # 3. Prepare control image
880
- num_channels_latents = self.transformer.config.in_channels // 4
881
- if isinstance(self.controlnet, FluxControlNetModel):
882
- control_image, height, width = self.prepare_image_with_mask(
883
- image=control_image,
884
- mask=control_mask,
885
- width=width,
886
- height=height,
887
- batch_size=batch_size * num_images_per_prompt,
888
- num_images_per_prompt=num_images_per_prompt,
889
- device=device,
890
- dtype=dtype,
891
- do_classifier_free_guidance=self.do_classifier_free_guidance,
892
- )
893
-
894
- # 4. Prepare latent variables
895
- num_channels_latents = self.transformer.config.in_channels // 4
896
- latents, latent_image_ids = self.prepare_latents(
897
- batch_size * num_images_per_prompt,
898
- num_channels_latents,
899
- height,
900
- width,
901
- prompt_embeds.dtype,
902
- device,
903
- generator,
904
- latents,
905
- )
906
-
907
- if self.do_classifier_free_guidance:
908
- latent_image_ids = torch.cat([latent_image_ids] * 2)
909
-
910
- # 5. Prepare timesteps
911
- sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
912
- image_seq_len = latents.shape[1]
913
- mu = calculate_shift(
914
- image_seq_len,
915
- self.scheduler.config.base_image_seq_len,
916
- self.scheduler.config.max_image_seq_len,
917
- self.scheduler.config.base_shift,
918
- self.scheduler.config.max_shift,
919
- )
920
- timesteps, num_inference_steps = retrieve_timesteps(
921
- self.scheduler,
922
- num_inference_steps,
923
- device,
924
- timesteps,
925
- sigmas,
926
- mu=mu,
927
- )
928
-
929
- num_warmup_steps = max(
930
- len(timesteps) - num_inference_steps * self.scheduler.order, 0
931
- )
932
- self._num_timesteps = len(timesteps)
933
-
934
- # 6. Denoising loop
935
- with self.progress_bar(total=num_inference_steps) as progress_bar:
936
- for i, t in enumerate(timesteps):
937
- if self.interrupt:
938
- continue
939
-
940
- latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
941
-
942
- # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
943
- timestep = t.expand(latent_model_input.shape[0]).to(latent_model_input.dtype)
944
-
945
- # handle guidance
946
- if self.transformer.config.guidance_embeds:
947
- guidance = torch.tensor([guidance_scale], device=device)
948
- guidance = guidance.expand(latent_model_input.shape[0])
949
- else:
950
- guidance = None
951
-
952
- # controlnet
953
- (
954
- controlnet_block_samples,
955
- controlnet_single_block_samples,
956
- ) = self.controlnet(
957
- hidden_states=latent_model_input,
958
- controlnet_cond=control_image,
959
- conditioning_scale=controlnet_conditioning_scale,
960
- timestep=timestep / 1000,
961
- guidance=guidance,
962
- pooled_projections=pooled_prompt_embeds,
963
- encoder_hidden_states=prompt_embeds,
964
- txt_ids=text_ids,
965
- img_ids=latent_image_ids,
966
- joint_attention_kwargs=self.joint_attention_kwargs,
967
- return_dict=False,
968
- )
969
-
970
- noise_pred = self.transformer(
971
- hidden_states=latent_model_input,
972
- # YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
973
- timestep=timestep / 1000,
974
- guidance=guidance,
975
- pooled_projections=pooled_prompt_embeds,
976
- encoder_hidden_states=prompt_embeds,
977
- controlnet_block_samples=[
978
- sample.to(dtype=self.transformer.dtype)
979
- for sample in controlnet_block_samples
980
- ],
981
- controlnet_single_block_samples=[
982
- sample.to(dtype=self.transformer.dtype)
983
- for sample in controlnet_single_block_samples
984
- ] if controlnet_single_block_samples is not None else controlnet_single_block_samples,
985
- txt_ids=text_ids,
986
- img_ids=latent_image_ids,
987
- joint_attention_kwargs=self.joint_attention_kwargs,
988
- return_dict=False,
989
- )[0]
990
-
991
- # 在生成循环中
992
- if self.do_classifier_free_guidance:
993
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
994
- noise_pred = noise_pred_uncond + true_guidance_scale * (noise_pred_text - noise_pred_uncond)
995
-
996
- # compute the previous noisy sample x_t -> x_t-1
997
- latents_dtype = latents.dtype
998
- latents = self.scheduler.step(
999
- noise_pred, t, latents, return_dict=False
1000
- )[0]
1001
-
1002
- if latents.dtype != latents_dtype:
1003
- if torch.backends.mps.is_available():
1004
- # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
1005
- latents = latents.to(latents_dtype)
1006
-
1007
- if callback_on_step_end is not None:
1008
- callback_kwargs = {}
1009
- for k in callback_on_step_end_tensor_inputs:
1010
- callback_kwargs[k] = locals()[k]
1011
- callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1012
-
1013
- latents = callback_outputs.pop("latents", latents)
1014
- prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1015
-
1016
- # call the callback, if provided
1017
- if i == len(timesteps) - 1 or (
1018
- (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1019
- ):
1020
- progress_bar.update()
1021
-
1022
- if XLA_AVAILABLE:
1023
- xm.mark_step()
1024
-
1025
- if output_type == "latent":
1026
- image = latents
1027
-
1028
- else:
1029
- latents = self._unpack_latents(
1030
- latents, height, width, self.vae_scale_factor
1031
- )
1032
- latents = (
1033
- latents / self.vae.config.scaling_factor
1034
- ) + self.vae.config.shift_factor
1035
- latents = latents.to(self.vae.dtype)
1036
-
1037
- image = self.vae.decode(latents, return_dict=False)[0]
1038
- image = self.image_processor.postprocess(image, output_type=output_type)
1039
-
1040
- # Offload all models
1041
- self.maybe_free_model_hooks()
1042
-
1043
- if not return_dict:
1044
- return (image,)
1045
-
1046
- return FluxPipelineOutput(images=image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
preprocessor.py CHANGED
@@ -81,4 +81,4 @@ class Preprocessor:
81
  image = np.array(image)
82
  image = HWC3(image)
83
  image = resize_image(image, resolution=image_resolution)
84
- return PIL.Image.fromarray(image)
 
81
  image = np.array(image)
82
  image = HWC3(image)
83
  image = resize_image(image, resolution=image_resolution)
84
+ return PIL.Image.fromarray(image)
requirements.txt CHANGED
@@ -7,7 +7,7 @@ einops
7
  spaces
8
  gradio
9
  opencv-python
10
- diffusers==0.30.2
11
  boto3
12
  sentencepiece
13
  peft
 
7
  spaces
8
  gradio
9
  opencv-python
10
+ git+https://github.com/huggingface/diffusers.git
11
  boto3
12
  sentencepiece
13
  peft
transformer_flux.py DELETED
@@ -1,525 +0,0 @@
1
- from typing import Any, Dict, List, Optional, Union
2
-
3
- import numpy as np
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
-
8
- from diffusers.configuration_utils import ConfigMixin, register_to_config
9
- from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
10
- from diffusers.models.attention import FeedForward
11
- from diffusers.models.attention_processor import (
12
- Attention,
13
- FluxAttnProcessor2_0,
14
- FluxSingleAttnProcessor2_0,
15
- )
16
- from diffusers.models.modeling_utils import ModelMixin
17
- from diffusers.models.normalization import (
18
- AdaLayerNormContinuous,
19
- AdaLayerNormZero,
20
- AdaLayerNormZeroSingle,
21
- )
22
- from diffusers.utils import (
23
- USE_PEFT_BACKEND,
24
- is_torch_version,
25
- logging,
26
- scale_lora_layers,
27
- unscale_lora_layers,
28
- )
29
- from diffusers.utils.torch_utils import maybe_allow_in_graph
30
- from diffusers.models.embeddings import (
31
- CombinedTimestepGuidanceTextProjEmbeddings,
32
- CombinedTimestepTextProjEmbeddings,
33
- )
34
- from diffusers.models.modeling_outputs import Transformer2DModelOutput
35
-
36
-
37
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
38
-
39
-
40
- # YiYi to-do: refactor rope related functions/classes
41
- def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
42
- assert dim % 2 == 0, "The dimension must be even."
43
-
44
- scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
45
- omega = 1.0 / (theta**scale)
46
-
47
- batch_size, seq_length = pos.shape
48
- out = torch.einsum("...n,d->...nd", pos, omega)
49
- cos_out = torch.cos(out)
50
- sin_out = torch.sin(out)
51
-
52
- stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
53
- out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
54
- return out.float()
55
-
56
-
57
- # YiYi to-do: refactor rope related functions/classes
58
- class EmbedND(nn.Module):
59
- def __init__(self, dim: int, theta: int, axes_dim: List[int]):
60
- super().__init__()
61
- self.dim = dim
62
- self.theta = theta
63
- self.axes_dim = axes_dim
64
-
65
- def forward(self, ids: torch.Tensor) -> torch.Tensor:
66
- n_axes = ids.shape[-1]
67
- emb = torch.cat(
68
- [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
69
- dim=-3,
70
- )
71
- return emb.unsqueeze(1)
72
-
73
-
74
- @maybe_allow_in_graph
75
- class FluxSingleTransformerBlock(nn.Module):
76
- r"""
77
- A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
78
-
79
- Reference: https://arxiv.org/abs/2403.03206
80
-
81
- Parameters:
82
- dim (`int`): The number of channels in the input and output.
83
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
84
- attention_head_dim (`int`): The number of channels in each head.
85
- context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
86
- processing of `context` conditions.
87
- """
88
-
89
- def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
90
- super().__init__()
91
- self.mlp_hidden_dim = int(dim * mlp_ratio)
92
-
93
- self.norm = AdaLayerNormZeroSingle(dim)
94
- self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
95
- self.act_mlp = nn.GELU(approximate="tanh")
96
- self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
97
-
98
- processor = FluxSingleAttnProcessor2_0()
99
- self.attn = Attention(
100
- query_dim=dim,
101
- cross_attention_dim=None,
102
- dim_head=attention_head_dim,
103
- heads=num_attention_heads,
104
- out_dim=dim,
105
- bias=True,
106
- processor=processor,
107
- qk_norm="rms_norm",
108
- eps=1e-6,
109
- pre_only=True,
110
- )
111
-
112
- def forward(
113
- self,
114
- hidden_states: torch.FloatTensor,
115
- temb: torch.FloatTensor,
116
- image_rotary_emb=None,
117
- ):
118
- residual = hidden_states
119
- norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
120
- mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
121
-
122
- attn_output = self.attn(
123
- hidden_states=norm_hidden_states,
124
- image_rotary_emb=image_rotary_emb,
125
- )
126
-
127
- hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
128
- gate = gate.unsqueeze(1)
129
- hidden_states = gate * self.proj_out(hidden_states)
130
- hidden_states = residual + hidden_states
131
- if hidden_states.dtype == torch.float16:
132
- hidden_states = hidden_states.clip(-65504, 65504)
133
-
134
- return hidden_states
135
-
136
-
137
- @maybe_allow_in_graph
138
- class FluxTransformerBlock(nn.Module):
139
- r"""
140
- A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
141
-
142
- Reference: https://arxiv.org/abs/2403.03206
143
-
144
- Parameters:
145
- dim (`int`): The number of channels in the input and output.
146
- num_attention_heads (`int`): The number of heads to use for multi-head attention.
147
- attention_head_dim (`int`): The number of channels in each head.
148
- context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
149
- processing of `context` conditions.
150
- """
151
-
152
- def __init__(
153
- self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6
154
- ):
155
- super().__init__()
156
-
157
- self.norm1 = AdaLayerNormZero(dim)
158
-
159
- self.norm1_context = AdaLayerNormZero(dim)
160
-
161
- if hasattr(F, "scaled_dot_product_attention"):
162
- processor = FluxAttnProcessor2_0()
163
- else:
164
- raise ValueError(
165
- "The current PyTorch version does not support the `scaled_dot_product_attention` function."
166
- )
167
- self.attn = Attention(
168
- query_dim=dim,
169
- cross_attention_dim=None,
170
- added_kv_proj_dim=dim,
171
- dim_head=attention_head_dim,
172
- heads=num_attention_heads,
173
- out_dim=dim,
174
- context_pre_only=False,
175
- bias=True,
176
- processor=processor,
177
- qk_norm=qk_norm,
178
- eps=eps,
179
- )
180
-
181
- self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
182
- self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
183
-
184
- self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
185
- self.ff_context = FeedForward(
186
- dim=dim, dim_out=dim, activation_fn="gelu-approximate"
187
- )
188
-
189
- # let chunk size default to None
190
- self._chunk_size = None
191
- self._chunk_dim = 0
192
-
193
- def forward(
194
- self,
195
- hidden_states: torch.FloatTensor,
196
- encoder_hidden_states: torch.FloatTensor,
197
- temb: torch.FloatTensor,
198
- image_rotary_emb=None,
199
- ):
200
- norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
201
- hidden_states, emb=temb
202
- )
203
-
204
- (
205
- norm_encoder_hidden_states,
206
- c_gate_msa,
207
- c_shift_mlp,
208
- c_scale_mlp,
209
- c_gate_mlp,
210
- ) = self.norm1_context(encoder_hidden_states, emb=temb)
211
-
212
- # Attention.
213
- attn_output, context_attn_output = self.attn(
214
- hidden_states=norm_hidden_states,
215
- encoder_hidden_states=norm_encoder_hidden_states,
216
- image_rotary_emb=image_rotary_emb,
217
- )
218
-
219
- # Process attention outputs for the `hidden_states`.
220
- attn_output = gate_msa.unsqueeze(1) * attn_output
221
- hidden_states = hidden_states + attn_output
222
-
223
- norm_hidden_states = self.norm2(hidden_states)
224
- norm_hidden_states = (
225
- norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
226
- )
227
-
228
- ff_output = self.ff(norm_hidden_states)
229
- ff_output = gate_mlp.unsqueeze(1) * ff_output
230
-
231
- hidden_states = hidden_states + ff_output
232
-
233
- # Process attention outputs for the `encoder_hidden_states`.
234
-
235
- context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
236
- encoder_hidden_states = encoder_hidden_states + context_attn_output
237
-
238
- norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
239
- norm_encoder_hidden_states = (
240
- norm_encoder_hidden_states * (1 + c_scale_mlp[:, None])
241
- + c_shift_mlp[:, None]
242
- )
243
-
244
- context_ff_output = self.ff_context(norm_encoder_hidden_states)
245
- encoder_hidden_states = (
246
- encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
247
- )
248
- if encoder_hidden_states.dtype == torch.float16:
249
- encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
250
-
251
- return encoder_hidden_states, hidden_states
252
-
253
-
254
- class FluxTransformer2DModel(
255
- ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin
256
- ):
257
- """
258
- The Transformer model introduced in Flux.
259
-
260
- Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
261
-
262
- Parameters:
263
- patch_size (`int`): Patch size to turn the input data into small patches.
264
- in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
265
- num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
266
- num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
267
- attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
268
- num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
269
- joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
270
- pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
271
- guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
272
- """
273
-
274
- _supports_gradient_checkpointing = True
275
-
276
- @register_to_config
277
- def __init__(
278
- self,
279
- patch_size: int = 1,
280
- in_channels: int = 64,
281
- num_layers: int = 19,
282
- num_single_layers: int = 38,
283
- attention_head_dim: int = 128,
284
- num_attention_heads: int = 24,
285
- joint_attention_dim: int = 4096,
286
- pooled_projection_dim: int = 768,
287
- guidance_embeds: bool = False,
288
- axes_dims_rope: List[int] = [16, 56, 56],
289
- ):
290
- super().__init__()
291
- self.out_channels = in_channels
292
- self.inner_dim = (
293
- self.config.num_attention_heads * self.config.attention_head_dim
294
- )
295
-
296
- self.pos_embed = EmbedND(
297
- dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope
298
- )
299
- text_time_guidance_cls = (
300
- CombinedTimestepGuidanceTextProjEmbeddings
301
- if guidance_embeds
302
- else CombinedTimestepTextProjEmbeddings
303
- )
304
- self.time_text_embed = text_time_guidance_cls(
305
- embedding_dim=self.inner_dim,
306
- pooled_projection_dim=self.config.pooled_projection_dim,
307
- )
308
-
309
- self.context_embedder = nn.Linear(
310
- self.config.joint_attention_dim, self.inner_dim
311
- )
312
- self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
313
-
314
- self.transformer_blocks = nn.ModuleList(
315
- [
316
- FluxTransformerBlock(
317
- dim=self.inner_dim,
318
- num_attention_heads=self.config.num_attention_heads,
319
- attention_head_dim=self.config.attention_head_dim,
320
- )
321
- for i in range(self.config.num_layers)
322
- ]
323
- )
324
-
325
- self.single_transformer_blocks = nn.ModuleList(
326
- [
327
- FluxSingleTransformerBlock(
328
- dim=self.inner_dim,
329
- num_attention_heads=self.config.num_attention_heads,
330
- attention_head_dim=self.config.attention_head_dim,
331
- )
332
- for i in range(self.config.num_single_layers)
333
- ]
334
- )
335
-
336
- self.norm_out = AdaLayerNormContinuous(
337
- self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6
338
- )
339
- self.proj_out = nn.Linear(
340
- self.inner_dim, patch_size * patch_size * self.out_channels, bias=True
341
- )
342
-
343
- self.gradient_checkpointing = False
344
-
345
- def _set_gradient_checkpointing(self, module, value=False):
346
- if hasattr(module, "gradient_checkpointing"):
347
- module.gradient_checkpointing = value
348
-
349
- def forward(
350
- self,
351
- hidden_states: torch.Tensor,
352
- encoder_hidden_states: torch.Tensor = None,
353
- pooled_projections: torch.Tensor = None,
354
- timestep: torch.LongTensor = None,
355
- img_ids: torch.Tensor = None,
356
- txt_ids: torch.Tensor = None,
357
- guidance: torch.Tensor = None,
358
- joint_attention_kwargs: Optional[Dict[str, Any]] = None,
359
- controlnet_block_samples=None,
360
- controlnet_single_block_samples=None,
361
- return_dict: bool = True,
362
- ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
363
- """
364
- The [`FluxTransformer2DModel`] forward method.
365
-
366
- Args:
367
- hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
368
- Input `hidden_states`.
369
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
370
- Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
371
- pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
372
- from the embeddings of input conditions.
373
- timestep ( `torch.LongTensor`):
374
- Used to indicate denoising step.
375
- block_controlnet_hidden_states: (`list` of `torch.Tensor`):
376
- A list of tensors that if specified are added to the residuals of transformer blocks.
377
- joint_attention_kwargs (`dict`, *optional*):
378
- A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
379
- `self.processor` in
380
- [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
381
- return_dict (`bool`, *optional*, defaults to `True`):
382
- Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
383
- tuple.
384
-
385
- Returns:
386
- If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
387
- `tuple` where the first element is the sample tensor.
388
- """
389
- if joint_attention_kwargs is not None:
390
- joint_attention_kwargs = joint_attention_kwargs.copy()
391
- lora_scale = joint_attention_kwargs.pop("scale", 1.0)
392
- else:
393
- lora_scale = 1.0
394
-
395
- if USE_PEFT_BACKEND:
396
- # weight the lora layers by setting `lora_scale` for each PEFT layer
397
- scale_lora_layers(self, lora_scale)
398
- else:
399
- if (
400
- joint_attention_kwargs is not None
401
- and joint_attention_kwargs.get("scale", None) is not None
402
- ):
403
- logger.warning(
404
- "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
405
- )
406
- hidden_states = self.x_embedder(hidden_states)
407
-
408
- timestep = timestep.to(hidden_states.dtype) * 1000
409
- if guidance is not None:
410
- guidance = guidance.to(hidden_states.dtype) * 1000
411
- else:
412
- guidance = None
413
- temb = (
414
- self.time_text_embed(timestep, pooled_projections)
415
- if guidance is None
416
- else self.time_text_embed(timestep, guidance, pooled_projections)
417
- )
418
- encoder_hidden_states = self.context_embedder(encoder_hidden_states)
419
-
420
- txt_ids = txt_ids.expand(img_ids.size(0), -1, -1)
421
- ids = torch.cat((txt_ids, img_ids), dim=1)
422
- image_rotary_emb = self.pos_embed(ids)
423
-
424
- for index_block, block in enumerate(self.transformer_blocks):
425
- if self.training and self.gradient_checkpointing:
426
-
427
- def create_custom_forward(module, return_dict=None):
428
- def custom_forward(*inputs):
429
- if return_dict is not None:
430
- return module(*inputs, return_dict=return_dict)
431
- else:
432
- return module(*inputs)
433
-
434
- return custom_forward
435
-
436
- ckpt_kwargs: Dict[str, Any] = (
437
- {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
438
- )
439
- (
440
- encoder_hidden_states,
441
- hidden_states,
442
- ) = torch.utils.checkpoint.checkpoint(
443
- create_custom_forward(block),
444
- hidden_states,
445
- encoder_hidden_states,
446
- temb,
447
- image_rotary_emb,
448
- **ckpt_kwargs,
449
- )
450
-
451
- else:
452
- encoder_hidden_states, hidden_states = block(
453
- hidden_states=hidden_states,
454
- encoder_hidden_states=encoder_hidden_states,
455
- temb=temb,
456
- image_rotary_emb=image_rotary_emb,
457
- )
458
-
459
- # controlnet residual
460
- if controlnet_block_samples is not None:
461
- interval_control = len(self.transformer_blocks) / len(
462
- controlnet_block_samples
463
- )
464
- interval_control = int(np.ceil(interval_control))
465
- hidden_states = (
466
- hidden_states
467
- + controlnet_block_samples[index_block // interval_control]
468
- )
469
-
470
- hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
471
-
472
- for index_block, block in enumerate(self.single_transformer_blocks):
473
- if self.training and self.gradient_checkpointing:
474
-
475
- def create_custom_forward(module, return_dict=None):
476
- def custom_forward(*inputs):
477
- if return_dict is not None:
478
- return module(*inputs, return_dict=return_dict)
479
- else:
480
- return module(*inputs)
481
-
482
- return custom_forward
483
-
484
- ckpt_kwargs: Dict[str, Any] = (
485
- {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
486
- )
487
- hidden_states = torch.utils.checkpoint.checkpoint(
488
- create_custom_forward(block),
489
- hidden_states,
490
- temb,
491
- image_rotary_emb,
492
- **ckpt_kwargs,
493
- )
494
-
495
- else:
496
- hidden_states = block(
497
- hidden_states=hidden_states,
498
- temb=temb,
499
- image_rotary_emb=image_rotary_emb,
500
- )
501
-
502
- # controlnet residual
503
- if controlnet_single_block_samples is not None:
504
- interval_control = len(self.single_transformer_blocks) / len(
505
- controlnet_single_block_samples
506
- )
507
- interval_control = int(np.ceil(interval_control))
508
- hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
509
- hidden_states[:, encoder_hidden_states.shape[1] :, ...]
510
- + controlnet_single_block_samples[index_block // interval_control]
511
- )
512
-
513
- hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
514
-
515
- hidden_states = self.norm_out(hidden_states, temb)
516
- output = self.proj_out(hidden_states)
517
-
518
- if USE_PEFT_BACKEND:
519
- # remove `lora_scale` from each PEFT layer
520
- unscale_lora_layers(self, lora_scale)
521
-
522
- if not return_dict:
523
- return (output,)
524
-
525
- return Transformer2DModelOutput(sample=output)