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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flux LoRA DDP Training Script
|
| 3 |
+
- 2 GPU DDP via accelerate
|
| 4 |
+
- bf16 mixed precision
|
| 5 |
+
- Gradient checkpointing
|
| 6 |
+
- WebDataset loading
|
| 7 |
+
- Checkpoint every 1000 steps with auto-upload to HF
|
| 8 |
+
- Auto-resume from latest checkpoint
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
import math
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from torch.utils.data import DataLoader
|
| 19 |
+
|
| 20 |
+
import webdataset as wds
|
| 21 |
+
from accelerate import Accelerator
|
| 22 |
+
from accelerate.utils import set_seed
|
| 23 |
+
from diffusers import FluxPipeline, FlowMatchEulerDiscreteScheduler
|
| 24 |
+
from diffusers.training_utils import compute_density_for_timestep_sampling
|
| 25 |
+
from peft import LoraConfig, get_peft_model
|
| 26 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
| 27 |
+
from huggingface_hub import HfApi, upload_folder
|
| 28 |
+
from torchvision import transforms
|
| 29 |
+
from PIL import Image
|
| 30 |
+
import io
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_args():
|
| 34 |
+
import argparse
|
| 35 |
+
p = argparse.ArgumentParser()
|
| 36 |
+
p.add_argument("--model-name", default="black-forest-labs/FLUX.1-dev")
|
| 37 |
+
p.add_argument("--data-dir", required=True)
|
| 38 |
+
p.add_argument("--output-dir", required=True)
|
| 39 |
+
p.add_argument("--batch-size", type=int, default=1)
|
| 40 |
+
p.add_argument("--gradient-accumulation", type=int, default=4)
|
| 41 |
+
p.add_argument("--learning-rate", type=float, default=1e-4)
|
| 42 |
+
p.add_argument("--lr-warmup-steps", type=int, default=100)
|
| 43 |
+
p.add_argument("--max-train-steps", type=int, default=100000)
|
| 44 |
+
p.add_argument("--save-steps", type=int, default=1000)
|
| 45 |
+
p.add_argument("--sample-steps", type=int, default=1000)
|
| 46 |
+
p.add_argument("--lora-rank", type=int, default=128)
|
| 47 |
+
p.add_argument("--lora-alpha", type=int, default=64)
|
| 48 |
+
p.add_argument("--max-grad-norm", type=float, default=1.0)
|
| 49 |
+
p.add_argument("--seed", type=int, default=42)
|
| 50 |
+
p.add_argument("--resolution", type=int, default=1024)
|
| 51 |
+
p.add_argument("--hf-user", default="memoryai")
|
| 52 |
+
p.add_argument("--hf-repo", default="4k-image-model-checkpoints")
|
| 53 |
+
return p.parse_args()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def create_webdataset(data_dir, resolution, tokenizer, tokenizer_2):
|
| 57 |
+
transform = transforms.Compose([
|
| 58 |
+
transforms.Resize(resolution, interpolation=transforms.InterpolationMode.LANCZOS),
|
| 59 |
+
transforms.CenterCrop(resolution),
|
| 60 |
+
transforms.ToTensor(),
|
| 61 |
+
transforms.Normalize([0.5], [0.5]),
|
| 62 |
+
])
|
| 63 |
+
|
| 64 |
+
def process_sample(sample):
|
| 65 |
+
try:
|
| 66 |
+
image = sample.get("jpg") or sample.get("png") or sample.get("jpeg")
|
| 67 |
+
if image is None:
|
| 68 |
+
return None
|
| 69 |
+
if not isinstance(image, Image.Image):
|
| 70 |
+
image = Image.open(io.BytesIO(image)).convert("RGB")
|
| 71 |
+
else:
|
| 72 |
+
image = image.convert("RGB")
|
| 73 |
+
image = transform(image)
|
| 74 |
+
caption = sample.get("txt", "")
|
| 75 |
+
if isinstance(caption, bytes):
|
| 76 |
+
caption = caption.decode("utf-8")
|
| 77 |
+
|
| 78 |
+
tokens_1 = tokenizer(
|
| 79 |
+
caption, max_length=77, padding="max_length",
|
| 80 |
+
truncation=True, return_tensors="pt"
|
| 81 |
+
)
|
| 82 |
+
tokens_2 = tokenizer_2(
|
| 83 |
+
caption, max_length=512, padding="max_length",
|
| 84 |
+
truncation=True, return_tensors="pt"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
"pixel_values": image,
|
| 89 |
+
"input_ids_1": tokens_1.input_ids.squeeze(0),
|
| 90 |
+
"attention_mask_1": tokens_1.attention_mask.squeeze(0),
|
| 91 |
+
"input_ids_2": tokens_2.input_ids.squeeze(0),
|
| 92 |
+
"attention_mask_2": tokens_2.attention_mask.squeeze(0),
|
| 93 |
+
}
|
| 94 |
+
except Exception:
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
shards = sorted([str(p) for p in Path(data_dir).glob("*.tar")])
|
| 98 |
+
if not shards:
|
| 99 |
+
raise ValueError(f"No .tar shards found in {data_dir}")
|
| 100 |
+
|
| 101 |
+
dataset = (
|
| 102 |
+
wds.WebDataset(shards, shardshuffle=1000, nodesplitter=wds.split_by_node, empty_check=False)
|
| 103 |
+
.decode("pil")
|
| 104 |
+
.shuffle(1000)
|
| 105 |
+
.map(process_sample)
|
| 106 |
+
.select(lambda x: x is not None)
|
| 107 |
+
.batched(1, collation_fn=lambda batch: {
|
| 108 |
+
"pixel_values": torch.stack([b["pixel_values"] for b in batch]),
|
| 109 |
+
"input_ids_1": torch.stack([b["input_ids_1"] for b in batch]),
|
| 110 |
+
"attention_mask_1": torch.stack([b["attention_mask_1"] for b in batch]),
|
| 111 |
+
"input_ids_2": torch.stack([b["input_ids_2"] for b in batch]),
|
| 112 |
+
"attention_mask_2": torch.stack([b["attention_mask_2"] for b in batch]),
|
| 113 |
+
})
|
| 114 |
+
)
|
| 115 |
+
return dataset
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def find_latest_checkpoint(output_dir):
|
| 119 |
+
output_path = Path(output_dir)
|
| 120 |
+
if not output_path.exists():
|
| 121 |
+
return None, 0
|
| 122 |
+
|
| 123 |
+
checkpoints = sorted(
|
| 124 |
+
[d for d in output_path.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")],
|
| 125 |
+
key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if checkpoints:
|
| 129 |
+
latest = checkpoints[-1]
|
| 130 |
+
state_file = latest / "training_state.pt"
|
| 131 |
+
if state_file.exists():
|
| 132 |
+
state = torch.load(state_file, map_location="cpu")
|
| 133 |
+
return latest, state.get("global_step", 0)
|
| 134 |
+
|
| 135 |
+
return None, 0
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def upload_checkpoint(output_dir, checkpoint_name, hf_user, hf_repo):
|
| 139 |
+
try:
|
| 140 |
+
repo_id = f"{hf_user}/{hf_repo}"
|
| 141 |
+
api = HfApi()
|
| 142 |
+
try:
|
| 143 |
+
api.repo_info(repo_id=repo_id, repo_type="model")
|
| 144 |
+
except Exception:
|
| 145 |
+
api.create_repo(repo_id=repo_id, repo_type="model", private=True)
|
| 146 |
+
|
| 147 |
+
ckpt_path = Path(output_dir) / checkpoint_name
|
| 148 |
+
if ckpt_path.exists():
|
| 149 |
+
path_in_repo = f"flux_lora_4k/{checkpoint_name}"
|
| 150 |
+
upload_folder(
|
| 151 |
+
folder_path=str(ckpt_path),
|
| 152 |
+
repo_id=repo_id,
|
| 153 |
+
path_in_repo=path_in_repo,
|
| 154 |
+
repo_type="model",
|
| 155 |
+
)
|
| 156 |
+
print(f" Uploaded {checkpoint_name} -> {repo_id}/{path_in_repo}")
|
| 157 |
+
|
| 158 |
+
samples_dir = Path(output_dir) / "samples"
|
| 159 |
+
if samples_dir.exists() and any(samples_dir.glob("*.png")):
|
| 160 |
+
upload_folder(
|
| 161 |
+
folder_path=str(samples_dir),
|
| 162 |
+
repo_id=repo_id,
|
| 163 |
+
path_in_repo="flux_lora_4k/samples",
|
| 164 |
+
repo_type="model",
|
| 165 |
+
)
|
| 166 |
+
except Exception as e:
|
| 167 |
+
print(f" Upload failed (non-fatal): {e}")
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def generate_samples(accelerator, pipe, output_dir, step, prompts=None):
|
| 171 |
+
if not accelerator.is_main_process:
|
| 172 |
+
return
|
| 173 |
+
|
| 174 |
+
if prompts is None:
|
| 175 |
+
prompts = [
|
| 176 |
+
"A stunning 4K photograph of a mountain landscape at golden hour",
|
| 177 |
+
"A detailed close-up of a butterfly on a flower, 4K ultra HD",
|
| 178 |
+
"A modern city skyline at night with reflections, high resolution",
|
| 179 |
+
"A portrait of an elderly craftsman in his workshop, natural lighting",
|
| 180 |
+
]
|
| 181 |
+
|
| 182 |
+
samples_dir = Path(output_dir) / "samples"
|
| 183 |
+
samples_dir.mkdir(exist_ok=True)
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
pipe.to(accelerator.device)
|
| 187 |
+
with torch.no_grad():
|
| 188 |
+
for i, prompt in enumerate(prompts):
|
| 189 |
+
image = pipe(
|
| 190 |
+
prompt=prompt,
|
| 191 |
+
num_inference_steps=20,
|
| 192 |
+
guidance_scale=3.5,
|
| 193 |
+
height=1024,
|
| 194 |
+
width=1024,
|
| 195 |
+
).images[0]
|
| 196 |
+
image.save(samples_dir / f"step_{step:06d}_{i}.png")
|
| 197 |
+
print(f" Samples saved at step {step}")
|
| 198 |
+
except Exception as e:
|
| 199 |
+
print(f" Sample generation failed (non-fatal): {e}")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def main():
|
| 203 |
+
args = get_args()
|
| 204 |
+
set_seed(args.seed)
|
| 205 |
+
|
| 206 |
+
accelerator = Accelerator(
|
| 207 |
+
gradient_accumulation_steps=args.gradient_accumulation,
|
| 208 |
+
mixed_precision="bf16",
|
| 209 |
+
log_with=None,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
if accelerator.is_main_process:
|
| 213 |
+
print(f" Devices: {accelerator.num_processes}")
|
| 214 |
+
print(f" Batch size (per device): {args.batch_size}")
|
| 215 |
+
print(f" Gradient accumulation: {args.gradient_accumulation}")
|
| 216 |
+
print(f" Effective batch size: {args.batch_size * args.gradient_accumulation * accelerator.num_processes}")
|
| 217 |
+
print(f" LoRA rank: {args.lora_rank}, alpha: {args.lora_alpha}")
|
| 218 |
+
print(f" Max steps: {args.max_train_steps}")
|
| 219 |
+
print(f" Save every: {args.save_steps} steps")
|
| 220 |
+
|
| 221 |
+
# Load tokenizers
|
| 222 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.model_name, subfolder="tokenizer")
|
| 223 |
+
tokenizer_2 = T5TokenizerFast.from_pretrained(args.model_name, subfolder="tokenizer_2")
|
| 224 |
+
|
| 225 |
+
# Load text encoders
|
| 226 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 227 |
+
args.model_name, subfolder="text_encoder", torch_dtype=torch.bfloat16
|
| 228 |
+
)
|
| 229 |
+
text_encoder_2 = T5EncoderModel.from_pretrained(
|
| 230 |
+
args.model_name, subfolder="text_encoder_2", torch_dtype=torch.bfloat16
|
| 231 |
+
)
|
| 232 |
+
text_encoder.requires_grad_(False)
|
| 233 |
+
text_encoder_2.requires_grad_(False)
|
| 234 |
+
|
| 235 |
+
# Load pipeline for VAE and transformer
|
| 236 |
+
pipe = FluxPipeline.from_pretrained(args.model_name, torch_dtype=torch.bfloat16)
|
| 237 |
+
vae = pipe.vae
|
| 238 |
+
transformer = pipe.transformer
|
| 239 |
+
noise_scheduler = pipe.scheduler
|
| 240 |
+
|
| 241 |
+
vae.requires_grad_(False)
|
| 242 |
+
|
| 243 |
+
# Apply LoRA to transformer
|
| 244 |
+
lora_config = LoraConfig(
|
| 245 |
+
r=args.lora_rank,
|
| 246 |
+
lora_alpha=args.lora_alpha,
|
| 247 |
+
target_modules=["to_q", "to_k", "to_v", "to_out.0", "proj_in", "proj_out",
|
| 248 |
+
"ff.net.0.proj", "ff.net.2"],
|
| 249 |
+
lora_dropout=0.0,
|
| 250 |
+
)
|
| 251 |
+
transformer = get_peft_model(transformer, lora_config)
|
| 252 |
+
transformer.enable_gradient_checkpointing()
|
| 253 |
+
|
| 254 |
+
if accelerator.is_main_process:
|
| 255 |
+
trainable = sum(p.numel() for p in transformer.parameters() if p.requires_grad)
|
| 256 |
+
total = sum(p.numel() for p in transformer.parameters())
|
| 257 |
+
print(f" Trainable params: {trainable:,} / {total:,} ({100*trainable/total:.2f}%)")
|
| 258 |
+
|
| 259 |
+
# Optimizer
|
| 260 |
+
optimizer = torch.optim.AdamW(
|
| 261 |
+
[p for p in transformer.parameters() if p.requires_grad],
|
| 262 |
+
lr=args.learning_rate,
|
| 263 |
+
betas=(0.9, 0.999),
|
| 264 |
+
weight_decay=0.01,
|
| 265 |
+
eps=1e-8,
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# Dataset
|
| 269 |
+
dataset = create_webdataset(args.data_dir, args.resolution, tokenizer, tokenizer_2)
|
| 270 |
+
|
| 271 |
+
dataloader = DataLoader(
|
| 272 |
+
dataset, batch_size=None, num_workers=2, pin_memory=True,
|
| 273 |
+
prefetch_factor=2,
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
# LR Scheduler
|
| 277 |
+
from torch.optim.lr_scheduler import LambdaLR
|
| 278 |
+
def lr_lambda(step):
|
| 279 |
+
if step < args.lr_warmup_steps:
|
| 280 |
+
return step / max(1, args.lr_warmup_steps)
|
| 281 |
+
return 1.0
|
| 282 |
+
lr_scheduler = LambdaLR(optimizer, lr_lambda)
|
| 283 |
+
|
| 284 |
+
# Prepare with accelerate (dataloader excluded - WebDataset handles DDP splitting)
|
| 285 |
+
transformer, optimizer, lr_scheduler = accelerator.prepare(
|
| 286 |
+
transformer, optimizer, lr_scheduler
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# Move frozen models to device
|
| 290 |
+
vae.to(accelerator.device, dtype=torch.bfloat16)
|
| 291 |
+
text_encoder.to(accelerator.device)
|
| 292 |
+
text_encoder_2.to(accelerator.device)
|
| 293 |
+
|
| 294 |
+
# Resume from checkpoint
|
| 295 |
+
output_dir = Path(args.output_dir)
|
| 296 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 297 |
+
resume_ckpt, global_step = find_latest_checkpoint(args.output_dir)
|
| 298 |
+
|
| 299 |
+
if resume_ckpt is not None:
|
| 300 |
+
if accelerator.is_main_process:
|
| 301 |
+
print(f" Resuming from {resume_ckpt.name} (step {global_step})")
|
| 302 |
+
state = torch.load(resume_ckpt / "training_state.pt", map_location="cpu")
|
| 303 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 304 |
+
lr_scheduler.load_state_dict(state["lr_scheduler"])
|
| 305 |
+
# Load LoRA weights
|
| 306 |
+
from peft import set_peft_model_state_dict
|
| 307 |
+
lora_state = torch.load(resume_ckpt / "lora_weights.pt", map_location="cpu")
|
| 308 |
+
set_peft_model_state_dict(accelerator.unwrap_model(transformer), lora_state)
|
| 309 |
+
else:
|
| 310 |
+
if accelerator.is_main_process:
|
| 311 |
+
print(" Starting from scratch")
|
| 312 |
+
|
| 313 |
+
# Training loop
|
| 314 |
+
if accelerator.is_main_process:
|
| 315 |
+
print(f"\n Training started at step {global_step}...")
|
| 316 |
+
|
| 317 |
+
transformer.train()
|
| 318 |
+
step_times = []
|
| 319 |
+
data_iter = iter(dataloader)
|
| 320 |
+
|
| 321 |
+
while global_step < args.max_train_steps:
|
| 322 |
+
step_start = time.time()
|
| 323 |
+
|
| 324 |
+
try:
|
| 325 |
+
batch = next(data_iter)
|
| 326 |
+
except (StopIteration, Exception):
|
| 327 |
+
data_iter = iter(dataloader)
|
| 328 |
+
batch = next(data_iter)
|
| 329 |
+
|
| 330 |
+
with accelerator.accumulate(transformer):
|
| 331 |
+
pixel_values = batch["pixel_values"].to(dtype=torch.bfloat16)
|
| 332 |
+
|
| 333 |
+
# Encode images
|
| 334 |
+
with torch.no_grad():
|
| 335 |
+
latents = vae.encode(pixel_values).latent_dist.sample()
|
| 336 |
+
latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor
|
| 337 |
+
|
| 338 |
+
# Pack latents for Flux
|
| 339 |
+
batch_size, channels, height, width = latents.shape
|
| 340 |
+
latents = latents.reshape(batch_size, channels, height // 2, 2, width // 2, 2)
|
| 341 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5).reshape(batch_size, (height // 2) * (width // 2), channels * 4)
|
| 342 |
+
|
| 343 |
+
# Text encoding
|
| 344 |
+
text_output_1 = text_encoder(
|
| 345 |
+
batch["input_ids_1"], attention_mask=batch["attention_mask_1"]
|
| 346 |
+
)
|
| 347 |
+
pooled_prompt_embeds = text_output_1.pooler_output
|
| 348 |
+
|
| 349 |
+
text_output_2 = text_encoder_2(
|
| 350 |
+
batch["input_ids_2"], attention_mask=batch["attention_mask_2"]
|
| 351 |
+
)
|
| 352 |
+
prompt_embeds = text_output_2.last_hidden_state
|
| 353 |
+
|
| 354 |
+
# Sample noise and timesteps
|
| 355 |
+
noise = torch.randn_like(latents)
|
| 356 |
+
timesteps = torch.rand(batch_size, device=latents.device, dtype=torch.bfloat16)
|
| 357 |
+
|
| 358 |
+
# Flow matching: interpolate between noise and latents
|
| 359 |
+
sigmas = timesteps.view(-1, 1, 1)
|
| 360 |
+
noisy_latents = (1 - sigmas) * latents + sigmas * noise
|
| 361 |
+
|
| 362 |
+
# Predict velocity
|
| 363 |
+
model_pred = transformer(
|
| 364 |
+
hidden_states=noisy_latents,
|
| 365 |
+
timestep=timesteps * 1000,
|
| 366 |
+
encoder_hidden_states=prompt_embeds,
|
| 367 |
+
pooled_projections=pooled_prompt_embeds,
|
| 368 |
+
return_dict=False,
|
| 369 |
+
)[0]
|
| 370 |
+
|
| 371 |
+
# Flow matching loss: predict (noise - latents)
|
| 372 |
+
target = noise - latents
|
| 373 |
+
loss = F.mse_loss(model_pred, target, reduction="mean")
|
| 374 |
+
|
| 375 |
+
accelerator.backward(loss)
|
| 376 |
+
if accelerator.sync_gradients:
|
| 377 |
+
accelerator.clip_grad_norm_(transformer.parameters(), args.max_grad_norm)
|
| 378 |
+
optimizer.step()
|
| 379 |
+
lr_scheduler.step()
|
| 380 |
+
optimizer.zero_grad()
|
| 381 |
+
|
| 382 |
+
if accelerator.sync_gradients:
|
| 383 |
+
global_step += 1
|
| 384 |
+
step_time = time.time() - step_start
|
| 385 |
+
step_times.append(step_time)
|
| 386 |
+
|
| 387 |
+
# Logging
|
| 388 |
+
if global_step % 50 == 0 and accelerator.is_main_process:
|
| 389 |
+
avg_time = sum(step_times[-50:]) / len(step_times[-50:])
|
| 390 |
+
steps_remaining = args.max_train_steps - global_step
|
| 391 |
+
eta_hours = (steps_remaining * avg_time) / 3600
|
| 392 |
+
print(
|
| 393 |
+
f" Step {global_step}/{args.max_train_steps} | "
|
| 394 |
+
f"Loss: {loss.item():.4f} | "
|
| 395 |
+
f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
|
| 396 |
+
f"Time/step: {avg_time:.2f}s | "
|
| 397 |
+
f"ETA: {eta_hours:.1f}h"
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
# Save checkpoint
|
| 401 |
+
if global_step % args.save_steps == 0:
|
| 402 |
+
if accelerator.is_main_process:
|
| 403 |
+
ckpt_name = f"checkpoint-{global_step}"
|
| 404 |
+
ckpt_path = output_dir / ckpt_name
|
| 405 |
+
ckpt_path.mkdir(exist_ok=True)
|
| 406 |
+
|
| 407 |
+
# Save LoRA weights
|
| 408 |
+
from peft import get_peft_model_state_dict
|
| 409 |
+
lora_state = get_peft_model_state_dict(accelerator.unwrap_model(transformer))
|
| 410 |
+
torch.save(lora_state, ckpt_path / "lora_weights.pt")
|
| 411 |
+
|
| 412 |
+
# Save training state
|
| 413 |
+
torch.save({
|
| 414 |
+
"global_step": global_step,
|
| 415 |
+
"optimizer": optimizer.state_dict(),
|
| 416 |
+
"lr_scheduler": lr_scheduler.state_dict(),
|
| 417 |
+
}, ckpt_path / "training_state.pt")
|
| 418 |
+
|
| 419 |
+
print(f" Checkpoint saved: {ckpt_name}")
|
| 420 |
+
|
| 421 |
+
# Upload to HF
|
| 422 |
+
upload_checkpoint(
|
| 423 |
+
args.output_dir, ckpt_name, args.hf_user, args.hf_repo
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
# Clean old checkpoints (keep last 3)
|
| 427 |
+
all_ckpts = sorted(
|
| 428 |
+
[d for d in output_dir.iterdir() if d.is_dir() and d.name.startswith("checkpoint-")],
|
| 429 |
+
key=lambda p: int(p.name.split("-")[1]),
|
| 430 |
+
)
|
| 431 |
+
for old_ckpt in all_ckpts[:-3]:
|
| 432 |
+
import shutil
|
| 433 |
+
shutil.rmtree(old_ckpt)
|
| 434 |
+
print(f" Removed old: {old_ckpt.name}")
|
| 435 |
+
|
| 436 |
+
accelerator.wait_for_everyone()
|
| 437 |
+
|
| 438 |
+
# Generate samples
|
| 439 |
+
if global_step % args.sample_steps == 0:
|
| 440 |
+
if accelerator.is_main_process:
|
| 441 |
+
generate_samples(accelerator, pipe, args.output_dir, global_step)
|
| 442 |
+
|
| 443 |
+
# Final save
|
| 444 |
+
if accelerator.is_main_process:
|
| 445 |
+
final_path = output_dir / "final"
|
| 446 |
+
final_path.mkdir(exist_ok=True)
|
| 447 |
+
from peft import get_peft_model_state_dict
|
| 448 |
+
lora_state = get_peft_model_state_dict(accelerator.unwrap_model(transformer))
|
| 449 |
+
torch.save(lora_state, final_path / "lora_weights.pt")
|
| 450 |
+
torch.save({"global_step": global_step}, final_path / "training_state.pt")
|
| 451 |
+
print(f"\n Training complete! Final model saved at step {global_step}")
|
| 452 |
+
upload_checkpoint(args.output_dir, "final", args.hf_user, args.hf_repo)
|
| 453 |
+
|
| 454 |
+
accelerator.end_training()
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
if __name__ == "__main__":
|
| 458 |
+
main()
|