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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,os
|
| 2 |
+
current_dir = os.path.dirname(__file__)
|
| 3 |
+
sys.path.append(os.path.abspath(os.path.join(current_dir, '..')))
|
| 4 |
+
import argparse
|
| 5 |
+
import copy
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
import os
|
| 9 |
+
from contextlib import contextmanager
|
| 10 |
+
import functools
|
| 11 |
+
import torch
|
| 12 |
+
import torch.utils.checkpoint
|
| 13 |
+
import transformers
|
| 14 |
+
from accelerate import Accelerator
|
| 15 |
+
from accelerate.logging import get_logger
|
| 16 |
+
from accelerate.utils import set_seed
|
| 17 |
+
from packaging import version
|
| 18 |
+
from peft import LoraConfig
|
| 19 |
+
from tqdm.auto import tqdm
|
| 20 |
+
from transformers import CLIPTokenizer, PretrainedConfig, T5TokenizerFast
|
| 21 |
+
from src.hook import save_model_hook,load_model_hook
|
| 22 |
+
import diffusers
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKL,
|
| 25 |
+
FlowMatchEulerDiscreteScheduler,
|
| 26 |
+
FluxPipeline,
|
| 27 |
+
)
|
| 28 |
+
from src.SubjectGeniusTransformer2DModel import SubjectGeniusTransformer2DModel
|
| 29 |
+
from diffusers.optimization import get_scheduler
|
| 30 |
+
from diffusers.training_utils import cast_training_params, compute_density_for_timestep_sampling, compute_loss_weighting_for_sd3
|
| 31 |
+
from diffusers.utils import check_min_version, is_wandb_available
|
| 32 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 33 |
+
from src.dataloader import get_dataset,prepare_dataset,collate_fn
|
| 34 |
+
if is_wandb_available():
|
| 35 |
+
pass
|
| 36 |
+
from src.text_encoder import encode_prompt
|
| 37 |
+
from datetime import datetime
|
| 38 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 39 |
+
check_min_version("0.32.0.dev0")
|
| 40 |
+
|
| 41 |
+
logger = get_logger(__name__, log_level="INFO")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@contextmanager
|
| 45 |
+
def preserve_requires_grad(model):
|
| 46 |
+
# 备份 requires_grad 状态
|
| 47 |
+
requires_grad_backup = {name: param.requires_grad for name, param in model.named_parameters()}
|
| 48 |
+
yield
|
| 49 |
+
# 恢复 requires_grad 状态
|
| 50 |
+
for name, param in model.named_parameters():
|
| 51 |
+
param.requires_grad = requires_grad_backup[name]
|
| 52 |
+
def load_text_encoders(class_one, class_two):
|
| 53 |
+
text_encoder_one = class_one.from_pretrained(
|
| 54 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
|
| 55 |
+
)
|
| 56 |
+
text_encoder_two = class_two.from_pretrained(
|
| 57 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder_2", revision=args.revision, variant=args.variant
|
| 58 |
+
)
|
| 59 |
+
return text_encoder_one, text_encoder_two
|
| 60 |
+
|
| 61 |
+
def encode_images(pixels: torch.Tensor, vae: torch.nn.Module, weight_dtype):
|
| 62 |
+
pixel_latents = vae.encode(pixels.to(vae.dtype)).latent_dist.sample()
|
| 63 |
+
pixel_latents = (pixel_latents - vae.config.shift_factor) * vae.config.scaling_factor
|
| 64 |
+
return pixel_latents.to(weight_dtype)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def import_model_class_from_model_name_or_path(
|
| 68 |
+
pretrained_model_name_or_path: str, revision: str, subfolder: str = "text_encoder"
|
| 69 |
+
):
|
| 70 |
+
text_encoder_config = PretrainedConfig.from_pretrained(
|
| 71 |
+
pretrained_model_name_or_path, subfolder=subfolder, revision=revision
|
| 72 |
+
)
|
| 73 |
+
model_class = text_encoder_config.architectures[0]
|
| 74 |
+
if model_class == "CLIPTextModel":
|
| 75 |
+
from transformers import CLIPTextModel
|
| 76 |
+
|
| 77 |
+
return CLIPTextModel
|
| 78 |
+
elif model_class == "T5EncoderModel":
|
| 79 |
+
from transformers import T5EncoderModel
|
| 80 |
+
|
| 81 |
+
return T5EncoderModel
|
| 82 |
+
else:
|
| 83 |
+
raise ValueError(f"{model_class} is not supported.")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def parse_args(input_args=None):
|
| 87 |
+
parser = argparse.ArgumentParser(description="training script.")
|
| 88 |
+
parser.add_argument( "--pretrained_model_name_or_path",type=str,default="ckpt/FLUX.1-schnell")
|
| 89 |
+
parser.add_argument("--transformer",type=str,default="ckpt/FLUX.1-schnell",)
|
| 90 |
+
parser.add_argument("--work_dir",type=str,default="output/train_result",)
|
| 91 |
+
parser.add_argument("--output_denoising_lora",type=str,default="depth_canny_union",)
|
| 92 |
+
parser.add_argument("--pretrained_condition_lora_dir",type=str,default="ckpt/Condition_LoRA",)
|
| 93 |
+
parser.add_argument("--training_adapter",type=str,default="ckpt/FLUX.1-schnell-training-adapter",)
|
| 94 |
+
parser.add_argument("--checkpointing_steps",type=int,default=1,)
|
| 95 |
+
parser.add_argument("--resume_from_checkpoint",type=str,default=None,)
|
| 96 |
+
parser.add_argument("--rank",type=int,default=4,help="The dimension of the LoRA rank.")
|
| 97 |
+
|
| 98 |
+
parser.add_argument("--dataset_name",type=str,default=[
|
| 99 |
+
"dataset/split_SubjectSpatial200K/train",
|
| 100 |
+
"dataset/split_SubjectSpatial200K/Collection3/train",
|
| 101 |
+
],
|
| 102 |
+
)
|
| 103 |
+
parser.add_argument("--image_column", type=str, default="image",)
|
| 104 |
+
parser.add_argument("--bbox_column",type=str,default="bbox",)
|
| 105 |
+
parser.add_argument("--canny_column",type=str,default="canny",)
|
| 106 |
+
parser.add_argument("--depth_column",type=str,default="depth",)
|
| 107 |
+
parser.add_argument("--condition_types",type=str,nargs='+',default=["depth","canny"],)
|
| 108 |
+
|
| 109 |
+
parser.add_argument("--max_sequence_length",type=int,default=512,help="Maximum sequence length to use with with the T5 text encoder")
|
| 110 |
+
parser.add_argument("--mixed_precision",type=str,default="bf16", choices=["no", "fp16", "bf16"],)
|
| 111 |
+
parser.add_argument("--cache_dir",type=str,default="cache",)
|
| 112 |
+
parser.add_argument("--seed", type=int, default=0, help="A seed for reproducible training.")
|
| 113 |
+
parser.add_argument("--resolution",type=int,default=512,)
|
| 114 |
+
parser.add_argument("--train_batch_size", type=int, default=1)
|
| 115 |
+
parser.add_argument("--num_train_epochs", type=int, default=None)
|
| 116 |
+
parser.add_argument("--max_train_steps", type=int, default=30000,)
|
| 117 |
+
parser.add_argument("--gradient_accumulation_steps",type=int,default=2)
|
| 118 |
+
|
| 119 |
+
parser.add_argument("--learning_rate",type=float,default=1e-4)
|
| 120 |
+
parser.add_argument("--scale_lr",action="store_true",default=False,)
|
| 121 |
+
parser.add_argument("--lr_scheduler",type=str,default="cosine",
|
| 122 |
+
choices=["linear", "cosine", "cosine_with_restarts", "polynomial","constant", "constant_with_warmup"])
|
| 123 |
+
parser.add_argument("--lr_warmup_steps", type=int, default=500,)
|
| 124 |
+
parser.add_argument("--weighting_scheme",type=str,default="none",
|
| 125 |
+
choices=["sigma_sqrt", "logit_normal", "mode", "cosmap", "none"],
|
| 126 |
+
help=('We default to the "none" weighting scheme for uniform sampling and uniform loss'),
|
| 127 |
+
)
|
| 128 |
+
parser.add_argument("--dataloader_num_workers",type=int,default=0)
|
| 129 |
+
parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
|
| 130 |
+
parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
|
| 131 |
+
parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
|
| 132 |
+
parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
|
| 133 |
+
parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
|
| 134 |
+
parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
|
| 135 |
+
parser.add_argument("--enable_xformers_memory_efficient_attention", default=True)
|
| 136 |
+
|
| 137 |
+
args = parser.parse_args()
|
| 138 |
+
args.revision = None
|
| 139 |
+
args.variant = None
|
| 140 |
+
args.work_dir = os.path.join(args.work_dir,f"{datetime.now().strftime("%y_%m_%d-%H:%M")}")
|
| 141 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
| 142 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
| 143 |
+
args.local_rank = env_local_rank
|
| 144 |
+
return args
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def main(args):
|
| 148 |
+
accelerator = Accelerator(
|
| 149 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 150 |
+
mixed_precision=args.mixed_precision,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Make one log on every process with the configuration for debugging.
|
| 154 |
+
logging.basicConfig(
|
| 155 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 156 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 157 |
+
level=logging.INFO,
|
| 158 |
+
)
|
| 159 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 160 |
+
if accelerator.is_local_main_process:
|
| 161 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 162 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 163 |
+
else:
|
| 164 |
+
transformers.utils.logging.set_verbosity_error()
|
| 165 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 166 |
+
|
| 167 |
+
# If passed along, set the training seed now.
|
| 168 |
+
if args.seed is not None:
|
| 169 |
+
set_seed(args.seed)
|
| 170 |
+
|
| 171 |
+
# Handle the repository creation
|
| 172 |
+
if accelerator.is_main_process:
|
| 173 |
+
os.makedirs(args.work_dir, exist_ok=True)
|
| 174 |
+
|
| 175 |
+
# For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision
|
| 176 |
+
# as these weights are only used for inference, keeping weights in full precision is not required.
|
| 177 |
+
weight_dtype = torch.float32
|
| 178 |
+
if accelerator.mixed_precision == "fp16":
|
| 179 |
+
weight_dtype = torch.float16
|
| 180 |
+
elif accelerator.mixed_precision == "bf16":
|
| 181 |
+
weight_dtype = torch.bfloat16
|
| 182 |
+
|
| 183 |
+
# Load the tokenizers
|
| 184 |
+
tokenizer_one = CLIPTokenizer.from_pretrained(
|
| 185 |
+
args.pretrained_model_name_or_path,
|
| 186 |
+
subfolder="tokenizer",
|
| 187 |
+
revision=args.revision,
|
| 188 |
+
)
|
| 189 |
+
tokenizer_two = T5TokenizerFast.from_pretrained(
|
| 190 |
+
args.pretrained_model_name_or_path,
|
| 191 |
+
subfolder="tokenizer_2",
|
| 192 |
+
revision=args.revision,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# import correct text encoder classes
|
| 196 |
+
text_encoder_cls_one = import_model_class_from_model_name_or_path(
|
| 197 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder"
|
| 198 |
+
)
|
| 199 |
+
text_encoder_cls_two = import_model_class_from_model_name_or_path(
|
| 200 |
+
args.pretrained_model_name_or_path, args.revision, subfolder="text_encoder_2"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# Load scheduler and models
|
| 204 |
+
noise_scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(
|
| 205 |
+
args.pretrained_model_name_or_path, subfolder="scheduler"
|
| 206 |
+
)
|
| 207 |
+
noise_scheduler_copy = copy.deepcopy(noise_scheduler)
|
| 208 |
+
|
| 209 |
+
text_encoder_one, text_encoder_two = load_text_encoders(text_encoder_cls_one, text_encoder_cls_two)
|
| 210 |
+
text_encoder_one = text_encoder_one.to(accelerator.device, dtype=weight_dtype)
|
| 211 |
+
text_encoder_two = text_encoder_two.to(accelerator.device, dtype=weight_dtype)
|
| 212 |
+
|
| 213 |
+
vae = AutoencoderKL.from_pretrained(
|
| 214 |
+
args.pretrained_model_name_or_path,
|
| 215 |
+
subfolder="vae",
|
| 216 |
+
revision=args.revision,
|
| 217 |
+
variant=args.variant,
|
| 218 |
+
).to(accelerator.device, dtype=weight_dtype)
|
| 219 |
+
vae_scale_factor = 2 ** (len(vae.config.block_out_channels) - 1)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
transformer = SubjectGeniusTransformer2DModel.from_pretrained(
|
| 223 |
+
pretrained_model_name_or_path=args.pretrained_model_name_or_path,
|
| 224 |
+
subfolder="transformer",
|
| 225 |
+
revision=args.revision,
|
| 226 |
+
variant=args.variant
|
| 227 |
+
).to(accelerator.device, dtype=weight_dtype)
|
| 228 |
+
# load lora !!!!!
|
| 229 |
+
lora_names = args.condition_types
|
| 230 |
+
for condition_type in lora_names:
|
| 231 |
+
transformer.load_lora_adapter(f"{args.pretrained_condition_lora_dir}/{condition_type}.safetensors", adapter_name=condition_type)
|
| 232 |
+
|
| 233 |
+
transformer.load_lora_adapter(f"{args.training_adapter}/pytorch_lora_weights.safetensors", adapter_name="schnell_assistant")
|
| 234 |
+
|
| 235 |
+
logger.info("All models loaded successfully")
|
| 236 |
+
# freeze parameters of models to save more memory
|
| 237 |
+
transformer.requires_grad_(False)
|
| 238 |
+
vae.requires_grad_(False)
|
| 239 |
+
text_encoder_one.requires_grad_(False)
|
| 240 |
+
text_encoder_two.requires_grad_(False)
|
| 241 |
+
|
| 242 |
+
logger.info("All models keeps requires_grad = False")
|
| 243 |
+
|
| 244 |
+
single_transformer_blocks_lora = [
|
| 245 |
+
f"single_transformer_blocks.{i}.proj_out"
|
| 246 |
+
for i in range(len(transformer.single_transformer_blocks))
|
| 247 |
+
] + [
|
| 248 |
+
f"single_transformer_blocks.{i}.proj_mlp"
|
| 249 |
+
for i in range(len(transformer.single_transformer_blocks))
|
| 250 |
+
]
|
| 251 |
+
|
| 252 |
+
transformer_lora_config = LoraConfig(
|
| 253 |
+
r=args.rank,
|
| 254 |
+
lora_alpha=args.rank,
|
| 255 |
+
init_lora_weights="gaussian",
|
| 256 |
+
target_modules=[
|
| 257 |
+
"x_embedder",
|
| 258 |
+
"norm1.linear",
|
| 259 |
+
"attn.to_q",
|
| 260 |
+
"attn.to_k",
|
| 261 |
+
"attn.to_v",
|
| 262 |
+
"attn.to_out.0",
|
| 263 |
+
"ff.net.2",
|
| 264 |
+
"norm.linear",
|
| 265 |
+
]+single_transformer_blocks_lora,
|
| 266 |
+
)
|
| 267 |
+
transformer.add_adapter(transformer_lora_config,adapter_name=args.output_denoising_lora)
|
| 268 |
+
logger.info(f"Trainable lora: {args.output_denoising_lora} is loaded successfully")
|
| 269 |
+
# hook
|
| 270 |
+
accelerator.register_save_state_pre_hook(functools.partial(save_model_hook,wanted_model=transformer,accelerator=accelerator,adapter_names=[args.output_denoising_lora]))
|
| 271 |
+
accelerator.register_load_state_pre_hook(functools.partial(load_model_hook,wanted_model=transformer,accelerator=accelerator,adapter_names=[args.output_denoising_lora]))
|
| 272 |
+
logger.info("Hooks for save and load is ok.")
|
| 273 |
+
|
| 274 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 275 |
+
if is_xformers_available():
|
| 276 |
+
import xformers
|
| 277 |
+
|
| 278 |
+
xformers_version = version.parse(xformers.__version__)
|
| 279 |
+
if xformers_version == version.parse("0.0.16"):
|
| 280 |
+
logger.warning(
|
| 281 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 282 |
+
)
|
| 283 |
+
transformer.enable_xformers_memory_efficient_attention()
|
| 284 |
+
else:
|
| 285 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if args.scale_lr:
|
| 289 |
+
args.learning_rate = args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 290 |
+
|
| 291 |
+
# Make sure the trainable params are in float32.
|
| 292 |
+
if args.mixed_precision == "fp16":
|
| 293 |
+
# only upcast trainable parameters (LoRA) into fp32
|
| 294 |
+
cast_training_params(transformer, dtype=torch.float32)
|
| 295 |
+
|
| 296 |
+
transformer_lora_parameters = list(filter(lambda p: p.requires_grad, transformer.parameters()))
|
| 297 |
+
|
| 298 |
+
# Initialize the optimizer
|
| 299 |
+
optimizer_cls = torch.optim.AdamW
|
| 300 |
+
|
| 301 |
+
optimizer = optimizer_cls(
|
| 302 |
+
transformer_lora_parameters,
|
| 303 |
+
lr=args.learning_rate,
|
| 304 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 305 |
+
weight_decay=args.adam_weight_decay,
|
| 306 |
+
eps=args.adam_epsilon,
|
| 307 |
+
)
|
| 308 |
+
logger.info("Optimizer initialized successfully.")
|
| 309 |
+
|
| 310 |
+
# Preprocessing the datasets.
|
| 311 |
+
train_dataset = get_dataset(args)
|
| 312 |
+
train_dataset = prepare_dataset(train_dataset, vae_scale_factor, accelerator, args)
|
| 313 |
+
|
| 314 |
+
# DataLoaders creation:
|
| 315 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 316 |
+
train_dataset,
|
| 317 |
+
shuffle=True,
|
| 318 |
+
collate_fn=collate_fn,
|
| 319 |
+
batch_size=args.train_batch_size,
|
| 320 |
+
num_workers=args.dataloader_num_workers,
|
| 321 |
+
)
|
| 322 |
+
logger.info("Training dataset and Dataloader initialized successfully.")
|
| 323 |
+
|
| 324 |
+
tokenizers = [tokenizer_one, tokenizer_two]
|
| 325 |
+
text_encoders = [text_encoder_one, text_encoder_two]
|
| 326 |
+
|
| 327 |
+
def compute_text_embeddings(prompt, text_encoders, tokenizers):
|
| 328 |
+
with torch.no_grad():
|
| 329 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = encode_prompt(
|
| 330 |
+
text_encoders, tokenizers, prompt, args.max_sequence_length
|
| 331 |
+
)
|
| 332 |
+
prompt_embeds = prompt_embeds.to(accelerator.device)
|
| 333 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(accelerator.device)
|
| 334 |
+
text_ids = text_ids.to(accelerator.device)
|
| 335 |
+
return prompt_embeds, pooled_prompt_embeds, text_ids
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# Scheduler and math around the number of training steps.
|
| 339 |
+
# Check the PR https://github.com/huggingface/diffusers/pull/8312 for detailed explanation.
|
| 340 |
+
num_warmup_steps_for_scheduler = args.lr_warmup_steps * accelerator.num_processes
|
| 341 |
+
if args.max_train_steps is None:
|
| 342 |
+
len_train_dataloader_after_sharding = math.ceil(len(train_dataloader) / accelerator.num_processes)
|
| 343 |
+
num_update_steps_per_epoch = math.ceil(len_train_dataloader_after_sharding / args.gradient_accumulation_steps)
|
| 344 |
+
num_training_steps_for_scheduler = (
|
| 345 |
+
args.num_train_epochs * num_update_steps_per_epoch * accelerator.num_processes
|
| 346 |
+
)
|
| 347 |
+
else:
|
| 348 |
+
num_training_steps_for_scheduler = args.max_train_steps * accelerator.num_processes
|
| 349 |
+
|
| 350 |
+
lr_scheduler = get_scheduler(
|
| 351 |
+
args.lr_scheduler,
|
| 352 |
+
optimizer=optimizer,
|
| 353 |
+
num_warmup_steps=num_warmup_steps_for_scheduler,
|
| 354 |
+
num_training_steps=num_training_steps_for_scheduler,
|
| 355 |
+
)
|
| 356 |
+
logger.info(f"lr_scheduler:{args.lr_scheduler} initialized successfully.")
|
| 357 |
+
|
| 358 |
+
with preserve_requires_grad(transformer):
|
| 359 |
+
transformer.set_adapters([i for i in lora_names] + [args.output_denoising_lora] + ["schnell_assistant"])
|
| 360 |
+
logger.info(f"Set Adapters:{[i for i in lora_names] + [args.output_denoising_lora] + ["schnell_assistant"]}")
|
| 361 |
+
|
| 362 |
+
# Prepare everything with our `accelerator`.
|
| 363 |
+
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 364 |
+
transformer, optimizer, train_dataloader, lr_scheduler
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 368 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 369 |
+
if args.max_train_steps is None:
|
| 370 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 371 |
+
if num_training_steps_for_scheduler != args.max_train_steps * accelerator.num_processes:
|
| 372 |
+
logger.warning(
|
| 373 |
+
f"The length of the 'train_dataloader' after 'accelerator.prepare' ({len(train_dataloader)}) does not match "
|
| 374 |
+
f"the expected length ({len_train_dataloader_after_sharding}) when the learning rate scheduler was created. "
|
| 375 |
+
f"This inconsistency may result in the learning rate scheduler not functioning properly."
|
| 376 |
+
)
|
| 377 |
+
# Afterwards we recalculate our number of training epochs
|
| 378 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 379 |
+
|
| 380 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 381 |
+
# The trackers initializes automatically on the main process.
|
| 382 |
+
if accelerator.is_main_process:
|
| 383 |
+
accelerator.init_trackers("SubjectGenius", config=vars(args))
|
| 384 |
+
|
| 385 |
+
# Train!
|
| 386 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 387 |
+
|
| 388 |
+
logger.info("***** Running training *****")
|
| 389 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 390 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 391 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 392 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 393 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 394 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 395 |
+
global_step = 0
|
| 396 |
+
first_epoch = 0
|
| 397 |
+
|
| 398 |
+
# Potentially load in the weights and states from a previous save
|
| 399 |
+
if args.resume_from_checkpoint:
|
| 400 |
+
if args.resume_from_checkpoint != "latest":
|
| 401 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 402 |
+
else:
|
| 403 |
+
# Get the most recent checkpoint
|
| 404 |
+
dirs = os.listdir(args.work_dir)
|
| 405 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 406 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 407 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 408 |
+
|
| 409 |
+
if path is None:
|
| 410 |
+
accelerator.print(
|
| 411 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 412 |
+
)
|
| 413 |
+
args.resume_from_checkpoint = None
|
| 414 |
+
initial_global_step = 0
|
| 415 |
+
else:
|
| 416 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 417 |
+
accelerator.load_state(os.path.join(args.work_dir, path))
|
| 418 |
+
global_step = int(path.split("-")[1])
|
| 419 |
+
initial_global_step = global_step
|
| 420 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 421 |
+
else:
|
| 422 |
+
initial_global_step = 0
|
| 423 |
+
|
| 424 |
+
progress_bar = tqdm(
|
| 425 |
+
range(0, args.max_train_steps),
|
| 426 |
+
initial=initial_global_step,
|
| 427 |
+
desc="Steps",
|
| 428 |
+
# Only show the progress bar once on each machine.
|
| 429 |
+
disable=not accelerator.is_local_main_process,
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
def get_sigmas(timesteps, n_dim=4, dtype=torch.float32):
|
| 433 |
+
sigmas = noise_scheduler_copy.sigmas.to(device=accelerator.device, dtype=dtype)
|
| 434 |
+
schedule_timesteps = noise_scheduler_copy.timesteps.to(accelerator.device)
|
| 435 |
+
timesteps = timesteps.to(accelerator.device)
|
| 436 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 437 |
+
|
| 438 |
+
sigma = sigmas[step_indices].flatten()
|
| 439 |
+
while len(sigma.shape) < n_dim:
|
| 440 |
+
sigma = sigma.unsqueeze(-1)
|
| 441 |
+
return sigma
|
| 442 |
+
|
| 443 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 444 |
+
transformer.train()
|
| 445 |
+
for step, batch in enumerate(train_dataloader):
|
| 446 |
+
with torch.no_grad():
|
| 447 |
+
prompts = batch["descriptions"]
|
| 448 |
+
prompt_embeds, pooled_prompt_embeds, text_ids = compute_text_embeddings(
|
| 449 |
+
prompts, text_encoders, tokenizers
|
| 450 |
+
)
|
| 451 |
+
# 1.1 Convert images to latent space.
|
| 452 |
+
latent_image = encode_images(pixels=batch["pixel_values"],vae=vae,weight_dtype=weight_dtype)
|
| 453 |
+
# 1.2 Get positional id.
|
| 454 |
+
latent_image_ids = FluxPipeline._prepare_latent_image_ids(
|
| 455 |
+
latent_image.shape[0],
|
| 456 |
+
latent_image.shape[2] // 2,
|
| 457 |
+
latent_image.shape[3] // 2,
|
| 458 |
+
accelerator.device,
|
| 459 |
+
weight_dtype,
|
| 460 |
+
)
|
| 461 |
+
# 2.1 Convert Conditions to latent space list.
|
| 462 |
+
# 2.2 Get Conditions positional id list.
|
| 463 |
+
# 2.3 Get Conditions types string list.
|
| 464 |
+
# (bs, cond_num, c, h, w) -> [cond_num, (bs, c, h ,w)]
|
| 465 |
+
condition_latents = list(torch.unbind(batch["condition_latents"], dim=1))
|
| 466 |
+
# [cond_num, (len ,3) ]
|
| 467 |
+
condition_ids = []
|
| 468 |
+
# [cond_num]
|
| 469 |
+
condition_types = batch["condition_types"][0]
|
| 470 |
+
for i,images_per_condition in enumerate(condition_latents):
|
| 471 |
+
# i means condition No.i.
|
| 472 |
+
# images_per_condition = (bs, c, h ,w)
|
| 473 |
+
images_per_condition = encode_images(pixels=images_per_condition,vae=vae,weight_dtype=weight_dtype)
|
| 474 |
+
cond_ids = FluxPipeline._prepare_latent_image_ids(
|
| 475 |
+
images_per_condition.shape[0],
|
| 476 |
+
images_per_condition.shape[2] // 2,
|
| 477 |
+
images_per_condition.shape[3] // 2,
|
| 478 |
+
accelerator.device,
|
| 479 |
+
weight_dtype,
|
| 480 |
+
)
|
| 481 |
+
if condition_types[i] == "subject":
|
| 482 |
+
cond_ids[:, 2] += images_per_condition.shape[2] // 2
|
| 483 |
+
condition_ids.append(cond_ids)
|
| 484 |
+
condition_latents[i] = images_per_condition
|
| 485 |
+
|
| 486 |
+
# 3 Sample noise that we'll add to the latents
|
| 487 |
+
noise = torch.randn_like(latent_image)
|
| 488 |
+
bsz = latent_image.shape[0]
|
| 489 |
+
|
| 490 |
+
# 4 Sample a random timestep for each image
|
| 491 |
+
u = compute_density_for_timestep_sampling(
|
| 492 |
+
weighting_scheme=args.weighting_scheme,
|
| 493 |
+
batch_size=bsz,
|
| 494 |
+
)
|
| 495 |
+
indices = (u * noise_scheduler_copy.config.num_train_timesteps).long()
|
| 496 |
+
timesteps = noise_scheduler_copy.timesteps[indices].to(device=accelerator.device)
|
| 497 |
+
|
| 498 |
+
# 5 Add noise according to flow matching.
|
| 499 |
+
# zt = (1 - texp) * x + texp * z1
|
| 500 |
+
sigmas = get_sigmas(timesteps, n_dim=latent_image.ndim, dtype=latent_image.dtype)
|
| 501 |
+
noisy_model_input = (1.0 - sigmas) * latent_image + sigmas * noise
|
| 502 |
+
|
| 503 |
+
# 6.1 pack noisy_model_input
|
| 504 |
+
packed_noisy_model_input = FluxPipeline._pack_latents(
|
| 505 |
+
noisy_model_input,
|
| 506 |
+
batch_size=latent_image.shape[0],
|
| 507 |
+
num_channels_latents=latent_image.shape[1],
|
| 508 |
+
height=latent_image.shape[2],
|
| 509 |
+
width=latent_image.shape[3],
|
| 510 |
+
)
|
| 511 |
+
# 6.2 pack Conditions latents
|
| 512 |
+
for i, images_per_condition in enumerate(condition_latents):
|
| 513 |
+
condition_latents[i] = FluxPipeline._pack_latents(
|
| 514 |
+
images_per_condition,
|
| 515 |
+
batch_size=latent_image.shape[0],
|
| 516 |
+
num_channels_latents=latent_image.shape[1],
|
| 517 |
+
height=latent_image.shape[2],
|
| 518 |
+
width=latent_image.shape[3],
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
# 7 handle guidance
|
| 522 |
+
if accelerator.unwrap_model(transformer).config.guidance_embeds:
|
| 523 |
+
guidance = torch.tensor([args.guidance_scale], device=accelerator.device)
|
| 524 |
+
guidance = guidance.expand(latent_image.shape[0])
|
| 525 |
+
else:
|
| 526 |
+
guidance = None
|
| 527 |
+
with accelerator.accumulate(transformer):
|
| 528 |
+
# 8 Predict the noise residual
|
| 529 |
+
model_pred = transformer(
|
| 530 |
+
model_config={},
|
| 531 |
+
# Inputs of the condition (new feature)
|
| 532 |
+
condition_latents=condition_latents,
|
| 533 |
+
condition_ids=condition_ids,
|
| 534 |
+
condition_type_ids=None,
|
| 535 |
+
condition_types = condition_types,
|
| 536 |
+
# Inputs to the original transformer
|
| 537 |
+
hidden_states=packed_noisy_model_input,
|
| 538 |
+
timestep=timesteps / 1000,
|
| 539 |
+
guidance=guidance,
|
| 540 |
+
pooled_projections=pooled_prompt_embeds,
|
| 541 |
+
encoder_hidden_states=prompt_embeds,
|
| 542 |
+
txt_ids=text_ids,
|
| 543 |
+
img_ids=latent_image_ids,
|
| 544 |
+
return_dict=False,
|
| 545 |
+
)[0]
|
| 546 |
+
model_pred = FluxPipeline._unpack_latents(
|
| 547 |
+
model_pred,
|
| 548 |
+
height=noisy_model_input.shape[2] * vae_scale_factor,
|
| 549 |
+
width=noisy_model_input.shape[3] * vae_scale_factor,
|
| 550 |
+
vae_scale_factor=vae_scale_factor,
|
| 551 |
+
)
|
| 552 |
+
# these weighting schemes use a uniform timestep sampling
|
| 553 |
+
# and instead post-weight the loss
|
| 554 |
+
weighting = compute_loss_weighting_for_sd3(weighting_scheme=args.weighting_scheme, sigmas=sigmas)
|
| 555 |
+
# flow matching loss
|
| 556 |
+
target = noise - latent_image
|
| 557 |
+
|
| 558 |
+
loss = torch.mean(
|
| 559 |
+
(weighting.float() * (model_pred.float() - target.float()) ** 2).reshape(target.shape[0], -1),
|
| 560 |
+
1,
|
| 561 |
+
)
|
| 562 |
+
loss = loss.mean()
|
| 563 |
+
|
| 564 |
+
accelerator.backward(loss)
|
| 565 |
+
|
| 566 |
+
if accelerator.sync_gradients:
|
| 567 |
+
params_to_clip = transformer.parameters()
|
| 568 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 569 |
+
optimizer.step()
|
| 570 |
+
lr_scheduler.step()
|
| 571 |
+
optimizer.zero_grad()
|
| 572 |
+
|
| 573 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 574 |
+
if accelerator.sync_gradients:
|
| 575 |
+
progress_bar.update(1)
|
| 576 |
+
global_step += 1
|
| 577 |
+
if accelerator.is_main_process:
|
| 578 |
+
if global_step % args.checkpointing_steps == 0:
|
| 579 |
+
save_path = os.path.join(args.work_dir, f"checkpoint-{global_step}")
|
| 580 |
+
accelerator.save_state(save_path)
|
| 581 |
+
logger.info(f"Saved state to {save_path}")
|
| 582 |
+
logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 583 |
+
progress_bar.set_postfix(**logs)
|
| 584 |
+
accelerator.log(logs, step=global_step)
|
| 585 |
+
|
| 586 |
+
if global_step >= args.max_train_steps:
|
| 587 |
+
break
|
| 588 |
+
|
| 589 |
+
accelerator.wait_for_everyone()
|
| 590 |
+
accelerator.end_training()
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
if __name__ == "__main__":
|
| 594 |
+
args = parse_args()
|
| 595 |
+
main(args)
|
| 596 |
+
|