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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pre-compute VAE latents and text embeddings for Flux training.
|
| 3 |
+
Removes VAE/CLIP/T5 from GPU during training, saving ~10GB VRAM per GPU.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import io
|
| 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 tqdm import tqdm
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_transform(resolution=1024):
|
| 17 |
+
return transforms.Compose([
|
| 18 |
+
transforms.Resize(resolution, interpolation=transforms.InterpolationMode.LANCZOS),
|
| 19 |
+
transforms.CenterCrop(resolution),
|
| 20 |
+
transforms.ToTensor(),
|
| 21 |
+
transforms.Normalize([0.5], [0.5]),
|
| 22 |
+
])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
parser = argparse.ArgumentParser(description="Pre-compute embeddings for Flux training")
|
| 27 |
+
parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
|
| 28 |
+
parser.add_argument("--data-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/shards"))
|
| 29 |
+
parser.add_argument("--output-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings"))
|
| 30 |
+
parser.add_argument("--resolution", type=int, default=1024)
|
| 31 |
+
parser.add_argument("--batch-size", type=int, default=8)
|
| 32 |
+
parser.add_argument("--cache-dir", default="/data0/models")
|
| 33 |
+
parser.add_argument("--device", default="cuda:0")
|
| 34 |
+
args = parser.parse_args()
|
| 35 |
+
|
| 36 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
device = torch.device(args.device)
|
| 38 |
+
transform = get_transform(args.resolution)
|
| 39 |
+
|
| 40 |
+
# Load pipeline components
|
| 41 |
+
print("Loading Flux pipeline components...")
|
| 42 |
+
from diffusers import FluxPipeline
|
| 43 |
+
pipe = FluxPipeline.from_pretrained(
|
| 44 |
+
args.model_name,
|
| 45 |
+
torch_dtype=torch.bfloat16,
|
| 46 |
+
cache_dir=args.cache_dir,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
vae = pipe.vae.to(device).eval()
|
| 50 |
+
text_encoder = pipe.text_encoder.to(device).eval()
|
| 51 |
+
text_encoder_2 = pipe.text_encoder_2.to(device).eval()
|
| 52 |
+
tokenizer = pipe.tokenizer
|
| 53 |
+
tokenizer_2 = pipe.tokenizer_2
|
| 54 |
+
|
| 55 |
+
vae_shift = vae.config.shift_factor
|
| 56 |
+
vae_scale = vae.config.scaling_factor
|
| 57 |
+
|
| 58 |
+
# Find tar shards
|
| 59 |
+
tar_files = sorted(args.data_dir.glob("*.tar"))
|
| 60 |
+
if not tar_files:
|
| 61 |
+
raise ValueError(f"No tar files found in {args.data_dir}")
|
| 62 |
+
print(f"Found {len(tar_files)} shards")
|
| 63 |
+
|
| 64 |
+
def decode_sample(sample):
|
| 65 |
+
try:
|
| 66 |
+
img = sample["jpg"]
|
| 67 |
+
if isinstance(img, bytes):
|
| 68 |
+
img = Image.open(io.BytesIO(img)).convert("RGB")
|
| 69 |
+
caption = sample.get("txt", b"")
|
| 70 |
+
if isinstance(caption, bytes):
|
| 71 |
+
caption = caption.decode("utf-8")
|
| 72 |
+
return {"image": transform(img), "caption": caption, "key": sample["__key__"]}
|
| 73 |
+
except:
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
dataset = (
|
| 77 |
+
wds.WebDataset([str(f) for f in tar_files])
|
| 78 |
+
.decode("pil")
|
| 79 |
+
.map(decode_sample)
|
| 80 |
+
.select(lambda x: x is not None)
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
dataloader = torch.utils.data.DataLoader(
|
| 84 |
+
dataset, batch_size=None, num_workers=4, pin_memory=True
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Process in batches
|
| 88 |
+
batch_images = []
|
| 89 |
+
batch_captions = []
|
| 90 |
+
batch_keys = []
|
| 91 |
+
sample_idx = 0
|
| 92 |
+
shard_idx = 0
|
| 93 |
+
shard_data = []
|
| 94 |
+
samples_per_shard = 1000
|
| 95 |
+
|
| 96 |
+
print(f"Pre-computing embeddings (batch_size={args.batch_size})...")
|
| 97 |
+
|
| 98 |
+
def save_shard(shard_data, shard_idx):
|
| 99 |
+
shard_path = args.output_dir / f"shard-{shard_idx:06d}.pt"
|
| 100 |
+
torch.save(shard_data, shard_path)
|
| 101 |
+
return shard_idx + 1
|
| 102 |
+
|
| 103 |
+
def process_batch(images, captions, keys):
|
| 104 |
+
imgs = torch.stack(images).to(device, dtype=torch.bfloat16)
|
| 105 |
+
|
| 106 |
+
with torch.no_grad():
|
| 107 |
+
latents = vae.encode(imgs).latent_dist.sample()
|
| 108 |
+
latents = (latents - vae_shift) * vae_scale
|
| 109 |
+
|
| 110 |
+
# Pack latents: (B, C, H, W) -> (B, H/2*W/2, C*4)
|
| 111 |
+
b, c, h, w = latents.shape
|
| 112 |
+
packed = latents.view(b, c, h // 2, 2, w // 2, 2)
|
| 113 |
+
packed = packed.permute(0, 2, 4, 1, 3, 5).reshape(b, (h // 2) * (w // 2), c * 4)
|
| 114 |
+
|
| 115 |
+
# Text embeddings
|
| 116 |
+
text_ids = tokenizer(
|
| 117 |
+
captions, padding="max_length", max_length=77,
|
| 118 |
+
truncation=True, return_tensors="pt"
|
| 119 |
+
).input_ids.to(device)
|
| 120 |
+
pooled = text_encoder(text_ids, output_hidden_states=False).pooler_output
|
| 121 |
+
|
| 122 |
+
text_ids_2 = tokenizer_2(
|
| 123 |
+
captions, padding="max_length", max_length=256,
|
| 124 |
+
truncation=True, return_tensors="pt"
|
| 125 |
+
).input_ids.to(device)
|
| 126 |
+
hidden_states = text_encoder_2(text_ids_2)[0]
|
| 127 |
+
|
| 128 |
+
# Latent image IDs
|
| 129 |
+
latent_h, latent_w = h // 2, w // 2
|
| 130 |
+
img_ids = torch.zeros(latent_h, latent_w, 3, device=device)
|
| 131 |
+
img_ids[..., 1] = torch.arange(latent_h)[:, None].float()
|
| 132 |
+
img_ids[..., 2] = torch.arange(latent_w)[None, :].float()
|
| 133 |
+
img_ids = img_ids.reshape(latent_h * latent_w, 3)
|
| 134 |
+
|
| 135 |
+
# Text IDs
|
| 136 |
+
txt_ids = torch.zeros(hidden_states.shape[1], 3, device=device)
|
| 137 |
+
|
| 138 |
+
results = []
|
| 139 |
+
for i in range(b):
|
| 140 |
+
results.append({
|
| 141 |
+
"key": keys[i],
|
| 142 |
+
"packed_latents": packed[i].cpu(),
|
| 143 |
+
"pooled_prompt_embeds": pooled[i].cpu(),
|
| 144 |
+
"encoder_hidden_states": hidden_states[i].cpu(),
|
| 145 |
+
"img_ids": img_ids.cpu(),
|
| 146 |
+
"txt_ids": txt_ids.cpu(),
|
| 147 |
+
})
|
| 148 |
+
return results
|
| 149 |
+
|
| 150 |
+
total_processed = 0
|
| 151 |
+
for sample in dataloader:
|
| 152 |
+
batch_images.append(sample["image"])
|
| 153 |
+
batch_captions.append(sample["caption"])
|
| 154 |
+
batch_keys.append(sample["key"])
|
| 155 |
+
|
| 156 |
+
if len(batch_images) >= args.batch_size:
|
| 157 |
+
results = process_batch(batch_images, batch_captions, batch_keys)
|
| 158 |
+
shard_data.extend(results)
|
| 159 |
+
total_processed += len(results)
|
| 160 |
+
|
| 161 |
+
if len(shard_data) >= samples_per_shard:
|
| 162 |
+
shard_idx = save_shard(shard_data, shard_idx)
|
| 163 |
+
print(f" Saved shard {shard_idx - 1} ({total_processed} samples total)")
|
| 164 |
+
shard_data = []
|
| 165 |
+
|
| 166 |
+
batch_images = []
|
| 167 |
+
batch_captions = []
|
| 168 |
+
batch_keys = []
|
| 169 |
+
|
| 170 |
+
# Process remaining
|
| 171 |
+
if batch_images:
|
| 172 |
+
results = process_batch(batch_images, batch_captions, batch_keys)
|
| 173 |
+
shard_data.extend(results)
|
| 174 |
+
total_processed += len(results)
|
| 175 |
+
|
| 176 |
+
if shard_data:
|
| 177 |
+
shard_idx = save_shard(shard_data, shard_idx)
|
| 178 |
+
print(f" Saved shard {shard_idx - 1} ({total_processed} samples total)")
|
| 179 |
+
|
| 180 |
+
print(f"\nDone! {total_processed} samples saved to {args.output_dir} ({shard_idx} shards)")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
main()
|
scripts/training/run_train_flux_deepspeed.sh
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Flux LoRA Training with DeepSpeed ZeRO-3 on 2x H100 NVL
|
| 3 |
+
# Step 1: Pre-compute embeddings (one-time)
|
| 4 |
+
# Step 2: Train with both GPUs in parallel
|
| 5 |
+
#
|
| 6 |
+
# Usage: bash scripts/training/run_train_flux_deepspeed.sh
|
| 7 |
+
|
| 8 |
+
set -e
|
| 9 |
+
|
| 10 |
+
PROJECT_DIR="/home/adminuser/chungcat"
|
| 11 |
+
EMBEDDING_DIR="/data0/datasets/processed/flux_train/embeddings"
|
| 12 |
+
SHARD_DIR="/data0/datasets/processed/flux_train/shards"
|
| 13 |
+
|
| 14 |
+
export PYTHONPATH="$PROJECT_DIR:$PYTHONPATH"
|
| 15 |
+
export HF_HOME="/home/adminuser/.cache/huggingface"
|
| 16 |
+
export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True
|
| 17 |
+
|
| 18 |
+
# Step 1: Pre-compute embeddings if not done
|
| 19 |
+
if [ ! -d "$EMBEDDING_DIR" ] || [ $(ls "$EMBEDDING_DIR"/shard-*.pt 2>/dev/null | wc -l) -eq 0 ]; then
|
| 20 |
+
echo "=== Pre-computing embeddings ==="
|
| 21 |
+
python3 "$PROJECT_DIR/scripts/training/precompute_embeddings.py" \
|
| 22 |
+
--data-dir "$SHARD_DIR" \
|
| 23 |
+
--output-dir "$EMBEDDING_DIR" \
|
| 24 |
+
--batch-size 8 \
|
| 25 |
+
--device cuda:0
|
| 26 |
+
echo "=== Embeddings ready ==="
|
| 27 |
+
fi
|
| 28 |
+
|
| 29 |
+
# Step 2: Launch DeepSpeed training on 2 GPUs
|
| 30 |
+
echo "=== Starting DeepSpeed ZeRO-3 Training ==="
|
| 31 |
+
accelerate launch \
|
| 32 |
+
--config_file "$PROJECT_DIR/configs/accelerate_config.yaml" \
|
| 33 |
+
"$PROJECT_DIR/scripts/training/train_flux_deepspeed.py" \
|
| 34 |
+
--embedding-dir "$EMBEDDING_DIR" \
|
| 35 |
+
--output-dir "/data0/checkpoints/flux_lora_ds" \
|
| 36 |
+
--batch-size 4 \
|
| 37 |
+
--gradient-accumulation 4 \
|
| 38 |
+
--learning-rate 1e-4 \
|
| 39 |
+
--lr-warmup-steps 500 \
|
| 40 |
+
--max-train-steps 100000 \
|
| 41 |
+
--save-steps 5000 \
|
| 42 |
+
--lora-rank 128 \
|
| 43 |
+
--lora-alpha 128
|
scripts/training/train_flux_deepspeed.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Flux LoRA Training with DeepSpeed ZeRO-3.
|
| 3 |
+
Uses pre-computed embeddings for maximum GPU efficiency.
|
| 4 |
+
Both GPUs train the transformer in parallel.
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from torch.utils.data import Dataset, DataLoader
|
| 13 |
+
from accelerate import Accelerator
|
| 14 |
+
from diffusers import FluxTransformer2DModel
|
| 15 |
+
from diffusers.optimization import get_scheduler
|
| 16 |
+
from peft import LoraConfig, get_peft_model
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class EmbeddingDataset(Dataset):
|
| 20 |
+
"""Load pre-computed latents and text embeddings from .pt shards."""
|
| 21 |
+
|
| 22 |
+
def __init__(self, embedding_dir):
|
| 23 |
+
self.embedding_dir = Path(embedding_dir)
|
| 24 |
+
self.shard_files = sorted(self.embedding_dir.glob("shard-*.pt"))
|
| 25 |
+
if not self.shard_files:
|
| 26 |
+
raise ValueError(f"No shard files found in {embedding_dir}")
|
| 27 |
+
|
| 28 |
+
# Load index: count samples per shard
|
| 29 |
+
self.shard_lengths = []
|
| 30 |
+
self.cumulative = [0]
|
| 31 |
+
for sf in self.shard_files:
|
| 32 |
+
data = torch.load(sf, map_location="cpu", weights_only=False)
|
| 33 |
+
self.shard_lengths.append(len(data))
|
| 34 |
+
self.cumulative.append(self.cumulative[-1] + len(data))
|
| 35 |
+
del data
|
| 36 |
+
|
| 37 |
+
self.total_samples = self.cumulative[-1]
|
| 38 |
+
self._cache_shard_idx = -1
|
| 39 |
+
self._cache_data = None
|
| 40 |
+
print(f"EmbeddingDataset: {self.total_samples} samples in {len(self.shard_files)} shards")
|
| 41 |
+
|
| 42 |
+
def __len__(self):
|
| 43 |
+
return self.total_samples
|
| 44 |
+
|
| 45 |
+
def _get_shard_and_local_idx(self, idx):
|
| 46 |
+
for i in range(len(self.shard_files)):
|
| 47 |
+
if idx < self.cumulative[i + 1]:
|
| 48 |
+
return i, idx - self.cumulative[i]
|
| 49 |
+
raise IndexError(f"Index {idx} out of range")
|
| 50 |
+
|
| 51 |
+
def __getitem__(self, idx):
|
| 52 |
+
shard_idx, local_idx = self._get_shard_and_local_idx(idx)
|
| 53 |
+
|
| 54 |
+
if shard_idx != self._cache_shard_idx:
|
| 55 |
+
self._cache_data = torch.load(
|
| 56 |
+
self.shard_files[shard_idx], map_location="cpu", weights_only=False
|
| 57 |
+
)
|
| 58 |
+
self._cache_shard_idx = shard_idx
|
| 59 |
+
|
| 60 |
+
sample = self._cache_data[local_idx]
|
| 61 |
+
return {
|
| 62 |
+
"packed_latents": sample["packed_latents"],
|
| 63 |
+
"pooled_prompt_embeds": sample["pooled_prompt_embeds"],
|
| 64 |
+
"encoder_hidden_states": sample["encoder_hidden_states"],
|
| 65 |
+
"img_ids": sample["img_ids"],
|
| 66 |
+
"txt_ids": sample["txt_ids"],
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def main():
|
| 71 |
+
parser = argparse.ArgumentParser(description="Flux LoRA training with DeepSpeed ZeRO-3")
|
| 72 |
+
parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
|
| 73 |
+
parser.add_argument("--embedding-dir", type=Path, default=Path("/data0/datasets/processed/flux_train/embeddings"))
|
| 74 |
+
parser.add_argument("--output-dir", type=Path, default=Path("/data0/checkpoints/flux_lora_ds"))
|
| 75 |
+
parser.add_argument("--cache-dir", default="/data0/models")
|
| 76 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 77 |
+
parser.add_argument("--gradient-accumulation", type=int, default=4)
|
| 78 |
+
parser.add_argument("--learning-rate", type=float, default=1e-4)
|
| 79 |
+
parser.add_argument("--lr-scheduler", default="cosine")
|
| 80 |
+
parser.add_argument("--lr-warmup-steps", type=int, default=500)
|
| 81 |
+
parser.add_argument("--max-train-steps", type=int, default=100000)
|
| 82 |
+
parser.add_argument("--save-steps", type=int, default=5000)
|
| 83 |
+
parser.add_argument("--lora-rank", type=int, default=128)
|
| 84 |
+
parser.add_argument("--lora-alpha", type=int, default=128)
|
| 85 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 86 |
+
args = parser.parse_args()
|
| 87 |
+
|
| 88 |
+
accelerator = Accelerator(
|
| 89 |
+
mixed_precision="bf16",
|
| 90 |
+
gradient_accumulation_steps=args.gradient_accumulation,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
if accelerator.is_main_process:
|
| 94 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
torch.manual_seed(args.seed)
|
| 97 |
+
|
| 98 |
+
# Load only the transformer (no VAE/CLIP/T5 needed)
|
| 99 |
+
if accelerator.is_main_process:
|
| 100 |
+
print("Loading Flux Transformer...")
|
| 101 |
+
transformer = FluxTransformer2DModel.from_pretrained(
|
| 102 |
+
args.model_name,
|
| 103 |
+
subfolder="transformer",
|
| 104 |
+
torch_dtype=torch.bfloat16,
|
| 105 |
+
cache_dir=args.cache_dir,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
transformer.enable_gradient_checkpointing()
|
| 109 |
+
|
| 110 |
+
lora_config = LoraConfig(
|
| 111 |
+
r=args.lora_rank,
|
| 112 |
+
lora_alpha=args.lora_alpha,
|
| 113 |
+
target_modules=["to_q", "to_k", "to_v", "to_out.0"],
|
| 114 |
+
lora_dropout=0.0,
|
| 115 |
+
)
|
| 116 |
+
transformer = get_peft_model(transformer, lora_config)
|
| 117 |
+
|
| 118 |
+
if accelerator.is_main_process:
|
| 119 |
+
transformer.print_trainable_parameters()
|
| 120 |
+
|
| 121 |
+
optimizer = torch.optim.AdamW(
|
| 122 |
+
[p for p in transformer.parameters() if p.requires_grad],
|
| 123 |
+
lr=args.learning_rate,
|
| 124 |
+
weight_decay=0.01,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
lr_scheduler = get_scheduler(
|
| 128 |
+
args.lr_scheduler,
|
| 129 |
+
optimizer=optimizer,
|
| 130 |
+
num_warmup_steps=args.lr_warmup_steps,
|
| 131 |
+
num_training_steps=args.max_train_steps,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
# Dataset
|
| 135 |
+
dataset = EmbeddingDataset(args.embedding_dir)
|
| 136 |
+
dataloader = DataLoader(
|
| 137 |
+
dataset,
|
| 138 |
+
batch_size=args.batch_size,
|
| 139 |
+
shuffle=True,
|
| 140 |
+
num_workers=4,
|
| 141 |
+
pin_memory=True,
|
| 142 |
+
drop_last=True,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# Prepare with Accelerator (handles DeepSpeed wrapping)
|
| 146 |
+
transformer, optimizer, dataloader, lr_scheduler = accelerator.prepare(
|
| 147 |
+
transformer, optimizer, dataloader, lr_scheduler
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
# Training loop
|
| 151 |
+
global_step = 0
|
| 152 |
+
t0 = time.time()
|
| 153 |
+
|
| 154 |
+
if accelerator.is_main_process:
|
| 155 |
+
print(f"\nStarting training...")
|
| 156 |
+
print(f" Batch size/GPU: {args.batch_size}")
|
| 157 |
+
print(f" Num GPUs: {accelerator.num_processes}")
|
| 158 |
+
print(f" Grad accumulation: {args.gradient_accumulation}")
|
| 159 |
+
print(f" Effective batch: {args.batch_size * accelerator.num_processes * args.gradient_accumulation}")
|
| 160 |
+
print(f" Max steps: {args.max_train_steps}")
|
| 161 |
+
print(f" Dataset: {len(dataset)} samples")
|
| 162 |
+
|
| 163 |
+
transformer.train()
|
| 164 |
+
|
| 165 |
+
while global_step < args.max_train_steps:
|
| 166 |
+
for batch in dataloader:
|
| 167 |
+
if global_step >= args.max_train_steps:
|
| 168 |
+
break
|
| 169 |
+
|
| 170 |
+
with accelerator.accumulate(transformer):
|
| 171 |
+
packed_latents = batch["packed_latents"].to(dtype=torch.bfloat16)
|
| 172 |
+
pooled_prompt_embeds = batch["pooled_prompt_embeds"].to(dtype=torch.bfloat16)
|
| 173 |
+
encoder_hidden_states = batch["encoder_hidden_states"].to(dtype=torch.bfloat16)
|
| 174 |
+
img_ids = batch["img_ids"][0] # same for all samples at same resolution
|
| 175 |
+
txt_ids = batch["txt_ids"][0]
|
| 176 |
+
|
| 177 |
+
bs = packed_latents.shape[0]
|
| 178 |
+
|
| 179 |
+
# Flow matching: sample timestep, create noisy latents
|
| 180 |
+
noise = torch.randn_like(packed_latents)
|
| 181 |
+
t = torch.rand(bs, device=packed_latents.device, dtype=torch.bfloat16)
|
| 182 |
+
t_expand = t.view(-1, 1, 1)
|
| 183 |
+
|
| 184 |
+
noisy_latents = (1 - t_expand) * packed_latents + t_expand * noise
|
| 185 |
+
timesteps = (t * 1000).to(dtype=packed_latents.dtype)
|
| 186 |
+
|
| 187 |
+
# Forward pass
|
| 188 |
+
model_pred = transformer(
|
| 189 |
+
hidden_states=noisy_latents,
|
| 190 |
+
timestep=timesteps,
|
| 191 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 192 |
+
pooled_projections=pooled_prompt_embeds,
|
| 193 |
+
img_ids=img_ids,
|
| 194 |
+
txt_ids=txt_ids,
|
| 195 |
+
return_dict=False,
|
| 196 |
+
)[0]
|
| 197 |
+
|
| 198 |
+
# Target: velocity (noise - signal)
|
| 199 |
+
target = noise - packed_latents
|
| 200 |
+
loss = F.mse_loss(model_pred, target)
|
| 201 |
+
|
| 202 |
+
accelerator.backward(loss)
|
| 203 |
+
|
| 204 |
+
if accelerator.sync_gradients:
|
| 205 |
+
accelerator.clip_grad_norm_(
|
| 206 |
+
[p for p in transformer.parameters() if p.requires_grad], 1.0
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
optimizer.step()
|
| 210 |
+
lr_scheduler.step()
|
| 211 |
+
optimizer.zero_grad()
|
| 212 |
+
|
| 213 |
+
if accelerator.sync_gradients:
|
| 214 |
+
global_step += 1
|
| 215 |
+
|
| 216 |
+
if global_step % 100 == 0 and accelerator.is_main_process:
|
| 217 |
+
elapsed = time.time() - t0
|
| 218 |
+
steps_per_sec = global_step / elapsed
|
| 219 |
+
eta_hours = (args.max_train_steps - global_step) / steps_per_sec / 3600
|
| 220 |
+
print(
|
| 221 |
+
f"Step {global_step}/{args.max_train_steps} | "
|
| 222 |
+
f"Loss: {loss.item():.4f} | "
|
| 223 |
+
f"LR: {lr_scheduler.get_last_lr()[0]:.2e} | "
|
| 224 |
+
f"Speed: {steps_per_sec:.2f} steps/s | "
|
| 225 |
+
f"ETA: {eta_hours:.1f}h"
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
if global_step % args.save_steps == 0 and accelerator.is_main_process:
|
| 229 |
+
save_path = args.output_dir / f"checkpoint-{global_step}"
|
| 230 |
+
save_path.mkdir(parents=True, exist_ok=True)
|
| 231 |
+
unwrapped = accelerator.unwrap_model(transformer)
|
| 232 |
+
unwrapped.save_pretrained(save_path)
|
| 233 |
+
print(f"Saved checkpoint: {save_path}")
|
| 234 |
+
|
| 235 |
+
# Save final
|
| 236 |
+
if accelerator.is_main_process:
|
| 237 |
+
final_path = args.output_dir / "final"
|
| 238 |
+
final_path.mkdir(parents=True, exist_ok=True)
|
| 239 |
+
unwrapped = accelerator.unwrap_model(transformer)
|
| 240 |
+
unwrapped.save_pretrained(final_path)
|
| 241 |
+
total_time = (time.time() - t0) / 3600
|
| 242 |
+
print(f"\nTraining complete! Saved to {final_path}")
|
| 243 |
+
print(f"Total time: {total_time:.1f} hours")
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if __name__ == "__main__":
|
| 247 |
+
main()
|