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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from diffusers.configuration_utils import register_to_config
|
| 3 |
+
from typing import Any, Dict, Optional, Union, List, Tuple
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from diffusers.models.transformers.transformer_flux import (
|
| 7 |
+
FluxTransformer2DModel,
|
| 8 |
+
Transformer2DModelOutput,
|
| 9 |
+
)
|
| 10 |
+
from diffusers.utils import unscale_lora_layers,is_torch_version,USE_PEFT_BACKEND,scale_lora_layers,logging
|
| 11 |
+
from .lora_switching_module import enable_lora, module_active_adapters
|
| 12 |
+
from .SubjectGeniusTransformerBlock import block_forward,single_block_forward
|
| 13 |
+
|
| 14 |
+
logger = logging.get_logger(__name__)
|
| 15 |
+
class SubjectGeniusTransformer2DModel(FluxTransformer2DModel):
|
| 16 |
+
@register_to_config
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
patch_size: int = 1,
|
| 20 |
+
in_channels: int = 64,
|
| 21 |
+
out_channels: Optional[int] = None,
|
| 22 |
+
num_layers: int = 19,
|
| 23 |
+
num_single_layers: int = 38,
|
| 24 |
+
attention_head_dim: int = 128,
|
| 25 |
+
num_attention_heads: int = 24,
|
| 26 |
+
joint_attention_dim: int = 4096,
|
| 27 |
+
pooled_projection_dim: int = 768,
|
| 28 |
+
guidance_embeds: bool = False,
|
| 29 |
+
axes_dims_rope: Tuple[int] = (16, 56, 56),
|
| 30 |
+
):
|
| 31 |
+
super().__init__(patch_size,
|
| 32 |
+
in_channels,
|
| 33 |
+
out_channels,
|
| 34 |
+
num_layers,
|
| 35 |
+
num_single_layers,
|
| 36 |
+
attention_head_dim,
|
| 37 |
+
num_attention_heads,
|
| 38 |
+
joint_attention_dim,
|
| 39 |
+
pooled_projection_dim,
|
| 40 |
+
guidance_embeds,
|
| 41 |
+
axes_dims_rope)
|
| 42 |
+
|
| 43 |
+
def forward(self,
|
| 44 |
+
hidden_states: torch.Tensor,
|
| 45 |
+
condition_latents: List[torch.Tensor],
|
| 46 |
+
condition_ids: List[torch.Tensor],
|
| 47 |
+
condition_type_ids: List[torch.Tensor],
|
| 48 |
+
condition_types: List[str],
|
| 49 |
+
model_config: Optional[Dict[str, Any]] = {},
|
| 50 |
+
return_condition_latents: bool = False,
|
| 51 |
+
c_t=0,
|
| 52 |
+
encoder_hidden_states: torch.Tensor = None,
|
| 53 |
+
pooled_projections: torch.Tensor = None,
|
| 54 |
+
timestep: torch.LongTensor = None,
|
| 55 |
+
img_ids: torch.Tensor = None,
|
| 56 |
+
txt_ids: torch.Tensor = None,
|
| 57 |
+
guidance: torch.Tensor = None,
|
| 58 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 59 |
+
controlnet_block_samples=None,
|
| 60 |
+
controlnet_single_block_samples=None,
|
| 61 |
+
return_dict: bool = True,
|
| 62 |
+
controlnet_blocks_repeat: bool = False,
|
| 63 |
+
) -> tuple[Any, None] | tuple[Any, Any | None] | Transformer2DModelOutput:
|
| 64 |
+
use_condition = condition_latents is not None
|
| 65 |
+
|
| 66 |
+
# lora scale
|
| 67 |
+
if joint_attention_kwargs is not None:
|
| 68 |
+
joint_attention_kwargs = joint_attention_kwargs.copy()
|
| 69 |
+
lora_scale = joint_attention_kwargs.pop("scale", 1.0)
|
| 70 |
+
else:
|
| 71 |
+
lora_scale = 1.0
|
| 72 |
+
|
| 73 |
+
if USE_PEFT_BACKEND:
|
| 74 |
+
# MAYBE a conflict when loading multi-loras, seems to weight them together. Weight the lora layers by setting `lora_scale` for each PEFT layer
|
| 75 |
+
scale_lora_layers(self, lora_scale)
|
| 76 |
+
else:
|
| 77 |
+
if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
|
| 78 |
+
logger.warning(
|
| 79 |
+
"Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
|
| 80 |
+
)
|
| 81 |
+
# hidden_state proj
|
| 82 |
+
with enable_lora([self.x_embedder],[item for item in module_active_adapters(self.x_embedder) if item not in condition_types]):
|
| 83 |
+
hidden_states = self.x_embedder(hidden_states)
|
| 84 |
+
# condition proj
|
| 85 |
+
if use_condition:
|
| 86 |
+
condition_latents = copy.deepcopy(condition_latents)
|
| 87 |
+
for i, cond_type in enumerate(condition_types):
|
| 88 |
+
with enable_lora([self.x_embedder],[cond_type]):
|
| 89 |
+
condition_latents[i] = self.x_embedder(condition_latents[i])
|
| 90 |
+
|
| 91 |
+
# text_embedding proj
|
| 92 |
+
encoder_hidden_states = self.context_embedder(encoder_hidden_states)
|
| 93 |
+
|
| 94 |
+
# prepare for timestep and guidance value
|
| 95 |
+
timestep = timestep.to(hidden_states.dtype) * 1000
|
| 96 |
+
if guidance is not None:
|
| 97 |
+
guidance = guidance.to(hidden_states.dtype) * 1000
|
| 98 |
+
else:
|
| 99 |
+
guidance = None
|
| 100 |
+
|
| 101 |
+
# computing the time_poolingtext_guidance embedding for the text branch and the denoising branch
|
| 102 |
+
temb = (
|
| 103 |
+
self.time_text_embed(timestep, pooled_projections)
|
| 104 |
+
if guidance is None
|
| 105 |
+
else self.time_text_embed(timestep, guidance, pooled_projections)
|
| 106 |
+
)
|
| 107 |
+
# computing the time_poolingtext_guidance embedding for the conditional branches
|
| 108 |
+
cond_temb = (
|
| 109 |
+
self.time_text_embed(torch.ones_like(timestep) * c_t * 1000, pooled_projections)
|
| 110 |
+
if guidance is None
|
| 111 |
+
else self.time_text_embed(torch.ones_like(timestep) * c_t * 1000, guidance, pooled_projections)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# not use in this version
|
| 115 |
+
if hasattr(self, "cond_type_embed") and condition_type_ids is not None:
|
| 116 |
+
cond_type_proj = self.time_text_embed.time_proj(condition_type_ids[0])
|
| 117 |
+
cond_type_emb = self.cond_type_embed(cond_type_proj.to(dtype=cond_temb.dtype))
|
| 118 |
+
cond_temb = cond_temb + cond_type_emb
|
| 119 |
+
|
| 120 |
+
# Rotary Positional Embedding
|
| 121 |
+
if txt_ids.ndim == 3:
|
| 122 |
+
logger.warning(
|
| 123 |
+
"Passing `txt_ids` 3d torch.Tensor is deprecated."
|
| 124 |
+
"Please remove the batch dimension and pass it as a 2d torch Tensor"
|
| 125 |
+
)
|
| 126 |
+
txt_ids = txt_ids[0]
|
| 127 |
+
if img_ids.ndim == 3:
|
| 128 |
+
logger.warning(
|
| 129 |
+
"Passing `img_ids` 3d torch.Tensor is deprecated."
|
| 130 |
+
"Please remove the batch dimension and pass it as a 2d torch Tensor"
|
| 131 |
+
)
|
| 132 |
+
img_ids = img_ids[0]
|
| 133 |
+
|
| 134 |
+
ids = torch.cat((txt_ids, img_ids), dim=0)
|
| 135 |
+
image_rotary_emb = tuple(i.to(self.dtype) for i in self.pos_embed(ids))
|
| 136 |
+
cond_rotary_embs = []
|
| 137 |
+
if use_condition:
|
| 138 |
+
for cond_id in condition_ids:
|
| 139 |
+
cond_rotary_embs.append(tuple(i.to(self.dtype) for i in self.pos_embed(cond_id)))
|
| 140 |
+
|
| 141 |
+
# process in mm-DiT_block
|
| 142 |
+
for index_block, block in enumerate(self.transformer_blocks):
|
| 143 |
+
encoder_hidden_states, hidden_states, condition_latents = block_forward(
|
| 144 |
+
block,
|
| 145 |
+
model_config=model_config,
|
| 146 |
+
hidden_states=hidden_states,
|
| 147 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 148 |
+
condition_latents= condition_latents if use_condition else None,
|
| 149 |
+
condition_types = condition_types if use_condition else None,
|
| 150 |
+
temb=temb,
|
| 151 |
+
cond_temb=cond_temb if use_condition else None,
|
| 152 |
+
image_rotary_emb=image_rotary_emb,
|
| 153 |
+
cond_rotary_embs=cond_rotary_embs if use_condition else None,
|
| 154 |
+
)
|
| 155 |
+
# controlnet residual
|
| 156 |
+
if controlnet_block_samples is not None:
|
| 157 |
+
interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
|
| 158 |
+
interval_control = int(np.ceil(interval_control))
|
| 159 |
+
hidden_states = (hidden_states + controlnet_block_samples[index_block // interval_control])
|
| 160 |
+
|
| 161 |
+
hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
|
| 162 |
+
|
| 163 |
+
# process in single-DiT_block
|
| 164 |
+
for index_block, block in enumerate(self.single_transformer_blocks):
|
| 165 |
+
hidden_states, condition_latents = single_block_forward(
|
| 166 |
+
block,
|
| 167 |
+
model_config=model_config,
|
| 168 |
+
hidden_states=hidden_states,
|
| 169 |
+
condition_latents= condition_latents if use_condition else None,
|
| 170 |
+
condition_types=condition_types if use_condition else None,
|
| 171 |
+
temb=temb,
|
| 172 |
+
cond_temb= cond_temb if use_condition else None,
|
| 173 |
+
image_rotary_emb=image_rotary_emb,
|
| 174 |
+
cond_rotary_embs= cond_rotary_embs if use_condition else None,
|
| 175 |
+
)
|
| 176 |
+
# controlnet residual
|
| 177 |
+
if controlnet_single_block_samples is not None:
|
| 178 |
+
interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
|
| 179 |
+
interval_control = int(np.ceil(interval_control))
|
| 180 |
+
hidden_states[:, encoder_hidden_states.shape[1]:, ...] = (
|
| 181 |
+
hidden_states[:, encoder_hidden_states.shape[1]:, ...]+ controlnet_single_block_samples[index_block // interval_control]
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
hidden_states = hidden_states[:, encoder_hidden_states.shape[1]:, ...]
|
| 185 |
+
|
| 186 |
+
hidden_states = self.norm_out(hidden_states, temb).to(self.dtype)
|
| 187 |
+
output = self.proj_out(hidden_states)
|
| 188 |
+
if return_condition_latents:
|
| 189 |
+
condition_latents = [ self.proj_out(self.norm_out(i, cond_temb)) if use_condition else None for i in condition_latents]
|
| 190 |
+
|
| 191 |
+
if USE_PEFT_BACKEND:
|
| 192 |
+
unscale_lora_layers(self, lora_scale)
|
| 193 |
+
if not return_dict:
|
| 194 |
+
return (output,None) if not return_condition_latents else (output, condition_latents)
|
| 195 |
+
|
| 196 |
+
return Transformer2DModelOutput(sample=output)
|