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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from diffusers import FluxTransformer2DModel
|
| 8 |
+
from diffusers.configuration_utils import FrozenDict
|
| 9 |
+
|
| 10 |
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 11 |
+
if PROJECT_ROOT not in sys.path:
|
| 12 |
+
sys.path.insert(0, PROJECT_ROOT)
|
| 13 |
+
|
| 14 |
+
logging.getLogger("transformers.tokenization_utils_base").setLevel(logging.ERROR)
|
| 15 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
|
| 16 |
+
|
| 17 |
+
from models.mmdit import CustomFluxTransformer2DModel
|
| 18 |
+
from models.multiLayer_adapter import MultiLayerAdapter
|
| 19 |
+
from models.pipeline import CustomFluxPipeline, CustomFluxPipelineCfgLayer
|
| 20 |
+
from models.transp_vae import AutoencoderKLTransformerTraining as CustomVAE
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def resolve_local_config_path(path: str | None) -> str | None:
|
| 24 |
+
"""Resolve project-relative asset paths while leaving absolute paths untouched."""
|
| 25 |
+
if not path:
|
| 26 |
+
return path
|
| 27 |
+
if os.path.isabs(path):
|
| 28 |
+
return path
|
| 29 |
+
return os.path.join(PROJECT_ROOT, path)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def scale_box_xyxy(box, source_size: int, target_size: int) -> tuple:
|
| 33 |
+
"""Scale an xyxy box from source_size to target_size."""
|
| 34 |
+
scale = target_size / source_size
|
| 35 |
+
x0, y0, x1, y1 = box
|
| 36 |
+
|
| 37 |
+
x0_s = int(x0 * scale)
|
| 38 |
+
y0_s = int(y0 * scale)
|
| 39 |
+
x1_s = int(x1 * scale)
|
| 40 |
+
y1_s = int(y1 * scale)
|
| 41 |
+
|
| 42 |
+
x0_s = max(0, x0_s)
|
| 43 |
+
y0_s = max(0, y0_s)
|
| 44 |
+
x1_s = min(target_size, x1_s)
|
| 45 |
+
y1_s = min(target_size, y1_s)
|
| 46 |
+
|
| 47 |
+
return (x0_s, y0_s, x1_s, y1_s)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def quantize_box_16(box: tuple, target_size: int) -> tuple:
|
| 51 |
+
"""Quantize an xyxy box to the 16-pixel latent grid."""
|
| 52 |
+
x0, y0, x1, y1 = box
|
| 53 |
+
|
| 54 |
+
x0_q = (x0 // 16) * 16
|
| 55 |
+
y0_q = (y0 // 16) * 16
|
| 56 |
+
x1_q = ((x1 + 15) // 16) * 16
|
| 57 |
+
y1_q = ((y1 + 15) // 16) * 16
|
| 58 |
+
|
| 59 |
+
x0_q = max(0, x0_q)
|
| 60 |
+
y0_q = max(0, y0_q)
|
| 61 |
+
x1_q = min(target_size, x1_q)
|
| 62 |
+
y1_q = min(target_size, y1_q)
|
| 63 |
+
|
| 64 |
+
return (x0_q, y0_q, x1_q, y1_q)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_layer_boxes(layers: list, source_size: int, target_size: int) -> list:
|
| 68 |
+
"""Extract, scale, and quantize prism layer boxes."""
|
| 69 |
+
boxes = []
|
| 70 |
+
for layer in layers:
|
| 71 |
+
box = layer.get("box", [0, 0, source_size, source_size])
|
| 72 |
+
scaled_box = scale_box_xyxy(box, source_size, target_size)
|
| 73 |
+
boxes.append(quantize_box_16(scaled_box, target_size))
|
| 74 |
+
return boxes
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def initialize_pipeline(config):
|
| 78 |
+
"""Initialize the SynLayers decomposition pipeline."""
|
| 79 |
+
transp_vae_path = resolve_local_config_path(config.get("transp_vae_path"))
|
| 80 |
+
pretrained_lora_dir = resolve_local_config_path(config.get("pretrained_lora_dir"))
|
| 81 |
+
artplus_lora_dir = resolve_local_config_path(config.get("artplus_lora_dir"))
|
| 82 |
+
layer_ckpt = resolve_local_config_path(config.get("layer_ckpt"))
|
| 83 |
+
adapter_lora_dir = resolve_local_config_path(config.get("adapter_lora_dir"))
|
| 84 |
+
lora_ckpt = resolve_local_config_path(config.get("lora_ckpt"))
|
| 85 |
+
|
| 86 |
+
print("[INFO] Loading Transparent VAE...", flush=True)
|
| 87 |
+
vae_args = argparse.Namespace(
|
| 88 |
+
max_layers=config.get("max_layers", 48),
|
| 89 |
+
decoder_arch=config.get("decoder_arch", "vit"),
|
| 90 |
+
pos_embedding=config.get("pos_embedding", "rope"),
|
| 91 |
+
layer_embedding=config.get("layer_embedding", "rope"),
|
| 92 |
+
single_layer_decoder=config.get("single_layer_decoder", None),
|
| 93 |
+
)
|
| 94 |
+
transp_vae = CustomVAE(vae_args)
|
| 95 |
+
transp_vae_weights = torch.load(transp_vae_path, map_location=torch.device("cuda"))
|
| 96 |
+
missing_keys, unexpected_keys = transp_vae.load_state_dict(
|
| 97 |
+
transp_vae_weights["model"], strict=False
|
| 98 |
+
)
|
| 99 |
+
if missing_keys:
|
| 100 |
+
print(f"ViT Encoder Missing keys: {missing_keys}")
|
| 101 |
+
if unexpected_keys:
|
| 102 |
+
print(f"ViT Encoder Unexpected keys: {unexpected_keys}")
|
| 103 |
+
transp_vae.eval()
|
| 104 |
+
transp_vae = transp_vae.to(torch.device("cuda"))
|
| 105 |
+
print("[INFO] Transparent VAE loaded.", flush=True)
|
| 106 |
+
|
| 107 |
+
print("[INFO] Loading pretrained Transformer model...", flush=True)
|
| 108 |
+
transformer_orig = FluxTransformer2DModel.from_pretrained(
|
| 109 |
+
config.get("transformer_varient", config["pretrained_model_name_or_path"]),
|
| 110 |
+
subfolder="" if "transformer_varient" in config else "transformer",
|
| 111 |
+
revision=config.get("revision", None),
|
| 112 |
+
variant=config.get("variant", None),
|
| 113 |
+
torch_dtype=torch.bfloat16,
|
| 114 |
+
cache_dir=config.get("cache_dir", None),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
mmdit_config = dict(transformer_orig.config)
|
| 118 |
+
mmdit_config["_class_name"] = "CustomSD3Transformer2DModel"
|
| 119 |
+
mmdit_config["max_layer_num"] = config["max_layer_num"]
|
| 120 |
+
mmdit_config = FrozenDict(mmdit_config)
|
| 121 |
+
|
| 122 |
+
transformer = CustomFluxTransformer2DModel.from_config(mmdit_config).to(
|
| 123 |
+
dtype=torch.bfloat16
|
| 124 |
+
)
|
| 125 |
+
transformer.load_state_dict(transformer_orig.state_dict(), strict=False)
|
| 126 |
+
|
| 127 |
+
if pretrained_lora_dir:
|
| 128 |
+
print("[INFO] Loading pretrained LoRA weights...", flush=True)
|
| 129 |
+
lora_state_dict = CustomFluxPipeline.lora_state_dict(pretrained_lora_dir)
|
| 130 |
+
CustomFluxPipeline.load_lora_into_transformer(lora_state_dict, None, transformer)
|
| 131 |
+
transformer.fuse_lora(safe_fusing=True)
|
| 132 |
+
transformer.unload_lora()
|
| 133 |
+
|
| 134 |
+
if artplus_lora_dir:
|
| 135 |
+
print("[INFO] Loading artplus LoRA weights...", flush=True)
|
| 136 |
+
lora_state_dict = CustomFluxPipeline.lora_state_dict(artplus_lora_dir)
|
| 137 |
+
CustomFluxPipeline.load_lora_into_transformer(lora_state_dict, None, transformer)
|
| 138 |
+
transformer.fuse_lora(safe_fusing=True)
|
| 139 |
+
transformer.unload_lora()
|
| 140 |
+
|
| 141 |
+
layer_pe_path = os.path.join(layer_ckpt, "layer_pe.pth") if layer_ckpt else ""
|
| 142 |
+
if os.path.exists(layer_pe_path):
|
| 143 |
+
print(f"[INFO] Loading layer_pe from {layer_pe_path}...", flush=True)
|
| 144 |
+
layer_pe = torch.load(layer_pe_path)
|
| 145 |
+
transformer.load_state_dict(layer_pe, strict=False)
|
| 146 |
+
|
| 147 |
+
print("[INFO] Loading MultiLayer-Adapter...", flush=True)
|
| 148 |
+
multiLayer_adapter = MultiLayerAdapter.from_pretrained(
|
| 149 |
+
config["pretrained_adapter_path"]
|
| 150 |
+
).to(torch.bfloat16).to(torch.device("cuda"))
|
| 151 |
+
|
| 152 |
+
if adapter_lora_dir:
|
| 153 |
+
print("[INFO] Loading adapter LoRA weights...", flush=True)
|
| 154 |
+
lora_state_dict = CustomFluxPipeline.lora_state_dict(adapter_lora_dir)
|
| 155 |
+
CustomFluxPipeline.load_lora_into_transformer(
|
| 156 |
+
lora_state_dict, None, multiLayer_adapter
|
| 157 |
+
)
|
| 158 |
+
multiLayer_adapter.fuse_lora(safe_fusing=True)
|
| 159 |
+
multiLayer_adapter.unload_lora()
|
| 160 |
+
|
| 161 |
+
multiLayer_adapter.set_layerPE(transformer.layer_pe, transformer.max_layer_num)
|
| 162 |
+
|
| 163 |
+
pipeline = CustomFluxPipelineCfgLayer.from_pretrained(
|
| 164 |
+
config["pretrained_model_name_or_path"],
|
| 165 |
+
transformer=transformer,
|
| 166 |
+
revision=config.get("revision", None),
|
| 167 |
+
variant=config.get("variant", None),
|
| 168 |
+
torch_dtype=torch.bfloat16,
|
| 169 |
+
cache_dir=config.get("cache_dir", None),
|
| 170 |
+
).to(torch.device("cuda"))
|
| 171 |
+
pipeline.set_multiLayerAdapter(multiLayer_adapter)
|
| 172 |
+
|
| 173 |
+
if lora_ckpt:
|
| 174 |
+
print(f"[INFO] Loading trained LoRA from {lora_ckpt}...", flush=True)
|
| 175 |
+
pipeline.load_lora_weights(lora_ckpt, adapter_name="layer")
|
| 176 |
+
|
| 177 |
+
return pipeline, transp_vae
|