Upload folder using huggingface_hub
Browse files
scripts/training/run_train_flux.sh
CHANGED
|
@@ -1,25 +1,29 @@
|
|
| 1 |
#!/bin/bash
|
| 2 |
-
# Launch Flux LoRA training
|
|
|
|
|
|
|
| 3 |
# Usage: bash scripts/training/run_train_flux.sh
|
| 4 |
|
| 5 |
export PYTHONPATH="/home/adminuser/chungcat:$PYTHONPATH"
|
| 6 |
-
export
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
--config_file /home/adminuser/chungcat/configs/accelerate_config.yaml \
|
| 10 |
-
/home/adminuser/chungcat/scripts/training/train_flux_lora.py \
|
| 11 |
--model-name "black-forest-labs/FLUX.1-schnell" \
|
| 12 |
--data-dir "/home/adminuser/chungcat/data/processed/flux_train/shards" \
|
| 13 |
--output-dir "/home/adminuser/chungcat/checkpoints/flux_lora" \
|
| 14 |
--resolution 1024 \
|
| 15 |
--batch-size 1 \
|
| 16 |
-
--gradient-accumulation
|
| 17 |
--learning-rate 1e-4 \
|
| 18 |
--lr-scheduler cosine \
|
| 19 |
-
--lr-warmup-steps
|
| 20 |
--max-train-steps 100000 \
|
| 21 |
--save-steps 5000 \
|
| 22 |
--lora-rank 128 \
|
| 23 |
--lora-alpha 128 \
|
| 24 |
-
--
|
| 25 |
-
--
|
|
|
|
|
|
|
|
|
| 1 |
#!/bin/bash
|
| 2 |
+
# Launch Flux LoRA training - split model across 2 GPUs
|
| 3 |
+
# GPU 0: VAE + CLIP + T5 (encoding)
|
| 4 |
+
# GPU 1: Flux Transformer (training)
|
| 5 |
# Usage: bash scripts/training/run_train_flux.sh
|
| 6 |
|
| 7 |
export PYTHONPATH="/home/adminuser/chungcat:$PYTHONPATH"
|
| 8 |
+
export HF_HOME="/home/adminuser/.cache/huggingface"
|
| 9 |
+
export WANDB_MODE=disabled
|
| 10 |
+
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
| 11 |
|
| 12 |
+
python3 /home/adminuser/chungcat/scripts/training/train_flux_lora.py \
|
|
|
|
|
|
|
| 13 |
--model-name "black-forest-labs/FLUX.1-schnell" \
|
| 14 |
--data-dir "/home/adminuser/chungcat/data/processed/flux_train/shards" \
|
| 15 |
--output-dir "/home/adminuser/chungcat/checkpoints/flux_lora" \
|
| 16 |
--resolution 1024 \
|
| 17 |
--batch-size 1 \
|
| 18 |
+
--gradient-accumulation 8 \
|
| 19 |
--learning-rate 1e-4 \
|
| 20 |
--lr-scheduler cosine \
|
| 21 |
+
--lr-warmup-steps 1000 \
|
| 22 |
--max-train-steps 100000 \
|
| 23 |
--save-steps 5000 \
|
| 24 |
--lora-rank 128 \
|
| 25 |
--lora-alpha 128 \
|
| 26 |
+
--seed 42 \
|
| 27 |
+
--gradient-checkpointing \
|
| 28 |
+
--encode-device cuda:0 \
|
| 29 |
+
--train-device cuda:1
|
scripts/training/run_train_sr_2gpu.sh
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# SR Training + Auto-backup for VPS 2x H100
|
| 3 |
+
# This script runs on the 2-GPU VPS:
|
| 4 |
+
# - Stage 2: SR 1K→2K
|
| 5 |
+
# - Stage 3: SR 2K→4K (after Stage 2 converges)
|
| 6 |
+
# - Auto-backup to HuggingFace every 30 minutes
|
| 7 |
+
#
|
| 8 |
+
# Usage: bash scripts/training/run_train_sr_2gpu.sh <hf_token>
|
| 9 |
+
|
| 10 |
+
set -e
|
| 11 |
+
|
| 12 |
+
HF_TOKEN=${1:-""}
|
| 13 |
+
PROJECT_DIR="/home/adminuser/chungcat"
|
| 14 |
+
|
| 15 |
+
if [ -z "$HF_TOKEN" ]; then
|
| 16 |
+
echo "Usage: bash scripts/training/run_train_sr_2gpu.sh <hf_token>"
|
| 17 |
+
exit 1
|
| 18 |
+
fi
|
| 19 |
+
|
| 20 |
+
# Login HuggingFace
|
| 21 |
+
echo "=== Logging into HuggingFace ==="
|
| 22 |
+
python3 -c "from huggingface_hub import login; login(token='$HF_TOKEN')"
|
| 23 |
+
HF_USER=$(python3 -c "from huggingface_hub import HfApi; print(HfApi().whoami()['name'])")
|
| 24 |
+
echo "Logged in as: $HF_USER"
|
| 25 |
+
|
| 26 |
+
# Start auto-backup in background
|
| 27 |
+
echo "=== Starting auto-backup (every 30 min) ==="
|
| 28 |
+
pkill -f "backup.py --auto" 2>/dev/null || true
|
| 29 |
+
nohup python3 "$PROJECT_DIR/scripts/backup.py" --auto --interval 30 --user "$HF_USER" \
|
| 30 |
+
> "$PROJECT_DIR/logs/backup.log" 2>&1 &
|
| 31 |
+
echo "Auto-backup PID: $!"
|
| 32 |
+
|
| 33 |
+
# Create SR pairs if not exist
|
| 34 |
+
SR_PAIRS="$PROJECT_DIR/data/processed/sr_pairs"
|
| 35 |
+
if [ ! -d "$SR_PAIRS/1k_input" ] || [ $(ls "$SR_PAIRS/1k_input"/*.png 2>/dev/null | wc -l) -lt 100 ]; then
|
| 36 |
+
echo "=== Creating SR pairs from 4K images ==="
|
| 37 |
+
python3 "$PROJECT_DIR/scripts/data_collection/create_sr_pairs.py" \
|
| 38 |
+
--input-dir "$PROJECT_DIR/data/processed/sr_4k/shards" \
|
| 39 |
+
--output-dir "$SR_PAIRS" 2>&1 | tail -5
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
# Train Stage 2: 1K→2K on GPU 0
|
| 43 |
+
echo "=== Starting SR Stage 2 (1K→2K) on GPU 0 ==="
|
| 44 |
+
export CUDA_VISIBLE_DEVICES=0
|
| 45 |
+
nohup python3 "$PROJECT_DIR/scripts/training/train_sr.py" \
|
| 46 |
+
--stage 2 \
|
| 47 |
+
--input-dir "$SR_PAIRS/1k_input" \
|
| 48 |
+
--target-dir "$SR_PAIRS/2k_target" \
|
| 49 |
+
--output-dir "$PROJECT_DIR/checkpoints/sr_stage2" \
|
| 50 |
+
--batch-size 4 \
|
| 51 |
+
--learning-rate 2e-4 \
|
| 52 |
+
--max-steps 200000 \
|
| 53 |
+
--save-steps 10000 \
|
| 54 |
+
--base-channels 64 \
|
| 55 |
+
--perceptual-weight 0.1 \
|
| 56 |
+
> "$PROJECT_DIR/logs/train_sr_stage2.log" 2>&1 &
|
| 57 |
+
echo "SR Stage 2 PID: $!"
|
| 58 |
+
|
| 59 |
+
# Train Stage 3: 2K→4K on GPU 1
|
| 60 |
+
echo "=== Starting SR Stage 3 (2K→4K) on GPU 1 ==="
|
| 61 |
+
export CUDA_VISIBLE_DEVICES=1
|
| 62 |
+
nohup python3 "$PROJECT_DIR/scripts/training/train_sr.py" \
|
| 63 |
+
--stage 3 \
|
| 64 |
+
--input-dir "$SR_PAIRS/2k_input" \
|
| 65 |
+
--target-dir "$SR_PAIRS/4k_target" \
|
| 66 |
+
--output-dir "$PROJECT_DIR/checkpoints/sr_stage3" \
|
| 67 |
+
--batch-size 2 \
|
| 68 |
+
--learning-rate 2e-4 \
|
| 69 |
+
--max-steps 200000 \
|
| 70 |
+
--save-steps 10000 \
|
| 71 |
+
--base-channels 64 \
|
| 72 |
+
--perceptual-weight 0.1 \
|
| 73 |
+
> "$PROJECT_DIR/logs/train_sr_stage3.log" 2>&1 &
|
| 74 |
+
echo "SR Stage 3 PID: $!"
|
| 75 |
+
|
| 76 |
+
echo ""
|
| 77 |
+
echo "=== All jobs started ==="
|
| 78 |
+
echo "Monitor:"
|
| 79 |
+
echo " tail -f $PROJECT_DIR/logs/train_sr_stage2.log"
|
| 80 |
+
echo " tail -f $PROJECT_DIR/logs/train_sr_stage3.log"
|
| 81 |
+
echo " tail -f $PROJECT_DIR/logs/backup.log"
|
| 82 |
+
echo " nvidia-smi"
|
scripts/training/train_flux_lora.py
CHANGED
|
@@ -1,22 +1,16 @@
|
|
| 1 |
"""
|
| 2 |
Fine-tune Flux model using LoRA on downloaded COYO dataset.
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
import argparse
|
| 6 |
-
import
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
import torch
|
| 10 |
import webdataset as wds
|
| 11 |
from PIL import Image
|
| 12 |
from torchvision import transforms
|
| 13 |
-
from diffusers import FluxPipeline, FluxTransformer2DModel
|
| 14 |
-
from diffusers.training_utils import compute_snr
|
| 15 |
from peft import LoraConfig, get_peft_model
|
| 16 |
-
from accelerate import Accelerator
|
| 17 |
-
from accelerate.utils import ProjectConfiguration
|
| 18 |
-
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
| 19 |
-
import wandb
|
| 20 |
|
| 21 |
|
| 22 |
def get_train_transforms(resolution=1024):
|
|
@@ -34,7 +28,7 @@ def collate_batch(samples):
|
|
| 34 |
return {"image": images, "caption": captions}
|
| 35 |
|
| 36 |
|
| 37 |
-
def create_webdataset(data_dir, resolution=1024, batch_size=
|
| 38 |
transform = get_train_transforms(resolution)
|
| 39 |
|
| 40 |
def preprocess(sample):
|
|
@@ -52,7 +46,7 @@ def create_webdataset(data_dir, resolution=1024, batch_size=4):
|
|
| 52 |
raise ValueError(f"No tar files found in {data_dir}")
|
| 53 |
|
| 54 |
dataset = (
|
| 55 |
-
wds.WebDataset([str(f) for f in tar_files], shardshuffle=True
|
| 56 |
.shuffle(1000)
|
| 57 |
.decode("pil")
|
| 58 |
.map(preprocess)
|
|
@@ -61,6 +55,13 @@ def create_webdataset(data_dir, resolution=1024, batch_size=4):
|
|
| 61 |
return dataset
|
| 62 |
|
| 63 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def main():
|
| 65 |
parser = argparse.ArgumentParser(description="Fine-tune Flux with LoRA")
|
| 66 |
parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
|
|
@@ -68,73 +69,83 @@ def main():
|
|
| 68 |
parser.add_argument("--output-dir", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/flux_lora"))
|
| 69 |
parser.add_argument("--resolution", type=int, default=1024)
|
| 70 |
parser.add_argument("--batch-size", type=int, default=1)
|
| 71 |
-
parser.add_argument("--gradient-accumulation", type=int, default=
|
| 72 |
parser.add_argument("--learning-rate", type=float, default=1e-4)
|
| 73 |
parser.add_argument("--lr-scheduler", default="cosine")
|
| 74 |
-
parser.add_argument("--lr-warmup-steps", type=int, default=
|
| 75 |
parser.add_argument("--max-train-steps", type=int, default=100000)
|
| 76 |
parser.add_argument("--save-steps", type=int, default=5000)
|
| 77 |
parser.add_argument("--lora-rank", type=int, default=128)
|
| 78 |
parser.add_argument("--lora-alpha", type=int, default=128)
|
| 79 |
-
parser.add_argument("--mixed-precision", default="bf16")
|
| 80 |
parser.add_argument("--seed", type=int, default=42)
|
| 81 |
-
parser.add_argument("--
|
| 82 |
-
parser.add_argument("--
|
|
|
|
| 83 |
args = parser.parse_args()
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
project_dir=str(args.output_dir),
|
| 88 |
-
logging_dir=str(args.output_dir / "logs"),
|
| 89 |
-
)
|
| 90 |
-
accelerator = Accelerator(
|
| 91 |
-
mixed_precision=args.mixed_precision,
|
| 92 |
-
gradient_accumulation_steps=args.gradient_accumulation,
|
| 93 |
-
project_config=project_config,
|
| 94 |
-
)
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
if args.use_wandb:
|
| 99 |
-
wandb.init(project=args.wandb_project, config=vars(args))
|
| 100 |
|
| 101 |
-
# Load
|
| 102 |
-
print(
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
)
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
tokenizer_2 = pipe.tokenizer_2
|
| 113 |
-
vae = pipe.vae
|
| 114 |
|
| 115 |
-
|
|
|
|
|
|
|
| 116 |
vae.requires_grad_(False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
text_encoder.requires_grad_(False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
text_encoder_2.requires_grad_(False)
|
| 119 |
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
lora_config = LoraConfig(
|
| 122 |
r=args.lora_rank,
|
| 123 |
lora_alpha=args.lora_alpha,
|
| 124 |
-
target_modules=["to_q", "to_k", "to_v", "to_out.0"
|
| 125 |
-
lora_dropout=0.
|
| 126 |
)
|
| 127 |
transformer = get_peft_model(transformer, lora_config)
|
|
|
|
| 128 |
transformer.print_trainable_parameters()
|
|
|
|
| 129 |
|
| 130 |
-
# Optimizer
|
| 131 |
optimizer = torch.optim.AdamW(
|
| 132 |
-
transformer.parameters(),
|
| 133 |
lr=args.learning_rate,
|
| 134 |
weight_decay=0.01,
|
| 135 |
)
|
| 136 |
|
| 137 |
-
# Learning rate scheduler
|
| 138 |
from diffusers.optimization import get_scheduler
|
| 139 |
lr_scheduler = get_scheduler(
|
| 140 |
args.lr_scheduler,
|
|
@@ -143,133 +154,117 @@ def main():
|
|
| 143 |
num_training_steps=args.max_train_steps,
|
| 144 |
)
|
| 145 |
|
| 146 |
-
# Dataset
|
| 147 |
print(f"Loading dataset from {args.data_dir}")
|
| 148 |
train_dataset = create_webdataset(args.data_dir, args.resolution, args.batch_size)
|
| 149 |
train_dataloader = torch.utils.data.DataLoader(
|
| 150 |
train_dataset, batch_size=None, num_workers=4, pin_memory=True
|
| 151 |
)
|
| 152 |
|
| 153 |
-
#
|
| 154 |
-
transformer, optimizer, lr_scheduler = accelerator.prepare(
|
| 155 |
-
transformer, optimizer, lr_scheduler
|
| 156 |
-
)
|
| 157 |
-
|
| 158 |
-
# Move frozen models to device
|
| 159 |
-
vae.to(accelerator.device, dtype=torch.bfloat16)
|
| 160 |
-
text_encoder.to(accelerator.device, dtype=torch.bfloat16)
|
| 161 |
-
text_encoder_2.to(accelerator.device, dtype=torch.bfloat16)
|
| 162 |
-
|
| 163 |
-
# Training loop
|
| 164 |
global_step = 0
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
-
|
| 168 |
-
# Pack 2x2 patches: (B, C, H, W) -> (B, H//2 * W//2, C*4)
|
| 169 |
-
b, c, h, w = latents.shape
|
| 170 |
-
latents = latents.reshape(b, c, h // 2, 2, w // 2, 2)
|
| 171 |
-
latents = latents.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)
|
| 172 |
-
return latents
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
images = batch["image"].to(accelerator.device, dtype=torch.bfloat16)
|
| 181 |
captions = batch["caption"]
|
| 182 |
|
| 183 |
-
# Encode
|
| 184 |
with torch.no_grad():
|
| 185 |
latents = vae.encode(images).latent_dist.sample()
|
| 186 |
-
latents = (latents -
|
| 187 |
|
| 188 |
-
|
| 189 |
-
with torch.no_grad():
|
| 190 |
-
# CLIP text encoder -> pooled embeddings
|
| 191 |
-
text_input_ids = tokenizer(
|
| 192 |
captions, padding="max_length", max_length=77,
|
| 193 |
truncation=True, return_tensors="pt"
|
| 194 |
-
).input_ids.to(
|
| 195 |
-
pooled_prompt_embeds = text_encoder(
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
captions, padding="max_length", max_length=512,
|
| 200 |
truncation=True, return_tensors="pt"
|
| 201 |
-
).input_ids.to(
|
| 202 |
-
encoder_hidden_states = text_encoder_2(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
-
# Flow matching
|
| 205 |
noise = torch.randn_like(latents)
|
| 206 |
-
t = torch.rand(latents.shape[0], device=
|
| 207 |
t_expand = t.view(-1, 1, 1, 1)
|
| 208 |
-
|
| 209 |
-
# Noisy latents via linear interpolation
|
| 210 |
noisy_latents = (1 - t_expand) * latents + t_expand * noise
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
target_latents = pack_latents(noise - latents)
|
| 215 |
|
| 216 |
-
|
| 217 |
-
timesteps = (t * 1000).to(dtype=noisy_latents.dtype)
|
| 218 |
|
| 219 |
-
|
| 220 |
-
b, seq_len, _ = noisy_latents.shape
|
| 221 |
-
img_ids = torch.zeros(seq_len, 3, device=accelerator.device, dtype=noisy_latents.dtype)
|
| 222 |
h_patches = w_patches = int(seq_len ** 0.5)
|
| 223 |
-
img_ids
|
| 224 |
-
img_ids[:,
|
| 225 |
-
img_ids =
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
global_step += 1
|
| 253 |
|
| 254 |
if global_step % 100 == 0:
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
wandb.log({"loss": loss.item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step})
|
| 259 |
|
| 260 |
if global_step % args.save_steps == 0:
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
accelerator.unwrap_model(transformer).save_pretrained(final_path)
|
| 270 |
-
print(f"Training complete! Final model saved to {final_path}")
|
| 271 |
-
if args.use_wandb:
|
| 272 |
-
wandb.finish()
|
| 273 |
|
| 274 |
|
| 275 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
Fine-tune Flux model using LoRA on downloaded COYO dataset.
|
| 3 |
+
Split approach: VAE+text encoders on cuda:0, transformer on cuda:1.
|
| 4 |
"""
|
| 5 |
import argparse
|
| 6 |
+
import gc
|
| 7 |
from pathlib import Path
|
| 8 |
|
| 9 |
import torch
|
| 10 |
import webdataset as wds
|
| 11 |
from PIL import Image
|
| 12 |
from torchvision import transforms
|
|
|
|
|
|
|
| 13 |
from peft import LoraConfig, get_peft_model
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
def get_train_transforms(resolution=1024):
|
|
|
|
| 28 |
return {"image": images, "caption": captions}
|
| 29 |
|
| 30 |
|
| 31 |
+
def create_webdataset(data_dir, resolution=1024, batch_size=1):
|
| 32 |
transform = get_train_transforms(resolution)
|
| 33 |
|
| 34 |
def preprocess(sample):
|
|
|
|
| 46 |
raise ValueError(f"No tar files found in {data_dir}")
|
| 47 |
|
| 48 |
dataset = (
|
| 49 |
+
wds.WebDataset([str(f) for f in tar_files], shardshuffle=True)
|
| 50 |
.shuffle(1000)
|
| 51 |
.decode("pil")
|
| 52 |
.map(preprocess)
|
|
|
|
| 55 |
return dataset
|
| 56 |
|
| 57 |
|
| 58 |
+
def pack_latents(latents):
|
| 59 |
+
b, c, h, w = latents.shape
|
| 60 |
+
latents = latents.reshape(b, c, h // 2, 2, w // 2, 2)
|
| 61 |
+
latents = latents.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)
|
| 62 |
+
return latents
|
| 63 |
+
|
| 64 |
+
|
| 65 |
def main():
|
| 66 |
parser = argparse.ArgumentParser(description="Fine-tune Flux with LoRA")
|
| 67 |
parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
|
|
|
|
| 69 |
parser.add_argument("--output-dir", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/flux_lora"))
|
| 70 |
parser.add_argument("--resolution", type=int, default=1024)
|
| 71 |
parser.add_argument("--batch-size", type=int, default=1)
|
| 72 |
+
parser.add_argument("--gradient-accumulation", type=int, default=8)
|
| 73 |
parser.add_argument("--learning-rate", type=float, default=1e-4)
|
| 74 |
parser.add_argument("--lr-scheduler", default="cosine")
|
| 75 |
+
parser.add_argument("--lr-warmup-steps", type=int, default=1000)
|
| 76 |
parser.add_argument("--max-train-steps", type=int, default=100000)
|
| 77 |
parser.add_argument("--save-steps", type=int, default=5000)
|
| 78 |
parser.add_argument("--lora-rank", type=int, default=128)
|
| 79 |
parser.add_argument("--lora-alpha", type=int, default=128)
|
|
|
|
| 80 |
parser.add_argument("--seed", type=int, default=42)
|
| 81 |
+
parser.add_argument("--gradient-checkpointing", action="store_true", default=True)
|
| 82 |
+
parser.add_argument("--encode-device", default="cuda:0")
|
| 83 |
+
parser.add_argument("--train-device", default="cuda:1")
|
| 84 |
args = parser.parse_args()
|
| 85 |
|
| 86 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 87 |
+
torch.manual_seed(args.seed)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
encode_device = torch.device(args.encode_device)
|
| 90 |
+
train_device = torch.device(args.train_device)
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
# --- Load tokenizers ---
|
| 93 |
+
print("Loading tokenizers...")
|
| 94 |
+
from transformers import CLIPTokenizer, T5TokenizerFast
|
| 95 |
+
tokenizer = CLIPTokenizer.from_pretrained(args.model_name, subfolder="tokenizer")
|
| 96 |
+
tokenizer_2 = T5TokenizerFast.from_pretrained(args.model_name, subfolder="tokenizer_2")
|
|
|
|
| 97 |
|
| 98 |
+
# --- Load VAE + text encoders on encode_device ---
|
| 99 |
+
print(f"Loading VAE + text encoders on {encode_device}...")
|
| 100 |
+
from diffusers import AutoencoderKL
|
| 101 |
+
from transformers import CLIPTextModel, T5EncoderModel
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
vae = AutoencoderKL.from_pretrained(
|
| 104 |
+
args.model_name, subfolder="vae", torch_dtype=torch.bfloat16
|
| 105 |
+
).to(encode_device).eval()
|
| 106 |
vae.requires_grad_(False)
|
| 107 |
+
|
| 108 |
+
text_encoder = CLIPTextModel.from_pretrained(
|
| 109 |
+
args.model_name, subfolder="text_encoder", torch_dtype=torch.bfloat16
|
| 110 |
+
).to(encode_device).eval()
|
| 111 |
text_encoder.requires_grad_(False)
|
| 112 |
+
|
| 113 |
+
text_encoder_2 = T5EncoderModel.from_pretrained(
|
| 114 |
+
args.model_name, subfolder="text_encoder_2", torch_dtype=torch.bfloat16
|
| 115 |
+
).to(encode_device).eval()
|
| 116 |
text_encoder_2.requires_grad_(False)
|
| 117 |
|
| 118 |
+
vae_shift = vae.config.shift_factor
|
| 119 |
+
vae_scale = vae.config.scaling_factor
|
| 120 |
+
|
| 121 |
+
# --- Load transformer on train_device ---
|
| 122 |
+
print(f"Loading Flux transformer on {train_device}...")
|
| 123 |
+
from diffusers import FluxTransformer2DModel
|
| 124 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 125 |
+
args.model_name, subfolder="transformer", torch_dtype=torch.bfloat16
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if args.gradient_checkpointing:
|
| 129 |
+
transformer.enable_gradient_checkpointing()
|
| 130 |
+
|
| 131 |
lora_config = LoraConfig(
|
| 132 |
r=args.lora_rank,
|
| 133 |
lora_alpha=args.lora_alpha,
|
| 134 |
+
target_modules=["to_q", "to_k", "to_v", "to_out.0"],
|
| 135 |
+
lora_dropout=0.0,
|
| 136 |
)
|
| 137 |
transformer = get_peft_model(transformer, lora_config)
|
| 138 |
+
transformer.to(train_device)
|
| 139 |
transformer.print_trainable_parameters()
|
| 140 |
+
transformer.train()
|
| 141 |
|
| 142 |
+
# --- Optimizer + scheduler ---
|
| 143 |
optimizer = torch.optim.AdamW(
|
| 144 |
+
[p for p in transformer.parameters() if p.requires_grad],
|
| 145 |
lr=args.learning_rate,
|
| 146 |
weight_decay=0.01,
|
| 147 |
)
|
| 148 |
|
|
|
|
| 149 |
from diffusers.optimization import get_scheduler
|
| 150 |
lr_scheduler = get_scheduler(
|
| 151 |
args.lr_scheduler,
|
|
|
|
| 154 |
num_training_steps=args.max_train_steps,
|
| 155 |
)
|
| 156 |
|
| 157 |
+
# --- Dataset ---
|
| 158 |
print(f"Loading dataset from {args.data_dir}")
|
| 159 |
train_dataset = create_webdataset(args.data_dir, args.resolution, args.batch_size)
|
| 160 |
train_dataloader = torch.utils.data.DataLoader(
|
| 161 |
train_dataset, batch_size=None, num_workers=4, pin_memory=True
|
| 162 |
)
|
| 163 |
|
| 164 |
+
# --- Training loop ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
global_step = 0
|
| 166 |
+
accum_loss = 0.0
|
| 167 |
+
print(f"\nStarting training for {args.max_train_steps} steps...")
|
| 168 |
+
print(f" Batch size: {args.batch_size}, Grad accum: {args.gradient_accumulation}")
|
| 169 |
+
print(f" Effective batch: {args.batch_size * args.gradient_accumulation}")
|
| 170 |
+
print(f" Encode device: {encode_device}, Train device: {train_device}")
|
| 171 |
|
| 172 |
+
scaler = None # bf16 doesn't need GradScaler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
while global_step < args.max_train_steps:
|
| 175 |
+
for batch in train_dataloader:
|
| 176 |
+
if global_step >= args.max_train_steps:
|
| 177 |
+
break
|
| 178 |
|
| 179 |
+
images = batch["image"].to(encode_device, dtype=torch.bfloat16)
|
|
|
|
| 180 |
captions = batch["caption"]
|
| 181 |
|
| 182 |
+
# Encode on encode_device
|
| 183 |
with torch.no_grad():
|
| 184 |
latents = vae.encode(images).latent_dist.sample()
|
| 185 |
+
latents = (latents - vae_shift) * vae_scale
|
| 186 |
|
| 187 |
+
text_ids = tokenizer(
|
|
|
|
|
|
|
|
|
|
| 188 |
captions, padding="max_length", max_length=77,
|
| 189 |
truncation=True, return_tensors="pt"
|
| 190 |
+
).input_ids.to(encode_device)
|
| 191 |
+
pooled_prompt_embeds = text_encoder(text_ids, output_hidden_states=False).pooler_output
|
| 192 |
|
| 193 |
+
text_ids_2 = tokenizer_2(
|
| 194 |
+
captions, padding="max_length", max_length=256,
|
|
|
|
| 195 |
truncation=True, return_tensors="pt"
|
| 196 |
+
).input_ids.to(encode_device)
|
| 197 |
+
encoder_hidden_states = text_encoder_2(text_ids_2)[0]
|
| 198 |
+
|
| 199 |
+
# Move to train device
|
| 200 |
+
latents = latents.to(train_device)
|
| 201 |
+
pooled_prompt_embeds = pooled_prompt_embeds.to(train_device)
|
| 202 |
+
encoder_hidden_states = encoder_hidden_states.to(train_device)
|
| 203 |
|
| 204 |
+
# Flow matching
|
| 205 |
noise = torch.randn_like(latents)
|
| 206 |
+
t = torch.rand(latents.shape[0], device=train_device, dtype=torch.bfloat16)
|
| 207 |
t_expand = t.view(-1, 1, 1, 1)
|
|
|
|
|
|
|
| 208 |
noisy_latents = (1 - t_expand) * latents + t_expand * noise
|
| 209 |
|
| 210 |
+
noisy_packed = pack_latents(noisy_latents)
|
| 211 |
+
target = pack_latents(noise - latents)
|
|
|
|
| 212 |
|
| 213 |
+
timesteps = (t * 1000).to(dtype=torch.bfloat16)
|
|
|
|
| 214 |
|
| 215 |
+
b, seq_len, _ = noisy_packed.shape
|
|
|
|
|
|
|
| 216 |
h_patches = w_patches = int(seq_len ** 0.5)
|
| 217 |
+
img_ids = torch.zeros(b, seq_len, 3, device=train_device, dtype=torch.bfloat16)
|
| 218 |
+
img_ids[:, :, 1] = torch.arange(h_patches, device=train_device).repeat_interleave(w_patches).unsqueeze(0).expand(b, -1).to(torch.bfloat16)
|
| 219 |
+
img_ids[:, :, 2] = torch.arange(w_patches, device=train_device).repeat(h_patches).unsqueeze(0).expand(b, -1).to(torch.bfloat16)
|
| 220 |
+
|
| 221 |
+
txt_ids = torch.zeros(b, encoder_hidden_states.shape[1], 3, device=train_device, dtype=torch.bfloat16)
|
| 222 |
+
|
| 223 |
+
# Forward
|
| 224 |
+
with torch.amp.autocast("cuda", dtype=torch.bfloat16):
|
| 225 |
+
model_pred = transformer(
|
| 226 |
+
hidden_states=noisy_packed,
|
| 227 |
+
timestep=timesteps / 1000,
|
| 228 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 229 |
+
pooled_projections=pooled_prompt_embeds,
|
| 230 |
+
img_ids=img_ids,
|
| 231 |
+
txt_ids=txt_ids,
|
| 232 |
+
return_dict=False,
|
| 233 |
+
)[0]
|
| 234 |
+
|
| 235 |
+
loss = torch.nn.functional.mse_loss(model_pred, target, reduction="mean")
|
| 236 |
+
loss = loss / args.gradient_accumulation
|
| 237 |
+
|
| 238 |
+
loss.backward()
|
| 239 |
+
accum_loss += loss.item()
|
| 240 |
+
|
| 241 |
+
if (global_step + 1) % args.gradient_accumulation == 0 or True:
|
| 242 |
+
# Check if we should step
|
| 243 |
+
step_count = (global_step + 1) % args.gradient_accumulation
|
| 244 |
+
if step_count == 0:
|
| 245 |
+
torch.nn.utils.clip_grad_norm_(
|
| 246 |
+
[p for p in transformer.parameters() if p.requires_grad], 1.0
|
| 247 |
+
)
|
| 248 |
+
optimizer.step()
|
| 249 |
+
lr_scheduler.step()
|
| 250 |
+
optimizer.zero_grad()
|
| 251 |
+
|
| 252 |
global_step += 1
|
| 253 |
|
| 254 |
if global_step % 100 == 0:
|
| 255 |
+
avg_loss = accum_loss / 100 * args.gradient_accumulation
|
| 256 |
+
print(f"Step {global_step}/{args.max_train_steps}, Loss: {avg_loss:.4f}, LR: {lr_scheduler.get_last_lr()[0]:.2e}")
|
| 257 |
+
accum_loss = 0.0
|
|
|
|
| 258 |
|
| 259 |
if global_step % args.save_steps == 0:
|
| 260 |
+
save_path = args.output_dir / f"checkpoint-{global_step}"
|
| 261 |
+
transformer.save_pretrained(save_path)
|
| 262 |
+
print(f"Saved checkpoint to {save_path}")
|
| 263 |
+
|
| 264 |
+
# Save final
|
| 265 |
+
final_path = args.output_dir / "final"
|
| 266 |
+
transformer.save_pretrained(final_path)
|
| 267 |
+
print(f"Training complete! Final model saved to {final_path}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
|
| 270 |
if __name__ == "__main__":
|