Upload folder using huggingface_hub
Browse files- scripts/backup.py +259 -0
- scripts/bootstrap.sh +72 -0
- scripts/data_collection/caption_opus.py +136 -0
- scripts/data_collection/crawl_4k.py +115 -0
- scripts/data_collection/crawl_pexels.py +104 -0
- scripts/data_collection/crawl_unsplash.py +122 -0
- scripts/data_collection/create_sr_pairs.py +124 -0
- scripts/data_collection/download_coyo_images.py +72 -0
- scripts/data_collection/download_laion.py +146 -0
- scripts/data_collection/filter_coyo.py +116 -0
- scripts/data_collection/prepare_webdataset.py +68 -0
- scripts/serving/api_server.py +136 -0
- scripts/serving/inference.py +134 -0
- scripts/training/run_train_flux.sh +25 -0
- scripts/training/run_train_sr_stage2.sh +16 -0
- scripts/training/run_train_sr_stage3.sh +16 -0
- scripts/training/train_flux_lora.py +240 -0
- scripts/training/train_sr.py +315 -0
scripts/backup.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Auto-backup system: sync checkpoints, data, and configs to HuggingFace Hub.
|
| 3 |
+
Supports resume training from any new VPS.
|
| 4 |
+
|
| 5 |
+
Setup:
|
| 6 |
+
1. huggingface-cli login
|
| 7 |
+
2. python3 backup.py --init (tạo repos trên HF)
|
| 8 |
+
3. python3 backup.py --backup (push lên HF)
|
| 9 |
+
4. python3 backup.py --restore (pull về VPS mới)
|
| 10 |
+
"""
|
| 11 |
+
import argparse
|
| 12 |
+
import subprocess
|
| 13 |
+
import time
|
| 14 |
+
import threading
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from huggingface_hub import HfApi, create_repo, snapshot_download, upload_folder, upload_file
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
PROJECT_DIR = Path("/home/adminuser/chungcat")
|
| 20 |
+
HF_ORG = None # Set to your HF username or org
|
| 21 |
+
|
| 22 |
+
REPOS = {
|
| 23 |
+
"checkpoints": "{user}/4k-image-model-checkpoints",
|
| 24 |
+
"data_meta": "{user}/4k-image-model-data",
|
| 25 |
+
"scripts": "{user}/4k-image-model-scripts",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
BACKUP_PATHS = {
|
| 29 |
+
"checkpoints": [
|
| 30 |
+
PROJECT_DIR / "checkpoints",
|
| 31 |
+
],
|
| 32 |
+
"data_meta": [
|
| 33 |
+
PROJECT_DIR / "data" / "raw" / "coyo_filtered",
|
| 34 |
+
PROJECT_DIR / "configs",
|
| 35 |
+
],
|
| 36 |
+
"scripts": [
|
| 37 |
+
PROJECT_DIR / "scripts",
|
| 38 |
+
PROJECT_DIR / "configs",
|
| 39 |
+
PROJECT_DIR / "PLAN.md",
|
| 40 |
+
],
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_hf_user():
|
| 45 |
+
api = HfApi()
|
| 46 |
+
info = api.whoami()
|
| 47 |
+
return info["name"]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def init_repos(user):
|
| 51 |
+
"""Create HF repos if they don't exist."""
|
| 52 |
+
api = HfApi()
|
| 53 |
+
for key, repo_template in REPOS.items():
|
| 54 |
+
repo_id = repo_template.format(user=user)
|
| 55 |
+
try:
|
| 56 |
+
create_repo(repo_id, repo_type="model" if key == "checkpoints" else "dataset", exist_ok=True)
|
| 57 |
+
print(f" Repo ready: {repo_id}")
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f" Error creating {repo_id}: {e}")
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def backup_checkpoints(user):
|
| 63 |
+
"""Upload latest checkpoint to HF."""
|
| 64 |
+
api = HfApi()
|
| 65 |
+
repo_id = REPOS["checkpoints"].format(user=user)
|
| 66 |
+
ckpt_dir = PROJECT_DIR / "checkpoints"
|
| 67 |
+
|
| 68 |
+
if not ckpt_dir.exists():
|
| 69 |
+
print(" No checkpoints to backup")
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
# Find all checkpoint dirs
|
| 73 |
+
for model_dir in ckpt_dir.iterdir():
|
| 74 |
+
if not model_dir.is_dir():
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
# Upload latest checkpoint only (save bandwidth)
|
| 78 |
+
checkpoints = sorted(model_dir.glob("checkpoint-*"), key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0)
|
| 79 |
+
final = model_dir / "final"
|
| 80 |
+
|
| 81 |
+
to_upload = None
|
| 82 |
+
if final.exists():
|
| 83 |
+
to_upload = final
|
| 84 |
+
elif checkpoints:
|
| 85 |
+
to_upload = checkpoints[-1]
|
| 86 |
+
|
| 87 |
+
if to_upload:
|
| 88 |
+
path_in_repo = f"{model_dir.name}/{to_upload.name}"
|
| 89 |
+
print(f" Uploading {to_upload} → {repo_id}/{path_in_repo}")
|
| 90 |
+
upload_folder(
|
| 91 |
+
folder_path=str(to_upload),
|
| 92 |
+
repo_id=repo_id,
|
| 93 |
+
path_in_repo=path_in_repo,
|
| 94 |
+
repo_type="model",
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def backup_data_meta(user):
|
| 99 |
+
"""Upload filtered parquets and configs."""
|
| 100 |
+
api = HfApi()
|
| 101 |
+
repo_id = REPOS["data_meta"].format(user=user)
|
| 102 |
+
|
| 103 |
+
for path in BACKUP_PATHS["data_meta"]:
|
| 104 |
+
if not path.exists():
|
| 105 |
+
continue
|
| 106 |
+
rel_path = path.relative_to(PROJECT_DIR)
|
| 107 |
+
print(f" Uploading {rel_path} → {repo_id}")
|
| 108 |
+
upload_folder(
|
| 109 |
+
folder_path=str(path),
|
| 110 |
+
repo_id=repo_id,
|
| 111 |
+
path_in_repo=str(rel_path),
|
| 112 |
+
repo_type="dataset",
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def backup_scripts(user):
|
| 117 |
+
"""Upload all scripts and configs."""
|
| 118 |
+
api = HfApi()
|
| 119 |
+
repo_id = REPOS["scripts"].format(user=user)
|
| 120 |
+
|
| 121 |
+
for path in BACKUP_PATHS["scripts"]:
|
| 122 |
+
if not path.exists():
|
| 123 |
+
continue
|
| 124 |
+
rel_path = path.relative_to(PROJECT_DIR)
|
| 125 |
+
if path.is_file():
|
| 126 |
+
print(f" Uploading {rel_path}")
|
| 127 |
+
upload_file(
|
| 128 |
+
path_or_fileobj=str(path),
|
| 129 |
+
repo_id=repo_id,
|
| 130 |
+
path_in_repo=str(rel_path),
|
| 131 |
+
repo_type="dataset",
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
print(f" Uploading {rel_path}/")
|
| 135 |
+
upload_folder(
|
| 136 |
+
folder_path=str(path),
|
| 137 |
+
repo_id=repo_id,
|
| 138 |
+
path_in_repo=str(rel_path),
|
| 139 |
+
repo_type="dataset",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def backup_all(user):
|
| 144 |
+
"""Full backup."""
|
| 145 |
+
print("\n=== Backing up scripts ===")
|
| 146 |
+
backup_scripts(user)
|
| 147 |
+
print("\n=== Backing up data metadata ===")
|
| 148 |
+
backup_data_meta(user)
|
| 149 |
+
print("\n=== Backing up checkpoints ===")
|
| 150 |
+
backup_checkpoints(user)
|
| 151 |
+
print("\n=== Backup complete! ===")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def restore(user):
|
| 155 |
+
"""Restore everything from HF to a new VPS."""
|
| 156 |
+
print("\n=== Restoring from HuggingFace ===")
|
| 157 |
+
|
| 158 |
+
# Restore scripts
|
| 159 |
+
repo_id = REPOS["scripts"].format(user=user)
|
| 160 |
+
print(f"\n Restoring scripts from {repo_id}...")
|
| 161 |
+
try:
|
| 162 |
+
snapshot_download(
|
| 163 |
+
repo_id=repo_id,
|
| 164 |
+
repo_type="dataset",
|
| 165 |
+
local_dir=str(PROJECT_DIR),
|
| 166 |
+
)
|
| 167 |
+
except Exception as e:
|
| 168 |
+
print(f" Warning: {e}")
|
| 169 |
+
|
| 170 |
+
# Restore data metadata
|
| 171 |
+
repo_id = REPOS["data_meta"].format(user=user)
|
| 172 |
+
print(f"\n Restoring data metadata from {repo_id}...")
|
| 173 |
+
try:
|
| 174 |
+
snapshot_download(
|
| 175 |
+
repo_id=repo_id,
|
| 176 |
+
repo_type="dataset",
|
| 177 |
+
local_dir=str(PROJECT_DIR),
|
| 178 |
+
)
|
| 179 |
+
except Exception as e:
|
| 180 |
+
print(f" Warning: {e}")
|
| 181 |
+
|
| 182 |
+
# Restore checkpoints
|
| 183 |
+
repo_id = REPOS["checkpoints"].format(user=user)
|
| 184 |
+
print(f"\n Restoring checkpoints from {repo_id}...")
|
| 185 |
+
try:
|
| 186 |
+
snapshot_download(
|
| 187 |
+
repo_id=repo_id,
|
| 188 |
+
repo_type="model",
|
| 189 |
+
local_dir=str(PROJECT_DIR / "checkpoints"),
|
| 190 |
+
)
|
| 191 |
+
except Exception as e:
|
| 192 |
+
print(f" Warning: {e}")
|
| 193 |
+
|
| 194 |
+
print("\n=== Restore complete! ===")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class AutoBackup:
|
| 198 |
+
"""Background thread that backs up every N minutes."""
|
| 199 |
+
|
| 200 |
+
def __init__(self, user, interval_minutes=30):
|
| 201 |
+
self.user = user
|
| 202 |
+
self.interval = interval_minutes * 60
|
| 203 |
+
self.running = False
|
| 204 |
+
self.thread = None
|
| 205 |
+
|
| 206 |
+
def start(self):
|
| 207 |
+
self.running = True
|
| 208 |
+
self.thread = threading.Thread(target=self._loop, daemon=True)
|
| 209 |
+
self.thread.start()
|
| 210 |
+
print(f"Auto-backup started (every {self.interval // 60} minutes)")
|
| 211 |
+
|
| 212 |
+
def stop(self):
|
| 213 |
+
self.running = False
|
| 214 |
+
if self.thread:
|
| 215 |
+
self.thread.join()
|
| 216 |
+
|
| 217 |
+
def _loop(self):
|
| 218 |
+
while self.running:
|
| 219 |
+
time.sleep(self.interval)
|
| 220 |
+
if not self.running:
|
| 221 |
+
break
|
| 222 |
+
try:
|
| 223 |
+
print(f"\n[Auto-backup] Starting backup at {time.strftime('%H:%M:%S')}...")
|
| 224 |
+
backup_all(self.user)
|
| 225 |
+
print(f"[Auto-backup] Done at {time.strftime('%H:%M:%S')}")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
print(f"[Auto-backup] Error: {e}")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
if __name__ == "__main__":
|
| 231 |
+
parser = argparse.ArgumentParser(description="Backup/restore to HuggingFace Hub")
|
| 232 |
+
parser.add_argument("--init", action="store_true", help="Create HF repos")
|
| 233 |
+
parser.add_argument("--backup", action="store_true", help="Backup to HF")
|
| 234 |
+
parser.add_argument("--restore", action="store_true", help="Restore from HF")
|
| 235 |
+
parser.add_argument("--auto", action="store_true", help="Start auto-backup daemon")
|
| 236 |
+
parser.add_argument("--interval", type=int, default=30, help="Auto-backup interval (minutes)")
|
| 237 |
+
parser.add_argument("--user", default=None, help="HF username (auto-detected if logged in)")
|
| 238 |
+
args = parser.parse_args()
|
| 239 |
+
|
| 240 |
+
user = args.user or get_hf_user()
|
| 241 |
+
print(f"HuggingFace user: {user}")
|
| 242 |
+
|
| 243 |
+
if args.init:
|
| 244 |
+
print("\nInitializing repos...")
|
| 245 |
+
init_repos(user)
|
| 246 |
+
elif args.backup:
|
| 247 |
+
backup_all(user)
|
| 248 |
+
elif args.restore:
|
| 249 |
+
restore(user)
|
| 250 |
+
elif args.auto:
|
| 251 |
+
ab = AutoBackup(user, args.interval)
|
| 252 |
+
ab.start()
|
| 253 |
+
try:
|
| 254 |
+
while True:
|
| 255 |
+
time.sleep(1)
|
| 256 |
+
except KeyboardInterrupt:
|
| 257 |
+
ab.stop()
|
| 258 |
+
else:
|
| 259 |
+
print("Specify --init, --backup, --restore, or --auto")
|
scripts/bootstrap.sh
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
"""
|
| 3 |
+
Bootstrap script for new VPS.
|
| 4 |
+
Run this on a fresh VPS to restore everything and resume training.
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
curl -sSL <raw_url_of_this_script> | bash
|
| 8 |
+
OR
|
| 9 |
+
bash scripts/bootstrap.sh <hf_username>
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
set -e
|
| 13 |
+
|
| 14 |
+
HF_USER=${1:-""}
|
| 15 |
+
PROJECT_DIR="/home/adminuser/chungcat"
|
| 16 |
+
|
| 17 |
+
echo "=== 4K Image Model - VPS Bootstrap ==="
|
| 18 |
+
echo ""
|
| 19 |
+
|
| 20 |
+
# 1. Install system deps
|
| 21 |
+
echo "[1/6] Installing system dependencies..."
|
| 22 |
+
pip3 install torch torchvision torchaudio 2>/dev/null | tail -1
|
| 23 |
+
pip3 install diffusers transformers accelerate deepspeed bitsandbytes peft \
|
| 24 |
+
datasets webdataset img2dataset wandb safetensors xformers \
|
| 25 |
+
opencv-python-headless tqdm anthropic huggingface_hub fastapi uvicorn 2>/dev/null | tail -1
|
| 26 |
+
|
| 27 |
+
# 2. Login to HuggingFace
|
| 28 |
+
echo "[2/6] Checking HuggingFace login..."
|
| 29 |
+
if ! huggingface-cli whoami &>/dev/null; then
|
| 30 |
+
echo " Please login to HuggingFace:"
|
| 31 |
+
huggingface-cli login
|
| 32 |
+
fi
|
| 33 |
+
|
| 34 |
+
if [ -z "$HF_USER" ]; then
|
| 35 |
+
HF_USER=$(python3 -c "from huggingface_hub import HfApi; print(HfApi().whoami()['name'])")
|
| 36 |
+
fi
|
| 37 |
+
echo " User: $HF_USER"
|
| 38 |
+
|
| 39 |
+
# 3. Create project structure
|
| 40 |
+
echo "[3/6] Creating project structure..."
|
| 41 |
+
mkdir -p $PROJECT_DIR/{data/{raw,processed,captions},models,scripts,configs,checkpoints,logs,outputs}
|
| 42 |
+
|
| 43 |
+
# 4. Restore from HuggingFace
|
| 44 |
+
echo "[4/6] Restoring from HuggingFace..."
|
| 45 |
+
python3 $PROJECT_DIR/scripts/backup.py --restore --user $HF_USER 2>/dev/null || {
|
| 46 |
+
echo " No backup found or restore failed. Starting fresh."
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# 5. Verify GPU
|
| 50 |
+
echo "[5/6] Verifying GPU..."
|
| 51 |
+
python3 -c "
|
| 52 |
+
import torch
|
| 53 |
+
print(f' PyTorch: {torch.__version__}')
|
| 54 |
+
print(f' CUDA: {torch.version.cuda}')
|
| 55 |
+
print(f' GPUs: {torch.cuda.device_count()}')
|
| 56 |
+
for i in range(torch.cuda.device_count()):
|
| 57 |
+
print(f' GPU {i}: {torch.cuda.get_device_name(i)} ({torch.cuda.get_device_properties(i).total_memory/1024**3:.0f}GB)')
|
| 58 |
+
"
|
| 59 |
+
|
| 60 |
+
# 6. Start auto-backup
|
| 61 |
+
echo "[6/6] Starting auto-backup (every 30 min)..."
|
| 62 |
+
nohup python3 $PROJECT_DIR/scripts/backup.py --auto --interval 30 --user $HF_USER > $PROJECT_DIR/logs/backup.log 2>&1 &
|
| 63 |
+
echo " Auto-backup PID: $!"
|
| 64 |
+
|
| 65 |
+
echo ""
|
| 66 |
+
echo "=== Bootstrap complete! ==="
|
| 67 |
+
echo ""
|
| 68 |
+
echo "Next steps:"
|
| 69 |
+
echo " - Check data: du -sh $PROJECT_DIR/data/"
|
| 70 |
+
echo " - Resume training: bash $PROJECT_DIR/scripts/training/run_train_flux.sh"
|
| 71 |
+
echo " - Manual backup: python3 $PROJECT_DIR/scripts/backup.py --backup"
|
| 72 |
+
echo ""
|
scripts/data_collection/caption_opus.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Caption images using Anthropic Claude Opus 4.6 API.
|
| 3 |
+
Generates detailed descriptions for fine-tuning Flux.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import base64
|
| 8 |
+
import argparse
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 12 |
+
|
| 13 |
+
import anthropic
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
INPUT_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash")
|
| 17 |
+
OUTPUT_DIR = Path("/home/adminuser/chungcat/data/captions")
|
| 18 |
+
|
| 19 |
+
CAPTION_PROMPT = """Describe this image in detail for an AI image generation model. Include:
|
| 20 |
+
- Main subject and composition
|
| 21 |
+
- Colors, lighting, mood
|
| 22 |
+
- Style (photographic, artistic, etc.)
|
| 23 |
+
- Important details and textures
|
| 24 |
+
- Background elements
|
| 25 |
+
|
| 26 |
+
Write a single detailed paragraph, 2-4 sentences. Be specific and descriptive."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def encode_image(image_path):
|
| 30 |
+
with open(image_path, "rb") as f:
|
| 31 |
+
return base64.standard_b64encode(f.read()).decode("utf-8")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def caption_image(client, image_path, model="claude-opus-4-6-20250219"):
|
| 35 |
+
img_data = encode_image(image_path)
|
| 36 |
+
suffix = image_path.suffix.lower()
|
| 37 |
+
media_type = "image/jpeg" if suffix in [".jpg", ".jpeg"] else "image/png"
|
| 38 |
+
|
| 39 |
+
response = client.messages.create(
|
| 40 |
+
model=model,
|
| 41 |
+
max_tokens=300,
|
| 42 |
+
messages=[
|
| 43 |
+
{
|
| 44 |
+
"role": "user",
|
| 45 |
+
"content": [
|
| 46 |
+
{
|
| 47 |
+
"type": "image",
|
| 48 |
+
"source": {
|
| 49 |
+
"type": "base64",
|
| 50 |
+
"media_type": media_type,
|
| 51 |
+
"data": img_data,
|
| 52 |
+
},
|
| 53 |
+
},
|
| 54 |
+
{"type": "text", "text": CAPTION_PROMPT},
|
| 55 |
+
],
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
)
|
| 59 |
+
return response.content[0].text
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def process_batch(client, images, output_dir, model, max_retries=3):
|
| 63 |
+
results = []
|
| 64 |
+
for img_path in images:
|
| 65 |
+
output_path = output_dir / f"{img_path.stem}.json"
|
| 66 |
+
if output_path.exists():
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
for attempt in range(max_retries):
|
| 70 |
+
try:
|
| 71 |
+
caption = caption_image(client, img_path, model)
|
| 72 |
+
result = {
|
| 73 |
+
"image": str(img_path),
|
| 74 |
+
"caption": caption,
|
| 75 |
+
"filename": img_path.name,
|
| 76 |
+
}
|
| 77 |
+
output_path.write_text(json.dumps(result, ensure_ascii=False))
|
| 78 |
+
results.append(result)
|
| 79 |
+
break
|
| 80 |
+
except anthropic.RateLimitError:
|
| 81 |
+
time.sleep(2 ** attempt)
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"Error {img_path.name}: {e}")
|
| 84 |
+
if attempt == max_retries - 1:
|
| 85 |
+
print(f" Skipping after {max_retries} retries")
|
| 86 |
+
time.sleep(1)
|
| 87 |
+
|
| 88 |
+
return results
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def main():
|
| 92 |
+
parser = argparse.ArgumentParser(description="Caption images with Claude Opus")
|
| 93 |
+
parser.add_argument("--input-dir", type=Path, default=INPUT_DIR)
|
| 94 |
+
parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
|
| 95 |
+
parser.add_argument("--model", default="claude-opus-4-6-20250219")
|
| 96 |
+
parser.add_argument("--batch-size", type=int, default=10)
|
| 97 |
+
parser.add_argument("--workers", type=int, default=5)
|
| 98 |
+
parser.add_argument("--max-images", type=int, default=None)
|
| 99 |
+
args = parser.parse_args()
|
| 100 |
+
|
| 101 |
+
api_key = os.environ.get("ANTHROPIC_API_KEY")
|
| 102 |
+
if not api_key:
|
| 103 |
+
raise ValueError("Set ANTHROPIC_API_KEY environment variable")
|
| 104 |
+
|
| 105 |
+
client = anthropic.Anthropic(api_key=api_key)
|
| 106 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
|
| 108 |
+
images = sorted(args.input_dir.glob("*.jpg")) + sorted(args.input_dir.glob("*.png"))
|
| 109 |
+
if args.max_images:
|
| 110 |
+
images = images[:args.max_images]
|
| 111 |
+
|
| 112 |
+
already_done = len(list(args.output_dir.glob("*.json")))
|
| 113 |
+
images = [img for img in images if not (args.output_dir / f"{img.stem}.json").exists()]
|
| 114 |
+
|
| 115 |
+
print(f"Total images: {len(images) + already_done}")
|
| 116 |
+
print(f"Already captioned: {already_done}")
|
| 117 |
+
print(f"To caption: {len(images)}")
|
| 118 |
+
|
| 119 |
+
batches = [images[i:i+args.batch_size] for i in range(0, len(images), args.batch_size)]
|
| 120 |
+
|
| 121 |
+
total_captioned = 0
|
| 122 |
+
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
| 123 |
+
futures = [
|
| 124 |
+
executor.submit(process_batch, client, batch, args.output_dir, args.model)
|
| 125 |
+
for batch in batches
|
| 126 |
+
]
|
| 127 |
+
for future in tqdm(as_completed(futures), total=len(futures)):
|
| 128 |
+
results = future.result()
|
| 129 |
+
total_captioned += len(results)
|
| 130 |
+
|
| 131 |
+
print(f"\nDone! Captioned {total_captioned} new images")
|
| 132 |
+
print(f"Total captions: {already_done + total_captioned}")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
main()
|
scripts/data_collection/crawl_4k.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Crawl high-resolution 4K images for super-resolution training.
|
| 3 |
+
Uses Unsplash API filtering for images >= 3840px width.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import json
|
| 7 |
+
import requests
|
| 8 |
+
import argparse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
|
| 12 |
+
DATA_DIR = Path("/home/adminuser/chungcat/data/raw/4k")
|
| 13 |
+
METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/4k_meta")
|
| 14 |
+
MIN_WIDTH = 3840
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def fetch_page(access_key, query, page, per_page=30):
|
| 18 |
+
url = "https://api.unsplash.com/search/photos"
|
| 19 |
+
params = {
|
| 20 |
+
"query": query,
|
| 21 |
+
"page": page,
|
| 22 |
+
"per_page": per_page,
|
| 23 |
+
"client_id": access_key,
|
| 24 |
+
}
|
| 25 |
+
resp = requests.get(url, params=params, timeout=30)
|
| 26 |
+
resp.raise_for_status()
|
| 27 |
+
results = resp.json()["results"]
|
| 28 |
+
return [r for r in results if r["width"] >= MIN_WIDTH]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def download_raw(photo, save_dir):
|
| 32 |
+
photo_id = photo["id"]
|
| 33 |
+
url = photo["urls"]["raw"]
|
| 34 |
+
save_path = save_dir / f"{photo_id}.jpg"
|
| 35 |
+
|
| 36 |
+
if save_path.exists():
|
| 37 |
+
return save_path, photo
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
resp = requests.get(url, timeout=120)
|
| 41 |
+
resp.raise_for_status()
|
| 42 |
+
save_path.write_bytes(resp.content)
|
| 43 |
+
return save_path, photo
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Failed {photo_id}: {e}")
|
| 46 |
+
return None, photo
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def save_metadata(photo, meta_dir):
|
| 50 |
+
meta = {
|
| 51 |
+
"id": photo["id"],
|
| 52 |
+
"width": photo["width"],
|
| 53 |
+
"height": photo["height"],
|
| 54 |
+
"description": photo.get("description", ""),
|
| 55 |
+
"alt_description": photo.get("alt_description", ""),
|
| 56 |
+
"user": photo["user"]["name"],
|
| 57 |
+
"tags": [t.get("title", "") for t in photo.get("tags", [])],
|
| 58 |
+
}
|
| 59 |
+
meta_path = meta_dir / f"{photo['id']}.json"
|
| 60 |
+
meta_path.write_text(json.dumps(meta, ensure_ascii=False))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def crawl(access_key, queries, max_pages=200, workers=4):
|
| 64 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 65 |
+
METADATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
|
| 67 |
+
total = 0
|
| 68 |
+
|
| 69 |
+
for query in queries:
|
| 70 |
+
print(f"\n--- Crawling 4K: '{query}' ---")
|
| 71 |
+
for page in range(1, max_pages + 1):
|
| 72 |
+
try:
|
| 73 |
+
photos = fetch_page(access_key, query, page)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
print(f"Page {page} failed: {e}")
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
if not photos:
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
| 82 |
+
futures = [
|
| 83 |
+
executor.submit(download_raw, photo, DATA_DIR)
|
| 84 |
+
for photo in photos
|
| 85 |
+
]
|
| 86 |
+
for future in as_completed(futures):
|
| 87 |
+
path, photo = future.result()
|
| 88 |
+
if path:
|
| 89 |
+
save_metadata(photo, METADATA_DIR)
|
| 90 |
+
total += 1
|
| 91 |
+
|
| 92 |
+
if page % 10 == 0:
|
| 93 |
+
print(f" Page {page}, total 4K images: {total}")
|
| 94 |
+
|
| 95 |
+
print(f"\nDone! Total 4K images: {total}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
parser = argparse.ArgumentParser(description="Crawl 4K images for SR training")
|
| 100 |
+
parser.add_argument("--access-key", required=True, help="Unsplash API access key")
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--queries",
|
| 103 |
+
nargs="+",
|
| 104 |
+
default=[
|
| 105 |
+
"4k wallpaper", "high resolution landscape", "8k nature",
|
| 106 |
+
"ultra hd photography", "4k portrait", "high resolution architecture",
|
| 107 |
+
"macro photography", "aerial photography", "4k city",
|
| 108 |
+
"high resolution texture", "4k abstract", "detailed photography",
|
| 109 |
+
],
|
| 110 |
+
)
|
| 111 |
+
parser.add_argument("--max-pages", type=int, default=200)
|
| 112 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 113 |
+
args = parser.parse_args()
|
| 114 |
+
|
| 115 |
+
crawl(args.access_key, args.queries, args.max_pages, args.workers)
|
scripts/data_collection/crawl_pexels.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import requests
|
| 4 |
+
import argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 7 |
+
|
| 8 |
+
DATA_DIR = Path("/home/adminuser/chungcat/data/raw/pexels")
|
| 9 |
+
METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/pexels_meta")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def fetch_page(api_key, query, page, per_page=80, min_width=1024):
|
| 13 |
+
url = "https://api.pexels.com/v1/search"
|
| 14 |
+
headers = {"Authorization": api_key}
|
| 15 |
+
params = {"query": query, "page": page, "per_page": per_page}
|
| 16 |
+
resp = requests.get(url, headers=headers, params=params, timeout=30)
|
| 17 |
+
resp.raise_for_status()
|
| 18 |
+
photos = resp.json()["photos"]
|
| 19 |
+
return [p for p in photos if p["width"] >= min_width]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def download_image(photo, save_dir):
|
| 23 |
+
photo_id = photo["id"]
|
| 24 |
+
url = photo["src"]["original"]
|
| 25 |
+
save_path = save_dir / f"{photo_id}.jpg"
|
| 26 |
+
|
| 27 |
+
if save_path.exists():
|
| 28 |
+
return save_path, photo
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
resp = requests.get(url, timeout=60)
|
| 32 |
+
resp.raise_for_status()
|
| 33 |
+
save_path.write_bytes(resp.content)
|
| 34 |
+
return save_path, photo
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"Failed {photo_id}: {e}")
|
| 37 |
+
return None, photo
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def save_metadata(photo, meta_dir):
|
| 41 |
+
meta = {
|
| 42 |
+
"id": photo["id"],
|
| 43 |
+
"width": photo["width"],
|
| 44 |
+
"height": photo["height"],
|
| 45 |
+
"alt": photo.get("alt", ""),
|
| 46 |
+
"photographer": photo["photographer"],
|
| 47 |
+
"src": photo["src"],
|
| 48 |
+
}
|
| 49 |
+
meta_path = meta_dir / f"{photo['id']}.json"
|
| 50 |
+
meta_path.write_text(json.dumps(meta, ensure_ascii=False))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def crawl(api_key, queries, max_pages=100, workers=8):
|
| 54 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 55 |
+
METADATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
|
| 57 |
+
total_downloaded = 0
|
| 58 |
+
|
| 59 |
+
for query in queries:
|
| 60 |
+
print(f"\n--- Crawling: '{query}' ---")
|
| 61 |
+
for page in range(1, max_pages + 1):
|
| 62 |
+
try:
|
| 63 |
+
photos = fetch_page(api_key, query, page)
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"Page {page} failed: {e}")
|
| 66 |
+
break
|
| 67 |
+
|
| 68 |
+
if not photos:
|
| 69 |
+
break
|
| 70 |
+
|
| 71 |
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
| 72 |
+
futures = [
|
| 73 |
+
executor.submit(download_image, photo, DATA_DIR)
|
| 74 |
+
for photo in photos
|
| 75 |
+
]
|
| 76 |
+
for future in as_completed(futures):
|
| 77 |
+
path, photo = future.result()
|
| 78 |
+
if path:
|
| 79 |
+
save_metadata(photo, METADATA_DIR)
|
| 80 |
+
total_downloaded += 1
|
| 81 |
+
|
| 82 |
+
if page % 10 == 0:
|
| 83 |
+
print(f" Page {page}, total: {total_downloaded}")
|
| 84 |
+
|
| 85 |
+
print(f"\nDone! Total images: {total_downloaded}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
parser = argparse.ArgumentParser(description="Crawl Pexels images")
|
| 90 |
+
parser.add_argument("--api-key", required=True, help="Pexels API key")
|
| 91 |
+
parser.add_argument(
|
| 92 |
+
"--queries",
|
| 93 |
+
nargs="+",
|
| 94 |
+
default=[
|
| 95 |
+
"landscape", "portrait", "architecture", "nature", "city",
|
| 96 |
+
"food", "technology", "art", "abstract", "animals",
|
| 97 |
+
"fashion", "interior", "street photography", "ocean", "mountain",
|
| 98 |
+
],
|
| 99 |
+
)
|
| 100 |
+
parser.add_argument("--max-pages", type=int, default=100)
|
| 101 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 102 |
+
args = parser.parse_args()
|
| 103 |
+
|
| 104 |
+
crawl(args.api_key, args.queries, args.max_pages, args.workers)
|
scripts/data_collection/crawl_unsplash.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import requests
|
| 4 |
+
import argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
|
| 9 |
+
DATA_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash")
|
| 10 |
+
METADATA_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash_meta")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def fetch_page(access_key, query, page, per_page=30, min_width=1024):
|
| 14 |
+
url = "https://api.unsplash.com/search/photos"
|
| 15 |
+
params = {
|
| 16 |
+
"query": query,
|
| 17 |
+
"page": page,
|
| 18 |
+
"per_page": per_page,
|
| 19 |
+
"client_id": access_key,
|
| 20 |
+
}
|
| 21 |
+
resp = requests.get(url, params=params, timeout=30)
|
| 22 |
+
resp.raise_for_status()
|
| 23 |
+
results = resp.json()["results"]
|
| 24 |
+
return [r for r in results if r["width"] >= min_width]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def download_image(photo, resolution="regular", save_dir=None):
|
| 28 |
+
photo_id = photo["id"]
|
| 29 |
+
url = photo["urls"][resolution]
|
| 30 |
+
ext = "jpg"
|
| 31 |
+
save_path = save_dir / f"{photo_id}.{ext}"
|
| 32 |
+
|
| 33 |
+
if save_path.exists():
|
| 34 |
+
return save_path, photo
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
resp = requests.get(url, timeout=60)
|
| 38 |
+
resp.raise_for_status()
|
| 39 |
+
save_path.write_bytes(resp.content)
|
| 40 |
+
return save_path, photo
|
| 41 |
+
except Exception as e:
|
| 42 |
+
print(f"Failed {photo_id}: {e}")
|
| 43 |
+
return None, photo
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def save_metadata(photo, meta_dir):
|
| 47 |
+
photo_id = photo["id"]
|
| 48 |
+
meta = {
|
| 49 |
+
"id": photo_id,
|
| 50 |
+
"width": photo["width"],
|
| 51 |
+
"height": photo["height"],
|
| 52 |
+
"description": photo.get("description", ""),
|
| 53 |
+
"alt_description": photo.get("alt_description", ""),
|
| 54 |
+
"urls": photo["urls"],
|
| 55 |
+
"user": photo["user"]["name"],
|
| 56 |
+
"tags": [t.get("title", "") for t in photo.get("tags", [])],
|
| 57 |
+
}
|
| 58 |
+
meta_path = meta_dir / f"{photo_id}.json"
|
| 59 |
+
meta_path.write_text(json.dumps(meta, ensure_ascii=False))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def crawl(access_key, queries, max_pages=100, resolution="regular", workers=8):
|
| 63 |
+
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
METADATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 65 |
+
|
| 66 |
+
total_downloaded = 0
|
| 67 |
+
|
| 68 |
+
for query in queries:
|
| 69 |
+
print(f"\n--- Crawling: '{query}' ---")
|
| 70 |
+
for page in range(1, max_pages + 1):
|
| 71 |
+
try:
|
| 72 |
+
photos = fetch_page(access_key, query, page)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
print(f"Page {page} failed: {e}")
|
| 75 |
+
break
|
| 76 |
+
|
| 77 |
+
if not photos:
|
| 78 |
+
print(f"No more results for '{query}' at page {page}")
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
with ThreadPoolExecutor(max_workers=workers) as executor:
|
| 82 |
+
futures = []
|
| 83 |
+
for photo in photos:
|
| 84 |
+
futures.append(
|
| 85 |
+
executor.submit(download_image, photo, resolution, DATA_DIR)
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
for future in as_completed(futures):
|
| 89 |
+
path, photo = future.result()
|
| 90 |
+
if path:
|
| 91 |
+
save_metadata(photo, METADATA_DIR)
|
| 92 |
+
total_downloaded += 1
|
| 93 |
+
|
| 94 |
+
if page % 10 == 0:
|
| 95 |
+
print(f" Page {page}, total downloaded: {total_downloaded}")
|
| 96 |
+
|
| 97 |
+
print(f"\nDone! Total images: {total_downloaded}")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
if __name__ == "__main__":
|
| 101 |
+
parser = argparse.ArgumentParser(description="Crawl Unsplash images")
|
| 102 |
+
parser.add_argument("--access-key", required=True, help="Unsplash API access key")
|
| 103 |
+
parser.add_argument(
|
| 104 |
+
"--queries",
|
| 105 |
+
nargs="+",
|
| 106 |
+
default=[
|
| 107 |
+
"landscape", "portrait", "architecture", "nature", "city",
|
| 108 |
+
"food", "technology", "art", "abstract", "animals",
|
| 109 |
+
"fashion", "interior", "street photography", "ocean", "mountain",
|
| 110 |
+
],
|
| 111 |
+
)
|
| 112 |
+
parser.add_argument("--max-pages", type=int, default=100)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--resolution",
|
| 115 |
+
choices=["raw", "full", "regular", "small"],
|
| 116 |
+
default="full",
|
| 117 |
+
help="Image resolution (full=max quality)",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument("--workers", type=int, default=8)
|
| 120 |
+
args = parser.parse_args()
|
| 121 |
+
|
| 122 |
+
crawl(args.access_key, args.queries, args.max_pages, args.resolution, args.workers)
|
scripts/data_collection/create_sr_pairs.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tạo training pairs cho super-resolution:
|
| 3 |
+
- Lấy ảnh 4K gốc làm target (ground truth)
|
| 4 |
+
- Downscale xuống 2K và 1K làm input
|
| 5 |
+
- Thêm degradation (noise, blur, compression) cho realistic
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import random
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 11 |
+
|
| 12 |
+
import cv2
|
| 13 |
+
import numpy as np
|
| 14 |
+
from tqdm import tqdm
|
| 15 |
+
|
| 16 |
+
INPUT_DIR = Path("/home/adminuser/chungcat/data/raw/4k")
|
| 17 |
+
OUTPUT_BASE = Path("/home/adminuser/chungcat/data/processed")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def add_degradation(img, level="light"):
|
| 21 |
+
if level == "none":
|
| 22 |
+
return img
|
| 23 |
+
|
| 24 |
+
if random.random() < 0.3:
|
| 25 |
+
ksize = random.choice([3, 5])
|
| 26 |
+
img = cv2.GaussianBlur(img, (ksize, ksize), 0)
|
| 27 |
+
|
| 28 |
+
if random.random() < 0.3:
|
| 29 |
+
noise = np.random.normal(0, random.uniform(1, 5), img.shape).astype(np.float32)
|
| 30 |
+
img = np.clip(img.astype(np.float32) + noise, 0, 255).astype(np.uint8)
|
| 31 |
+
|
| 32 |
+
if random.random() < 0.3:
|
| 33 |
+
quality = random.randint(70, 95)
|
| 34 |
+
_, encoded = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, quality])
|
| 35 |
+
img = cv2.imdecode(encoded, cv2.IMREAD_COLOR)
|
| 36 |
+
|
| 37 |
+
return img
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def process_image(img_path, output_dirs, target_sizes, degradation="light"):
|
| 41 |
+
try:
|
| 42 |
+
img = cv2.imread(str(img_path), cv2.IMREAD_COLOR)
|
| 43 |
+
if img is None:
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
h, w = img.shape[:2]
|
| 47 |
+
if w < 3840 or h < 2160:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
stem = img_path.stem
|
| 51 |
+
|
| 52 |
+
# Crop to 4096x4096 or keep aspect ratio
|
| 53 |
+
# For training, use random crops
|
| 54 |
+
crop_size_4k = 4096
|
| 55 |
+
crop_size_2k = 2048
|
| 56 |
+
crop_size_1k = 1024
|
| 57 |
+
|
| 58 |
+
if h >= crop_size_4k and w >= crop_size_4k:
|
| 59 |
+
y = random.randint(0, h - crop_size_4k)
|
| 60 |
+
x = random.randint(0, w - crop_size_4k)
|
| 61 |
+
crop_4k = img[y:y+crop_size_4k, x:x+crop_size_4k]
|
| 62 |
+
else:
|
| 63 |
+
crop_4k = cv2.resize(img, (crop_size_4k, crop_size_4k), interpolation=cv2.INTER_LANCZOS4)
|
| 64 |
+
|
| 65 |
+
# Downscale to 2K
|
| 66 |
+
crop_2k = cv2.resize(crop_4k, (crop_size_2k, crop_size_2k), interpolation=cv2.INTER_AREA)
|
| 67 |
+
|
| 68 |
+
# Downscale to 1K
|
| 69 |
+
crop_1k = cv2.resize(crop_4k, (crop_size_1k, crop_size_1k), interpolation=cv2.INTER_AREA)
|
| 70 |
+
|
| 71 |
+
# Add degradation to inputs
|
| 72 |
+
crop_2k_degraded = add_degradation(crop_2k, degradation)
|
| 73 |
+
crop_1k_degraded = add_degradation(crop_1k, degradation)
|
| 74 |
+
|
| 75 |
+
# Save
|
| 76 |
+
cv2.imwrite(str(output_dirs["4k"] / f"{stem}.png"), crop_4k)
|
| 77 |
+
cv2.imwrite(str(output_dirs["2k"] / f"{stem}.png"), crop_2k_degraded)
|
| 78 |
+
cv2.imwrite(str(output_dirs["1k"] / f"{stem}.png"), crop_1k_degraded)
|
| 79 |
+
|
| 80 |
+
return stem
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"Error processing {img_path}: {e}")
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def main():
|
| 87 |
+
parser = argparse.ArgumentParser(description="Create SR training pairs from 4K images")
|
| 88 |
+
parser.add_argument("--input-dir", type=Path, default=INPUT_DIR)
|
| 89 |
+
parser.add_argument("--output-dir", type=Path, default=OUTPUT_BASE / "sr_pairs")
|
| 90 |
+
parser.add_argument("--degradation", choices=["none", "light", "heavy"], default="light")
|
| 91 |
+
parser.add_argument("--workers", type=int, default=16)
|
| 92 |
+
parser.add_argument("--max-images", type=int, default=None)
|
| 93 |
+
args = parser.parse_args()
|
| 94 |
+
|
| 95 |
+
output_dirs = {
|
| 96 |
+
"4k": args.output_dir / "4k_target",
|
| 97 |
+
"2k": args.output_dir / "2k_input",
|
| 98 |
+
"1k": args.output_dir / "1k_input",
|
| 99 |
+
}
|
| 100 |
+
for d in output_dirs.values():
|
| 101 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
|
| 103 |
+
images = list(args.input_dir.glob("*.jpg")) + list(args.input_dir.glob("*.png"))
|
| 104 |
+
if args.max_images:
|
| 105 |
+
images = images[:args.max_images]
|
| 106 |
+
|
| 107 |
+
print(f"Processing {len(images)} images...")
|
| 108 |
+
|
| 109 |
+
processed = 0
|
| 110 |
+
with ProcessPoolExecutor(max_workers=args.workers) as executor:
|
| 111 |
+
futures = [
|
| 112 |
+
executor.submit(process_image, img, output_dirs, None, args.degradation)
|
| 113 |
+
for img in images
|
| 114 |
+
]
|
| 115 |
+
for future in tqdm(as_completed(futures), total=len(futures)):
|
| 116 |
+
result = future.result()
|
| 117 |
+
if result:
|
| 118 |
+
processed += 1
|
| 119 |
+
|
| 120 |
+
print(f"Done! Processed {processed}/{len(images)} images")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
main()
|
scripts/data_collection/download_coyo_images.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Download images from filtered COYO parquet using img2dataset.
|
| 3 |
+
"""
|
| 4 |
+
import subprocess
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def download_from_parquet(parquet_path, output_dir, resolution=1024, workers=32, thread_count=128):
|
| 12 |
+
output_dir = Path(output_dir)
|
| 13 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
# img2dataset needs url + caption columns
|
| 16 |
+
df = pd.read_parquet(parquet_path)
|
| 17 |
+
print(f"Total URLs to download: {len(df)}")
|
| 18 |
+
|
| 19 |
+
# Save as temporary parquet with required columns
|
| 20 |
+
tmp_parquet = output_dir / "_urls.parquet"
|
| 21 |
+
df_out = df[["url", "text"]].rename(columns={"url": "URL", "text": "TEXT"})
|
| 22 |
+
df_out.to_parquet(tmp_parquet, index=False)
|
| 23 |
+
|
| 24 |
+
cmd = [
|
| 25 |
+
"img2dataset",
|
| 26 |
+
"--url_list", str(tmp_parquet),
|
| 27 |
+
"--input_format", "parquet",
|
| 28 |
+
"--url_col", "URL",
|
| 29 |
+
"--caption_col", "TEXT",
|
| 30 |
+
"--output_format", "webdataset",
|
| 31 |
+
"--output_folder", str(output_dir / "shards"),
|
| 32 |
+
"--processes_count", str(workers),
|
| 33 |
+
"--thread_count", str(thread_count),
|
| 34 |
+
"--image_size", str(resolution),
|
| 35 |
+
"--resize_mode", "center_crop",
|
| 36 |
+
"--resize_only_if_bigger", "True",
|
| 37 |
+
"--number_sample_per_shard", "1000",
|
| 38 |
+
"--save_additional_columns", '["aesthetic_score_laion_v2"]',
|
| 39 |
+
"--retries", "2",
|
| 40 |
+
"--disallowed_header_directives", '["noai", "noimageai", "noindex"]',
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
print(f"Running img2dataset...")
|
| 44 |
+
print(f" Resolution: {resolution}px")
|
| 45 |
+
print(f" Workers: {workers}")
|
| 46 |
+
print(f" Output: {output_dir / 'shards'}")
|
| 47 |
+
|
| 48 |
+
subprocess.run(cmd, check=True)
|
| 49 |
+
print("Download complete!")
|
| 50 |
+
|
| 51 |
+
# Cleanup temp file
|
| 52 |
+
tmp_parquet.unlink(missing_ok=True)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
parser = argparse.ArgumentParser(description="Download images from filtered COYO")
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
"--parquet",
|
| 59 |
+
type=Path,
|
| 60 |
+
default=Path("/home/adminuser/chungcat/data/raw/coyo_filtered/coyo_aesthetic.parquet"),
|
| 61 |
+
)
|
| 62 |
+
parser.add_argument(
|
| 63 |
+
"--output-dir",
|
| 64 |
+
type=Path,
|
| 65 |
+
default=Path("/home/adminuser/chungcat/data/processed/flux_train"),
|
| 66 |
+
)
|
| 67 |
+
parser.add_argument("--resolution", type=int, default=1024)
|
| 68 |
+
parser.add_argument("--workers", type=int, default=32)
|
| 69 |
+
parser.add_argument("--threads", type=int, default=128)
|
| 70 |
+
args = parser.parse_args()
|
| 71 |
+
|
| 72 |
+
download_from_parquet(args.parquet, args.output_dir, args.resolution, args.workers, args.threads)
|
scripts/data_collection/download_laion.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Download LAION-Aesthetics dataset (aesthetic score >= 6.0).
|
| 3 |
+
High-quality images with captions, suitable for Flux fine-tuning.
|
| 4 |
+
Uses img2dataset for fast parallel downloading.
|
| 5 |
+
"""
|
| 6 |
+
import subprocess
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
OUTPUT_DIR = Path("/home/adminuser/chungcat/data/raw/laion")
|
| 11 |
+
PARQUET_DIR = Path("/home/adminuser/chungcat/data/raw/laion_meta")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def download_metadata():
|
| 15 |
+
"""Download LAION-Aesthetics v2 6+ metadata (parquet files with URLs + captions)."""
|
| 16 |
+
PARQUET_DIR.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
|
| 18 |
+
print("Downloading LAION-Aesthetics v2 6+ metadata...")
|
| 19 |
+
# This subset contains ~600K images with aesthetic score >= 6.0
|
| 20 |
+
url = "https://huggingface.co/datasets/laion/laion2B-en-aesthetic/resolve/main"
|
| 21 |
+
|
| 22 |
+
subprocess.run([
|
| 23 |
+
"pip3", "install", "huggingface_hub[cli]"
|
| 24 |
+
], capture_output=True)
|
| 25 |
+
|
| 26 |
+
subprocess.run([
|
| 27 |
+
"python3", "-c", f"""
|
| 28 |
+
from huggingface_hub import snapshot_download
|
| 29 |
+
snapshot_download(
|
| 30 |
+
repo_id="laion/laion2B-en-aesthetic",
|
| 31 |
+
repo_type="dataset",
|
| 32 |
+
local_dir="{PARQUET_DIR}",
|
| 33 |
+
allow_patterns=["*.parquet"],
|
| 34 |
+
max_workers=8,
|
| 35 |
+
)
|
| 36 |
+
print("Metadata download complete!")
|
| 37 |
+
"""
|
| 38 |
+
], check=True)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def download_images(num_images=1000000, resolution=1024, workers=64):
|
| 42 |
+
"""Download images using img2dataset from parquet metadata."""
|
| 43 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
|
| 45 |
+
parquet_files = list(PARQUET_DIR.glob("**/*.parquet"))
|
| 46 |
+
if not parquet_files:
|
| 47 |
+
print("No parquet files found. Run with --download-meta first.")
|
| 48 |
+
return
|
| 49 |
+
|
| 50 |
+
print(f"Found {len(parquet_files)} parquet files")
|
| 51 |
+
print(f"Downloading up to {num_images} images at {resolution}px...")
|
| 52 |
+
|
| 53 |
+
# img2dataset handles parallel download, resize, and WebDataset output
|
| 54 |
+
cmd = [
|
| 55 |
+
"img2dataset",
|
| 56 |
+
"--url_list", str(parquet_files[0]),
|
| 57 |
+
"--input_format", "parquet",
|
| 58 |
+
"--url_col", "URL",
|
| 59 |
+
"--caption_col", "TEXT",
|
| 60 |
+
"--output_format", "webdataset",
|
| 61 |
+
"--output_folder", str(OUTPUT_DIR),
|
| 62 |
+
"--processes_count", str(workers),
|
| 63 |
+
"--thread_count", "128",
|
| 64 |
+
"--image_size", str(resolution),
|
| 65 |
+
"--resize_mode", "center_crop",
|
| 66 |
+
"--resize_only_if_bigger", "True",
|
| 67 |
+
"--enable_wandb", "False",
|
| 68 |
+
"--number_sample_per_shard", "1000",
|
| 69 |
+
"--save_additional_columns", '["AESTHETIC_SCORE","WIDTH","HEIGHT"]',
|
| 70 |
+
"--max_shard_retry", "3",
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
if num_images:
|
| 74 |
+
cmd.extend(["--max_shard_retry", "3"])
|
| 75 |
+
|
| 76 |
+
print(f"Running: {' '.join(cmd)}")
|
| 77 |
+
subprocess.run(cmd, check=True)
|
| 78 |
+
print("Download complete!")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def download_images_multi(num_workers=64, resolution=1024):
|
| 82 |
+
"""Download from all parquet files."""
|
| 83 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
|
| 85 |
+
parquet_files = sorted(PARQUET_DIR.glob("**/*.parquet"))
|
| 86 |
+
if not parquet_files:
|
| 87 |
+
print("No parquet files found. Run with --download-meta first.")
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
print(f"Found {len(parquet_files)} parquet files")
|
| 91 |
+
|
| 92 |
+
for i, pf in enumerate(parquet_files):
|
| 93 |
+
shard_output = OUTPUT_DIR / f"shard_{i:04d}"
|
| 94 |
+
shard_output.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
print(f"\n[{i+1}/{len(parquet_files)}] Processing {pf.name}...")
|
| 97 |
+
|
| 98 |
+
cmd = [
|
| 99 |
+
"img2dataset",
|
| 100 |
+
"--url_list", str(pf),
|
| 101 |
+
"--input_format", "parquet",
|
| 102 |
+
"--url_col", "URL",
|
| 103 |
+
"--caption_col", "TEXT",
|
| 104 |
+
"--output_format", "webdataset",
|
| 105 |
+
"--output_folder", str(shard_output),
|
| 106 |
+
"--processes_count", str(num_workers),
|
| 107 |
+
"--thread_count", "128",
|
| 108 |
+
"--image_size", str(resolution),
|
| 109 |
+
"--resize_mode", "center_crop",
|
| 110 |
+
"--resize_only_if_bigger", "True",
|
| 111 |
+
"--enable_wandb", "False",
|
| 112 |
+
"--number_sample_per_shard", "1000",
|
| 113 |
+
"--save_additional_columns", '["AESTHETIC_SCORE","WIDTH","HEIGHT"]',
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
subprocess.run(cmd, check=True)
|
| 118 |
+
except subprocess.CalledProcessError as e:
|
| 119 |
+
print(f"Error on {pf.name}: {e}")
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
print("\nAll shards downloaded!")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
parser = argparse.ArgumentParser(description="Download LAION-Aesthetics dataset")
|
| 127 |
+
parser.add_argument("--download-meta", action="store_true", help="Download metadata parquet files")
|
| 128 |
+
parser.add_argument("--download-images", action="store_true", help="Download images from first parquet")
|
| 129 |
+
parser.add_argument("--download-all", action="store_true", help="Download from all parquet files")
|
| 130 |
+
parser.add_argument("--resolution", type=int, default=1024)
|
| 131 |
+
parser.add_argument("--workers", type=int, default=64)
|
| 132 |
+
parser.add_argument("--max-images", type=int, default=1000000)
|
| 133 |
+
args = parser.parse_args()
|
| 134 |
+
|
| 135 |
+
if args.download_meta:
|
| 136 |
+
download_metadata()
|
| 137 |
+
elif args.download_images:
|
| 138 |
+
download_images(args.max_images, args.resolution, args.workers)
|
| 139 |
+
elif args.download_all:
|
| 140 |
+
download_images_multi(args.workers, args.resolution)
|
| 141 |
+
else:
|
| 142 |
+
print("Specify --download-meta, --download-images, or --download-all")
|
| 143 |
+
print("\nWorkflow:")
|
| 144 |
+
print(" 1. python3 download_laion.py --download-meta")
|
| 145 |
+
print(" 2. python3 download_laion.py --download-images --max-images 1000000")
|
| 146 |
+
print(" Or: python3 download_laion.py --download-all")
|
scripts/data_collection/filter_coyo.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Filter COYO-700M dataset by aesthetic score and resolution,
|
| 3 |
+
then download images using img2dataset.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
COYO_DIR = Path("/home/adminuser/chungcat/data/raw/coyo/data")
|
| 10 |
+
OUTPUT_DIR = Path("/home/adminuser/chungcat/data/raw/coyo_filtered")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def filter_parquet(
|
| 14 |
+
input_dir,
|
| 15 |
+
output_path,
|
| 16 |
+
min_aesthetic=6.0,
|
| 17 |
+
min_width=1024,
|
| 18 |
+
min_height=1024,
|
| 19 |
+
max_nsfw=0.3,
|
| 20 |
+
min_clip_score=0.25,
|
| 21 |
+
max_watermark=0.5,
|
| 22 |
+
max_records=None,
|
| 23 |
+
):
|
| 24 |
+
parquet_files = sorted(input_dir.glob("*.parquet"))
|
| 25 |
+
print(f"Found {len(parquet_files)} parquet files")
|
| 26 |
+
|
| 27 |
+
all_filtered = []
|
| 28 |
+
|
| 29 |
+
for pf in parquet_files:
|
| 30 |
+
print(f"\nProcessing {pf.name}...")
|
| 31 |
+
df = pd.read_parquet(pf)
|
| 32 |
+
print(f" Total records: {len(df)}")
|
| 33 |
+
|
| 34 |
+
filtered = df[
|
| 35 |
+
(df["aesthetic_score_laion_v2"] >= min_aesthetic)
|
| 36 |
+
& (df["width"] >= min_width)
|
| 37 |
+
& (df["height"] >= min_height)
|
| 38 |
+
& (df["nsfw_score_opennsfw2"] <= max_nsfw)
|
| 39 |
+
& (df["clip_similarity_vitl14"] >= min_clip_score)
|
| 40 |
+
& (df["watermark_score"] <= max_watermark)
|
| 41 |
+
].copy()
|
| 42 |
+
|
| 43 |
+
print(f" After filter: {len(filtered)}")
|
| 44 |
+
all_filtered.append(filtered)
|
| 45 |
+
|
| 46 |
+
result = pd.concat(all_filtered, ignore_index=True)
|
| 47 |
+
print(f"\nTotal filtered: {len(result)}")
|
| 48 |
+
|
| 49 |
+
if max_records and len(result) > max_records:
|
| 50 |
+
result = result.sort_values("aesthetic_score_laion_v2", ascending=False).head(max_records)
|
| 51 |
+
print(f"Trimmed to top {max_records} by aesthetic score")
|
| 52 |
+
|
| 53 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 54 |
+
result.to_parquet(output_path, index=False)
|
| 55 |
+
print(f"Saved to {output_path}")
|
| 56 |
+
|
| 57 |
+
print(f"\nStats:")
|
| 58 |
+
print(f" Aesthetic score: {result['aesthetic_score_laion_v2'].mean():.2f} avg")
|
| 59 |
+
print(f" Resolution: {result['width'].mean():.0f}x{result['height'].mean():.0f} avg")
|
| 60 |
+
print(f" CLIP score: {result['clip_similarity_vitl14'].mean():.3f} avg")
|
| 61 |
+
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def filter_4k(input_dir, output_path, min_width=3840, min_height=2160, max_nsfw=0.3):
|
| 66 |
+
"""Filter specifically for 4K+ images for SR training."""
|
| 67 |
+
parquet_files = sorted(input_dir.glob("*.parquet"))
|
| 68 |
+
all_filtered = []
|
| 69 |
+
|
| 70 |
+
for pf in parquet_files:
|
| 71 |
+
print(f"Processing {pf.name} for 4K...")
|
| 72 |
+
df = pd.read_parquet(pf)
|
| 73 |
+
filtered = df[
|
| 74 |
+
(df["width"] >= min_width)
|
| 75 |
+
& (df["height"] >= min_height)
|
| 76 |
+
& (df["nsfw_score_opennsfw2"] <= max_nsfw)
|
| 77 |
+
].copy()
|
| 78 |
+
print(f" 4K images: {len(filtered)}")
|
| 79 |
+
all_filtered.append(filtered)
|
| 80 |
+
|
| 81 |
+
result = pd.concat(all_filtered, ignore_index=True)
|
| 82 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 83 |
+
result.to_parquet(output_path, index=False)
|
| 84 |
+
print(f"\nTotal 4K images: {len(result)}")
|
| 85 |
+
print(f"Saved to {output_path}")
|
| 86 |
+
return result
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if __name__ == "__main__":
|
| 90 |
+
parser = argparse.ArgumentParser(description="Filter COYO dataset")
|
| 91 |
+
parser.add_argument("--input-dir", type=Path, default=COYO_DIR)
|
| 92 |
+
parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
|
| 93 |
+
parser.add_argument("--min-aesthetic", type=float, default=6.0)
|
| 94 |
+
parser.add_argument("--min-width", type=int, default=1024)
|
| 95 |
+
parser.add_argument("--min-height", type=int, default=1024)
|
| 96 |
+
parser.add_argument("--max-nsfw", type=float, default=0.3)
|
| 97 |
+
parser.add_argument("--min-clip", type=float, default=0.25)
|
| 98 |
+
parser.add_argument("--max-watermark", type=float, default=0.5)
|
| 99 |
+
parser.add_argument("--max-records", type=int, default=None)
|
| 100 |
+
parser.add_argument("--filter-4k", action="store_true", help="Filter for 4K+ images only")
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
|
| 103 |
+
if args.filter_4k:
|
| 104 |
+
filter_4k(args.input_dir, args.output_dir / "coyo_4k.parquet")
|
| 105 |
+
else:
|
| 106 |
+
filter_parquet(
|
| 107 |
+
args.input_dir,
|
| 108 |
+
args.output_dir / "coyo_aesthetic.parquet",
|
| 109 |
+
min_aesthetic=args.min_aesthetic,
|
| 110 |
+
min_width=args.min_width,
|
| 111 |
+
min_height=args.min_height,
|
| 112 |
+
max_nsfw=args.max_nsfw,
|
| 113 |
+
min_clip_score=args.min_clip,
|
| 114 |
+
max_watermark=args.max_watermark,
|
| 115 |
+
max_records=args.max_records,
|
| 116 |
+
)
|
scripts/data_collection/prepare_webdataset.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Prepare dataset for Flux fine-tuning.
|
| 3 |
+
Combines images + captions into WebDataset format (tar shards).
|
| 4 |
+
"""
|
| 5 |
+
import json
|
| 6 |
+
import io
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import webdataset as wds
|
| 11 |
+
from PIL import Image
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
|
| 14 |
+
IMAGE_DIR = Path("/home/adminuser/chungcat/data/raw/unsplash")
|
| 15 |
+
CAPTION_DIR = Path("/home/adminuser/chungcat/data/captions")
|
| 16 |
+
OUTPUT_DIR = Path("/home/adminuser/chungcat/data/processed/flux_train")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def create_webdataset(image_dir, caption_dir, output_dir, shard_size=1000):
|
| 20 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 21 |
+
pattern = str(output_dir / "shard-%06d.tar")
|
| 22 |
+
|
| 23 |
+
captions = list(caption_dir.glob("*.json"))
|
| 24 |
+
print(f"Found {len(captions)} captions")
|
| 25 |
+
|
| 26 |
+
with wds.ShardWriter(pattern, maxcount=shard_size) as sink:
|
| 27 |
+
written = 0
|
| 28 |
+
for cap_path in tqdm(captions):
|
| 29 |
+
meta = json.loads(cap_path.read_text())
|
| 30 |
+
stem = cap_path.stem
|
| 31 |
+
|
| 32 |
+
img_path = image_dir / f"{stem}.jpg"
|
| 33 |
+
if not img_path.exists():
|
| 34 |
+
img_path = image_dir / f"{stem}.png"
|
| 35 |
+
if not img_path.exists():
|
| 36 |
+
continue
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
img = Image.open(img_path).convert("RGB")
|
| 40 |
+
img = img.resize((1024, 1024), Image.LANCZOS)
|
| 41 |
+
|
| 42 |
+
img_bytes = io.BytesIO()
|
| 43 |
+
img.save(img_bytes, format="JPEG", quality=95)
|
| 44 |
+
img_bytes = img_bytes.getvalue()
|
| 45 |
+
|
| 46 |
+
sample = {
|
| 47 |
+
"__key__": stem,
|
| 48 |
+
"jpg": img_bytes,
|
| 49 |
+
"txt": meta["caption"],
|
| 50 |
+
"json": json.dumps(meta).encode(),
|
| 51 |
+
}
|
| 52 |
+
sink.write(sample)
|
| 53 |
+
written += 1
|
| 54 |
+
except Exception as e:
|
| 55 |
+
print(f"Error {stem}: {e}")
|
| 56 |
+
|
| 57 |
+
print(f"Done! Written {written} samples to {output_dir}")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
if __name__ == "__main__":
|
| 61 |
+
parser = argparse.ArgumentParser(description="Prepare WebDataset for Flux training")
|
| 62 |
+
parser.add_argument("--image-dir", type=Path, default=IMAGE_DIR)
|
| 63 |
+
parser.add_argument("--caption-dir", type=Path, default=CAPTION_DIR)
|
| 64 |
+
parser.add_argument("--output-dir", type=Path, default=OUTPUT_DIR)
|
| 65 |
+
parser.add_argument("--shard-size", type=int, default=1000)
|
| 66 |
+
args = parser.parse_args()
|
| 67 |
+
|
| 68 |
+
create_webdataset(args.image_dir, args.caption_dir, args.output_dir, args.shard_size)
|
scripts/serving/api_server.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FastAPI server for 4K image generation.
|
| 3 |
+
"""
|
| 4 |
+
import asyncio
|
| 5 |
+
import uuid
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from fastapi import FastAPI, BackgroundTasks
|
| 11 |
+
from fastapi.responses import FileResponse
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).parent))
|
| 16 |
+
from inference import load_flux_pipeline, load_sr_model, generate_4k
|
| 17 |
+
|
| 18 |
+
app = FastAPI(title="4K Image Generation API")
|
| 19 |
+
|
| 20 |
+
# Global models (loaded on startup)
|
| 21 |
+
flux_pipe = None
|
| 22 |
+
sr_stage2 = None
|
| 23 |
+
sr_stage3 = None
|
| 24 |
+
jobs = {}
|
| 25 |
+
|
| 26 |
+
OUTPUT_DIR = Path("/home/adminuser/chungcat/outputs/api")
|
| 27 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class GenerateRequest(BaseModel):
|
| 31 |
+
prompt: str
|
| 32 |
+
resolution: str = "4k" # "1k", "2k", "4k"
|
| 33 |
+
steps: int = 28
|
| 34 |
+
guidance_scale: float = 3.5
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class JobStatus(BaseModel):
|
| 38 |
+
job_id: str
|
| 39 |
+
status: str # "pending", "processing", "completed", "failed"
|
| 40 |
+
resolution: str
|
| 41 |
+
elapsed_seconds: float = 0
|
| 42 |
+
result_url: str = None
|
| 43 |
+
error: str = None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@app.on_event("startup")
|
| 47 |
+
async def startup():
|
| 48 |
+
global flux_pipe, sr_stage2, sr_stage3
|
| 49 |
+
|
| 50 |
+
flux_pipe = load_flux_pipeline(
|
| 51 |
+
"black-forest-labs/FLUX.1-schnell",
|
| 52 |
+
lora_path=Path("/home/adminuser/chungcat/checkpoints/flux_lora/final"),
|
| 53 |
+
device="cuda:0",
|
| 54 |
+
)
|
| 55 |
+
sr_stage2 = load_sr_model(
|
| 56 |
+
"/home/adminuser/chungcat/checkpoints/sr_stage2/final/model.pt",
|
| 57 |
+
device="cuda:1",
|
| 58 |
+
)
|
| 59 |
+
sr_stage3 = load_sr_model(
|
| 60 |
+
"/home/adminuser/chungcat/checkpoints/sr_stage3/final/model.pt",
|
| 61 |
+
device="cuda:1",
|
| 62 |
+
)
|
| 63 |
+
print("All models loaded!")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def process_job(job_id: str, request: GenerateRequest):
|
| 67 |
+
jobs[job_id]["status"] = "processing"
|
| 68 |
+
t0 = time.time()
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
image = generate_4k(
|
| 72 |
+
prompt=request.prompt,
|
| 73 |
+
flux_pipe=flux_pipe,
|
| 74 |
+
sr_stage2=sr_stage2,
|
| 75 |
+
sr_stage3=sr_stage3,
|
| 76 |
+
output_path=OUTPUT_DIR / job_id,
|
| 77 |
+
num_inference_steps=request.steps,
|
| 78 |
+
guidance_scale=request.guidance_scale,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
jobs[job_id]["status"] = "completed"
|
| 82 |
+
jobs[job_id]["elapsed_seconds"] = time.time() - t0
|
| 83 |
+
|
| 84 |
+
stem = request.prompt[:50].replace(" ", "_").replace("/", "_")
|
| 85 |
+
res_suffix = request.resolution
|
| 86 |
+
jobs[job_id]["result_url"] = f"/result/{job_id}/{stem}_{res_suffix}.png"
|
| 87 |
+
|
| 88 |
+
except Exception as e:
|
| 89 |
+
jobs[job_id]["status"] = "failed"
|
| 90 |
+
jobs[job_id]["error"] = str(e)
|
| 91 |
+
jobs[job_id]["elapsed_seconds"] = time.time() - t0
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@app.post("/generate", response_model=JobStatus)
|
| 95 |
+
async def generate(request: GenerateRequest, background_tasks: BackgroundTasks):
|
| 96 |
+
job_id = str(uuid.uuid4())[:8]
|
| 97 |
+
jobs[job_id] = {
|
| 98 |
+
"job_id": job_id,
|
| 99 |
+
"status": "pending",
|
| 100 |
+
"resolution": request.resolution,
|
| 101 |
+
"elapsed_seconds": 0,
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
background_tasks.add_task(process_job, job_id, request)
|
| 105 |
+
return JobStatus(**jobs[job_id])
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@app.get("/status/{job_id}", response_model=JobStatus)
|
| 109 |
+
async def get_status(job_id: str):
|
| 110 |
+
if job_id not in jobs:
|
| 111 |
+
return JobStatus(job_id=job_id, status="not_found", resolution="")
|
| 112 |
+
return JobStatus(**jobs[job_id])
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@app.get("/result/{job_id}/{filename}")
|
| 116 |
+
async def get_result(job_id: str, filename: str):
|
| 117 |
+
file_path = OUTPUT_DIR / job_id / filename
|
| 118 |
+
if not file_path.exists():
|
| 119 |
+
return {"error": "File not found"}
|
| 120 |
+
return FileResponse(file_path, media_type="image/png")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@app.get("/health")
|
| 124 |
+
async def health():
|
| 125 |
+
return {
|
| 126 |
+
"status": "ok",
|
| 127 |
+
"gpu_0": torch.cuda.get_device_name(0),
|
| 128 |
+
"gpu_1": torch.cuda.get_device_name(1),
|
| 129 |
+
"gpu_0_memory_used": f"{torch.cuda.memory_allocated(0) / 1024**3:.1f} GB",
|
| 130 |
+
"gpu_1_memory_used": f"{torch.cuda.memory_allocated(1) / 1024**3:.1f} GB",
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
import uvicorn
|
| 136 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
scripts/serving/inference.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Inference pipeline: Generate 4K image from text prompt.
|
| 3 |
+
Stage 1 (Flux) → Stage 2 (SR 1K→2K) → Stage 3 (SR 2K→4K)
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import time
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from diffusers import FluxPipeline
|
| 12 |
+
from peft import PeftModel
|
| 13 |
+
|
| 14 |
+
from train_sr import SRUNet
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def load_flux_pipeline(base_model, lora_path=None, device="cuda:0"):
|
| 18 |
+
print(f"Loading Flux from {base_model}...")
|
| 19 |
+
pipe = FluxPipeline.from_pretrained(
|
| 20 |
+
base_model,
|
| 21 |
+
torch_dtype=torch.bfloat16,
|
| 22 |
+
).to(device)
|
| 23 |
+
|
| 24 |
+
if lora_path:
|
| 25 |
+
print(f"Loading LoRA from {lora_path}...")
|
| 26 |
+
pipe.transformer = PeftModel.from_pretrained(pipe.transformer, lora_path)
|
| 27 |
+
|
| 28 |
+
return pipe
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def load_sr_model(checkpoint_path, base_channels=64, device="cuda:1"):
|
| 32 |
+
print(f"Loading SR model from {checkpoint_path}...")
|
| 33 |
+
model = SRUNet(in_channels=3, out_channels=3, base_channels=base_channels, scale_factor=2)
|
| 34 |
+
state_dict = torch.load(checkpoint_path, map_location="cpu")
|
| 35 |
+
model.load_state_dict(state_dict)
|
| 36 |
+
model = model.to(device, dtype=torch.bfloat16)
|
| 37 |
+
model.eval()
|
| 38 |
+
return model
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def image_to_tensor(image, device):
|
| 42 |
+
from torchvision import transforms
|
| 43 |
+
transform = transforms.Compose([
|
| 44 |
+
transforms.ToTensor(),
|
| 45 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 46 |
+
])
|
| 47 |
+
return transform(image).unsqueeze(0).to(device, dtype=torch.bfloat16)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def tensor_to_image(tensor):
|
| 51 |
+
tensor = tensor.squeeze(0).float().cpu()
|
| 52 |
+
tensor = tensor * 0.5 + 0.5
|
| 53 |
+
tensor = tensor.clamp(0, 1)
|
| 54 |
+
from torchvision.transforms.functional import to_pil_image
|
| 55 |
+
return to_pil_image(tensor)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@torch.no_grad()
|
| 59 |
+
def generate_4k(prompt, flux_pipe, sr_stage2, sr_stage3, output_path, num_inference_steps=28, guidance_scale=3.5):
|
| 60 |
+
print(f"\nGenerating: '{prompt}'")
|
| 61 |
+
t0 = time.time()
|
| 62 |
+
|
| 63 |
+
# Stage 1: Generate 1024px with Flux
|
| 64 |
+
print(" Stage 1: Generating 1024px...")
|
| 65 |
+
image_1k = flux_pipe(
|
| 66 |
+
prompt=prompt,
|
| 67 |
+
num_inference_steps=num_inference_steps,
|
| 68 |
+
guidance_scale=guidance_scale,
|
| 69 |
+
width=1024,
|
| 70 |
+
height=1024,
|
| 71 |
+
).images[0]
|
| 72 |
+
t1 = time.time()
|
| 73 |
+
print(f" Done in {t1-t0:.1f}s")
|
| 74 |
+
|
| 75 |
+
# Stage 2: Upscale 1K → 2K
|
| 76 |
+
print(" Stage 2: Upscaling to 2K...")
|
| 77 |
+
device_sr = next(sr_stage2.parameters()).device
|
| 78 |
+
input_tensor = image_to_tensor(image_1k, device_sr)
|
| 79 |
+
output_2k = sr_stage2(input_tensor)
|
| 80 |
+
image_2k = tensor_to_image(output_2k)
|
| 81 |
+
t2 = time.time()
|
| 82 |
+
print(f" Done in {t2-t1:.1f}s ({image_2k.size[0]}x{image_2k.size[1]})")
|
| 83 |
+
|
| 84 |
+
# Stage 3: Upscale 2K → 4K
|
| 85 |
+
print(" Stage 3: Upscaling to 4K...")
|
| 86 |
+
input_tensor = image_to_tensor(image_2k, device_sr)
|
| 87 |
+
output_4k = sr_stage3(input_tensor)
|
| 88 |
+
image_4k = tensor_to_image(output_4k)
|
| 89 |
+
t3 = time.time()
|
| 90 |
+
print(f" Done in {t3-t2:.1f}s ({image_4k.size[0]}x{image_4k.size[1]})")
|
| 91 |
+
|
| 92 |
+
# Save all stages
|
| 93 |
+
output_path = Path(output_path)
|
| 94 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
stem = prompt[:50].replace(" ", "_").replace("/", "_")
|
| 97 |
+
image_1k.save(output_path / f"{stem}_1k.png")
|
| 98 |
+
image_2k.save(output_path / f"{stem}_2k.png")
|
| 99 |
+
image_4k.save(output_path / f"{stem}_4k.png")
|
| 100 |
+
|
| 101 |
+
print(f"\n Total time: {t3-t0:.1f}s")
|
| 102 |
+
print(f" Saved to: {output_path}")
|
| 103 |
+
|
| 104 |
+
return image_4k
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
parser = argparse.ArgumentParser(description="Generate 4K images")
|
| 109 |
+
parser.add_argument("--prompt", required=True, help="Text prompt")
|
| 110 |
+
parser.add_argument("--flux-model", default="black-forest-labs/FLUX.1-schnell")
|
| 111 |
+
parser.add_argument("--lora-path", type=Path, default=None)
|
| 112 |
+
parser.add_argument("--sr-stage2", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/sr_stage2/final/model.pt"))
|
| 113 |
+
parser.add_argument("--sr-stage3", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/sr_stage3/final/model.pt"))
|
| 114 |
+
parser.add_argument("--output-dir", type=Path, default=Path("/home/adminuser/chungcat/outputs"))
|
| 115 |
+
parser.add_argument("--steps", type=int, default=28)
|
| 116 |
+
parser.add_argument("--guidance-scale", type=float, default=3.5)
|
| 117 |
+
parser.add_argument("--flux-device", default="cuda:0")
|
| 118 |
+
parser.add_argument("--sr-device", default="cuda:1")
|
| 119 |
+
args = parser.parse_args()
|
| 120 |
+
|
| 121 |
+
# Load models
|
| 122 |
+
flux_pipe = load_flux_pipeline(args.flux_model, args.lora_path, args.flux_device)
|
| 123 |
+
sr_stage2 = load_sr_model(args.sr_stage2, device=args.sr_device)
|
| 124 |
+
sr_stage3 = load_sr_model(args.sr_stage3, device=args.sr_device)
|
| 125 |
+
|
| 126 |
+
# Generate
|
| 127 |
+
generate_4k(
|
| 128 |
+
args.prompt, flux_pipe, sr_stage2, sr_stage3,
|
| 129 |
+
args.output_dir, args.steps, args.guidance_scale,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if __name__ == "__main__":
|
| 134 |
+
main()
|
scripts/training/run_train_flux.sh
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Launch Flux LoRA training on 2x H100
|
| 3 |
+
# Usage: bash scripts/training/run_train_flux.sh
|
| 4 |
+
|
| 5 |
+
export PYTHONPATH="/home/adminuser/chungcat:$PYTHONPATH"
|
| 6 |
+
export TORCH_DISTRIBUTED_DEBUG=DETAIL
|
| 7 |
+
|
| 8 |
+
accelerate launch \
|
| 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 4 \
|
| 17 |
+
--learning-rate 1e-4 \
|
| 18 |
+
--lr-scheduler cosine \
|
| 19 |
+
--lr-warmup-steps 500 \
|
| 20 |
+
--max-train-steps 100000 \
|
| 21 |
+
--save-steps 5000 \
|
| 22 |
+
--lora-rank 128 \
|
| 23 |
+
--lora-alpha 128 \
|
| 24 |
+
--mixed-precision bf16 \
|
| 25 |
+
--seed 42
|
scripts/training/run_train_sr_stage2.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Launch SR Stage 2 training (1K → 2K)
|
| 3 |
+
# Usage: bash scripts/training/run_train_sr_stage2.sh
|
| 4 |
+
|
| 5 |
+
export PYTHONPATH="/home/adminuser/chungcat:$PYTHONPATH"
|
| 6 |
+
|
| 7 |
+
accelerate launch \
|
| 8 |
+
--config_file /home/adminuser/chungcat/configs/accelerate_config.yaml \
|
| 9 |
+
/home/adminuser/chungcat/scripts/training/train_sr.py \
|
| 10 |
+
--stage 2 \
|
| 11 |
+
--batch-size 4 \
|
| 12 |
+
--learning-rate 2e-4 \
|
| 13 |
+
--max-steps 200000 \
|
| 14 |
+
--save-steps 10000 \
|
| 15 |
+
--base-channels 64 \
|
| 16 |
+
--perceptual-weight 0.1
|
scripts/training/run_train_sr_stage3.sh
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
# Launch SR Stage 3 training (2K → 4K)
|
| 3 |
+
# Usage: bash scripts/training/run_train_sr_stage3.sh
|
| 4 |
+
|
| 5 |
+
export PYTHONPATH="/home/adminuser/chungcat:$PYTHONPATH"
|
| 6 |
+
|
| 7 |
+
accelerate launch \
|
| 8 |
+
--config_file /home/adminuser/chungcat/configs/accelerate_config.yaml \
|
| 9 |
+
/home/adminuser/chungcat/scripts/training/train_sr.py \
|
| 10 |
+
--stage 3 \
|
| 11 |
+
--batch-size 2 \
|
| 12 |
+
--learning-rate 1e-4 \
|
| 13 |
+
--max-steps 200000 \
|
| 14 |
+
--save-steps 10000 \
|
| 15 |
+
--base-channels 64 \
|
| 16 |
+
--perceptual-weight 0.1
|
scripts/training/train_flux_lora.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Fine-tune Flux model using LoRA on downloaded COYO dataset.
|
| 3 |
+
Uses diffusers + accelerate + DeepSpeed for multi-GPU training.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import math
|
| 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):
|
| 23 |
+
return transforms.Compose([
|
| 24 |
+
transforms.Resize(resolution, interpolation=transforms.InterpolationMode.LANCZOS),
|
| 25 |
+
transforms.CenterCrop(resolution),
|
| 26 |
+
transforms.ToTensor(),
|
| 27 |
+
transforms.Normalize([0.5], [0.5]),
|
| 28 |
+
])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_webdataset(data_dir, resolution=1024, batch_size=4):
|
| 32 |
+
transform = get_train_transforms(resolution)
|
| 33 |
+
|
| 34 |
+
def preprocess(sample):
|
| 35 |
+
image = sample["jpg"]
|
| 36 |
+
if isinstance(image, bytes):
|
| 37 |
+
import io
|
| 38 |
+
image = Image.open(io.BytesIO(image)).convert("RGB")
|
| 39 |
+
caption = sample["txt"]
|
| 40 |
+
if isinstance(caption, bytes):
|
| 41 |
+
caption = caption.decode("utf-8")
|
| 42 |
+
return {"image": transform(image), "caption": caption}
|
| 43 |
+
|
| 44 |
+
tar_files = sorted(Path(data_dir).glob("*.tar"))
|
| 45 |
+
if not tar_files:
|
| 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)
|
| 53 |
+
.batched(batch_size)
|
| 54 |
+
)
|
| 55 |
+
return dataset
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def main():
|
| 59 |
+
parser = argparse.ArgumentParser(description="Fine-tune Flux with LoRA")
|
| 60 |
+
parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-schnell")
|
| 61 |
+
parser.add_argument("--data-dir", type=Path, default=Path("/home/adminuser/chungcat/data/processed/flux_train/shards"))
|
| 62 |
+
parser.add_argument("--output-dir", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/flux_lora"))
|
| 63 |
+
parser.add_argument("--resolution", type=int, default=1024)
|
| 64 |
+
parser.add_argument("--batch-size", type=int, default=1)
|
| 65 |
+
parser.add_argument("--gradient-accumulation", type=int, default=4)
|
| 66 |
+
parser.add_argument("--learning-rate", type=float, default=1e-4)
|
| 67 |
+
parser.add_argument("--lr-scheduler", default="cosine")
|
| 68 |
+
parser.add_argument("--lr-warmup-steps", type=int, default=500)
|
| 69 |
+
parser.add_argument("--max-train-steps", type=int, default=100000)
|
| 70 |
+
parser.add_argument("--save-steps", type=int, default=5000)
|
| 71 |
+
parser.add_argument("--lora-rank", type=int, default=128)
|
| 72 |
+
parser.add_argument("--lora-alpha", type=int, default=128)
|
| 73 |
+
parser.add_argument("--mixed-precision", default="bf16")
|
| 74 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 75 |
+
parser.add_argument("--use-wandb", action="store_true")
|
| 76 |
+
parser.add_argument("--wandb-project", default="flux-finetune")
|
| 77 |
+
args = parser.parse_args()
|
| 78 |
+
|
| 79 |
+
# Setup accelerator
|
| 80 |
+
project_config = ProjectConfiguration(
|
| 81 |
+
project_dir=str(args.output_dir),
|
| 82 |
+
logging_dir=str(args.output_dir / "logs"),
|
| 83 |
+
)
|
| 84 |
+
accelerator = Accelerator(
|
| 85 |
+
mixed_precision=args.mixed_precision,
|
| 86 |
+
gradient_accumulation_steps=args.gradient_accumulation,
|
| 87 |
+
project_config=project_config,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if accelerator.is_main_process:
|
| 91 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 92 |
+
if args.use_wandb:
|
| 93 |
+
wandb.init(project=args.wandb_project, config=vars(args))
|
| 94 |
+
|
| 95 |
+
# Load model
|
| 96 |
+
print(f"Loading model: {args.model_name}")
|
| 97 |
+
pipe = FluxPipeline.from_pretrained(
|
| 98 |
+
args.model_name,
|
| 99 |
+
torch_dtype=torch.bfloat16,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
transformer = pipe.transformer
|
| 103 |
+
text_encoder = pipe.text_encoder
|
| 104 |
+
text_encoder_2 = pipe.text_encoder_2
|
| 105 |
+
tokenizer = pipe.tokenizer
|
| 106 |
+
tokenizer_2 = pipe.tokenizer_2
|
| 107 |
+
vae = pipe.vae
|
| 108 |
+
|
| 109 |
+
# Freeze everything except transformer
|
| 110 |
+
vae.requires_grad_(False)
|
| 111 |
+
text_encoder.requires_grad_(False)
|
| 112 |
+
text_encoder_2.requires_grad_(False)
|
| 113 |
+
|
| 114 |
+
# Apply LoRA to transformer
|
| 115 |
+
lora_config = LoraConfig(
|
| 116 |
+
r=args.lora_rank,
|
| 117 |
+
lora_alpha=args.lora_alpha,
|
| 118 |
+
target_modules=["to_q", "to_k", "to_v", "to_out.0", "proj_in", "proj_out"],
|
| 119 |
+
lora_dropout=0.05,
|
| 120 |
+
)
|
| 121 |
+
transformer = get_peft_model(transformer, lora_config)
|
| 122 |
+
transformer.print_trainable_parameters()
|
| 123 |
+
|
| 124 |
+
# Optimizer
|
| 125 |
+
optimizer = torch.optim.AdamW(
|
| 126 |
+
transformer.parameters(),
|
| 127 |
+
lr=args.learning_rate,
|
| 128 |
+
weight_decay=0.01,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# Learning rate scheduler
|
| 132 |
+
from diffusers.optimization import get_scheduler
|
| 133 |
+
lr_scheduler = get_scheduler(
|
| 134 |
+
args.lr_scheduler,
|
| 135 |
+
optimizer=optimizer,
|
| 136 |
+
num_warmup_steps=args.lr_warmup_steps,
|
| 137 |
+
num_training_steps=args.max_train_steps,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Dataset
|
| 141 |
+
print(f"Loading dataset from {args.data_dir}")
|
| 142 |
+
train_dataset = create_webdataset(args.data_dir, args.resolution, args.batch_size)
|
| 143 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 144 |
+
train_dataset, batch_size=None, num_workers=4, pin_memory=True
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# Prepare with accelerator
|
| 148 |
+
transformer, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 149 |
+
transformer, optimizer, train_dataloader, lr_scheduler
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
# Move frozen models to device
|
| 153 |
+
vae.to(accelerator.device, dtype=torch.bfloat16)
|
| 154 |
+
text_encoder.to(accelerator.device, dtype=torch.bfloat16)
|
| 155 |
+
text_encoder_2.to(accelerator.device, dtype=torch.bfloat16)
|
| 156 |
+
|
| 157 |
+
# Training loop
|
| 158 |
+
global_step = 0
|
| 159 |
+
print(f"Starting training for {args.max_train_steps} steps...")
|
| 160 |
+
|
| 161 |
+
transformer.train()
|
| 162 |
+
for batch in train_dataloader:
|
| 163 |
+
if global_step >= args.max_train_steps:
|
| 164 |
+
break
|
| 165 |
+
|
| 166 |
+
with accelerator.accumulate(transformer):
|
| 167 |
+
images = batch["image"].to(accelerator.device, dtype=torch.bfloat16)
|
| 168 |
+
captions = batch["caption"]
|
| 169 |
+
|
| 170 |
+
# Encode images to latents
|
| 171 |
+
with torch.no_grad():
|
| 172 |
+
latents = vae.encode(images).latent_dist.sample()
|
| 173 |
+
latents = (latents - vae.config.shift_factor) * vae.config.scaling_factor
|
| 174 |
+
|
| 175 |
+
# Encode text
|
| 176 |
+
with torch.no_grad():
|
| 177 |
+
text_input_ids = tokenizer(
|
| 178 |
+
captions, padding="max_length", max_length=77,
|
| 179 |
+
truncation=True, return_tensors="pt"
|
| 180 |
+
).input_ids.to(accelerator.device)
|
| 181 |
+
encoder_hidden_states = text_encoder(text_input_ids)[0]
|
| 182 |
+
|
| 183 |
+
text_input_ids_2 = tokenizer_2(
|
| 184 |
+
captions, padding="max_length", max_length=512,
|
| 185 |
+
truncation=True, return_tensors="pt"
|
| 186 |
+
).input_ids.to(accelerator.device)
|
| 187 |
+
pooled_prompt_embeds = text_encoder_2(text_input_ids_2)[0]
|
| 188 |
+
|
| 189 |
+
# Sample noise and timesteps
|
| 190 |
+
noise = torch.randn_like(latents)
|
| 191 |
+
timesteps = torch.randint(0, 1000, (latents.shape[0],), device=latents.device).long()
|
| 192 |
+
|
| 193 |
+
# Add noise to latents
|
| 194 |
+
noisy_latents = pipe.scheduler.add_noise(latents, noise, timesteps)
|
| 195 |
+
|
| 196 |
+
# Predict noise
|
| 197 |
+
model_pred = transformer(
|
| 198 |
+
hidden_states=noisy_latents,
|
| 199 |
+
timestep=timesteps,
|
| 200 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 201 |
+
pooled_projections=pooled_prompt_embeds,
|
| 202 |
+
return_dict=False,
|
| 203 |
+
)[0]
|
| 204 |
+
|
| 205 |
+
# Loss
|
| 206 |
+
loss = torch.nn.functional.mse_loss(model_pred, noise, reduction="mean")
|
| 207 |
+
|
| 208 |
+
accelerator.backward(loss)
|
| 209 |
+
if accelerator.sync_gradients:
|
| 210 |
+
accelerator.clip_grad_norm_(transformer.parameters(), 1.0)
|
| 211 |
+
optimizer.step()
|
| 212 |
+
lr_scheduler.step()
|
| 213 |
+
optimizer.zero_grad()
|
| 214 |
+
|
| 215 |
+
if accelerator.sync_gradients:
|
| 216 |
+
global_step += 1
|
| 217 |
+
|
| 218 |
+
if global_step % 100 == 0:
|
| 219 |
+
if accelerator.is_main_process:
|
| 220 |
+
print(f"Step {global_step}/{args.max_train_steps}, Loss: {loss.item():.4f}, LR: {lr_scheduler.get_last_lr()[0]:.2e}")
|
| 221 |
+
if args.use_wandb:
|
| 222 |
+
wandb.log({"loss": loss.item(), "lr": lr_scheduler.get_last_lr()[0], "step": global_step})
|
| 223 |
+
|
| 224 |
+
if global_step % args.save_steps == 0:
|
| 225 |
+
if accelerator.is_main_process:
|
| 226 |
+
save_path = args.output_dir / f"checkpoint-{global_step}"
|
| 227 |
+
accelerator.unwrap_model(transformer).save_pretrained(save_path)
|
| 228 |
+
print(f"Saved checkpoint to {save_path}")
|
| 229 |
+
|
| 230 |
+
# Save final model
|
| 231 |
+
if accelerator.is_main_process:
|
| 232 |
+
final_path = args.output_dir / "final"
|
| 233 |
+
accelerator.unwrap_model(transformer).save_pretrained(final_path)
|
| 234 |
+
print(f"Training complete! Final model saved to {final_path}")
|
| 235 |
+
if args.use_wandb:
|
| 236 |
+
wandb.finish()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == "__main__":
|
| 240 |
+
main()
|
scripts/training/train_sr.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Train Super-Resolution model (Stage 2: 1K→2K, Stage 3: 2K→4K).
|
| 3 |
+
Uses a diffusion-based SR approach similar to StableSR/SUPIR.
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from torch.utils.data import Dataset, DataLoader
|
| 12 |
+
from torchvision import transforms
|
| 13 |
+
from PIL import Image
|
| 14 |
+
from accelerate import Accelerator
|
| 15 |
+
from accelerate.utils import ProjectConfiguration
|
| 16 |
+
from tqdm import tqdm
|
| 17 |
+
import wandb
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SRDataset(Dataset):
|
| 21 |
+
def __init__(self, input_dir, target_dir, input_size, target_size):
|
| 22 |
+
self.input_dir = Path(input_dir)
|
| 23 |
+
self.target_dir = Path(target_dir)
|
| 24 |
+
self.input_size = input_size
|
| 25 |
+
self.target_size = target_size
|
| 26 |
+
|
| 27 |
+
self.input_files = sorted(self.input_dir.glob("*.png"))
|
| 28 |
+
self.target_files = sorted(self.target_dir.glob("*.png"))
|
| 29 |
+
|
| 30 |
+
# Match by filename
|
| 31 |
+
input_stems = {f.stem: f for f in self.input_files}
|
| 32 |
+
target_stems = {f.stem: f for f in self.target_files}
|
| 33 |
+
common = set(input_stems.keys()) & set(target_stems.keys())
|
| 34 |
+
|
| 35 |
+
self.pairs = [(input_stems[s], target_stems[s]) for s in sorted(common)]
|
| 36 |
+
print(f"Found {len(self.pairs)} image pairs")
|
| 37 |
+
|
| 38 |
+
self.input_transform = transforms.Compose([
|
| 39 |
+
transforms.Resize((input_size, input_size), interpolation=transforms.InterpolationMode.LANCZOS),
|
| 40 |
+
transforms.ToTensor(),
|
| 41 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 42 |
+
])
|
| 43 |
+
self.target_transform = transforms.Compose([
|
| 44 |
+
transforms.Resize((target_size, target_size), interpolation=transforms.InterpolationMode.LANCZOS),
|
| 45 |
+
transforms.ToTensor(),
|
| 46 |
+
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
def __len__(self):
|
| 50 |
+
return len(self.pairs)
|
| 51 |
+
|
| 52 |
+
def __getitem__(self, idx):
|
| 53 |
+
input_path, target_path = self.pairs[idx]
|
| 54 |
+
input_img = Image.open(input_path).convert("RGB")
|
| 55 |
+
target_img = Image.open(target_path).convert("RGB")
|
| 56 |
+
return {
|
| 57 |
+
"input": self.input_transform(input_img),
|
| 58 |
+
"target": self.target_transform(target_img),
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class ResidualBlock(nn.Module):
|
| 63 |
+
def __init__(self, channels):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.conv1 = nn.Conv2d(channels, channels, 3, padding=1)
|
| 66 |
+
self.conv2 = nn.Conv2d(channels, channels, 3, padding=1)
|
| 67 |
+
self.norm1 = nn.GroupNorm(8, channels)
|
| 68 |
+
self.norm2 = nn.GroupNorm(8, channels)
|
| 69 |
+
|
| 70 |
+
def forward(self, x):
|
| 71 |
+
residual = x
|
| 72 |
+
x = F.silu(self.norm1(self.conv1(x)))
|
| 73 |
+
x = self.norm2(self.conv2(x))
|
| 74 |
+
return x + residual
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class SRUNet(nn.Module):
|
| 78 |
+
"""Simple U-Net based super-resolution model."""
|
| 79 |
+
def __init__(self, in_channels=3, out_channels=3, base_channels=64, scale_factor=2):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.scale_factor = scale_factor
|
| 82 |
+
|
| 83 |
+
# Encoder
|
| 84 |
+
self.enc1 = nn.Sequential(
|
| 85 |
+
nn.Conv2d(in_channels, base_channels, 3, padding=1),
|
| 86 |
+
ResidualBlock(base_channels),
|
| 87 |
+
ResidualBlock(base_channels),
|
| 88 |
+
)
|
| 89 |
+
self.enc2 = nn.Sequential(
|
| 90 |
+
nn.Conv2d(base_channels, base_channels * 2, 3, stride=2, padding=1),
|
| 91 |
+
ResidualBlock(base_channels * 2),
|
| 92 |
+
ResidualBlock(base_channels * 2),
|
| 93 |
+
)
|
| 94 |
+
self.enc3 = nn.Sequential(
|
| 95 |
+
nn.Conv2d(base_channels * 2, base_channels * 4, 3, stride=2, padding=1),
|
| 96 |
+
ResidualBlock(base_channels * 4),
|
| 97 |
+
ResidualBlock(base_channels * 4),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# Bottleneck
|
| 101 |
+
self.bottleneck = nn.Sequential(
|
| 102 |
+
ResidualBlock(base_channels * 4),
|
| 103 |
+
ResidualBlock(base_channels * 4),
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Decoder
|
| 107 |
+
self.dec3 = nn.Sequential(
|
| 108 |
+
nn.ConvTranspose2d(base_channels * 4, base_channels * 2, 4, stride=2, padding=1),
|
| 109 |
+
ResidualBlock(base_channels * 2),
|
| 110 |
+
ResidualBlock(base_channels * 2),
|
| 111 |
+
)
|
| 112 |
+
self.dec2 = nn.Sequential(
|
| 113 |
+
nn.ConvTranspose2d(base_channels * 4, base_channels, 4, stride=2, padding=1),
|
| 114 |
+
ResidualBlock(base_channels),
|
| 115 |
+
ResidualBlock(base_channels),
|
| 116 |
+
)
|
| 117 |
+
self.dec1 = nn.Sequential(
|
| 118 |
+
ResidualBlock(base_channels * 2),
|
| 119 |
+
ResidualBlock(base_channels),
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# Upscale + output
|
| 123 |
+
self.upscale = nn.Sequential(
|
| 124 |
+
nn.Conv2d(base_channels, base_channels * (scale_factor ** 2), 3, padding=1),
|
| 125 |
+
nn.PixelShuffle(scale_factor),
|
| 126 |
+
nn.Conv2d(base_channels, out_channels, 3, padding=1),
|
| 127 |
+
nn.Tanh(),
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def forward(self, x):
|
| 131 |
+
# Encoder
|
| 132 |
+
e1 = self.enc1(x)
|
| 133 |
+
e2 = self.enc2(e1)
|
| 134 |
+
e3 = self.enc3(e2)
|
| 135 |
+
|
| 136 |
+
# Bottleneck
|
| 137 |
+
b = self.bottleneck(e3)
|
| 138 |
+
|
| 139 |
+
# Decoder with skip connections
|
| 140 |
+
d3 = self.dec3(b)
|
| 141 |
+
d3 = torch.cat([d3, e2], dim=1)
|
| 142 |
+
d2 = self.dec2(d3)
|
| 143 |
+
d2 = torch.cat([d2, e1], dim=1)
|
| 144 |
+
d1 = self.dec1(d2)
|
| 145 |
+
|
| 146 |
+
# Upscale
|
| 147 |
+
out = self.upscale(d1)
|
| 148 |
+
return out
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class PerceptualLoss(nn.Module):
|
| 152 |
+
"""VGG-based perceptual loss."""
|
| 153 |
+
def __init__(self):
|
| 154 |
+
super().__init__()
|
| 155 |
+
from torchvision.models import vgg19, VGG19_Weights
|
| 156 |
+
vgg = vgg19(weights=VGG19_Weights.DEFAULT).features
|
| 157 |
+
self.blocks = nn.ModuleList([
|
| 158 |
+
vgg[:4], # relu1_2
|
| 159 |
+
vgg[4:9], # relu2_2
|
| 160 |
+
vgg[9:18], # relu3_4
|
| 161 |
+
])
|
| 162 |
+
for p in self.parameters():
|
| 163 |
+
p.requires_grad = False
|
| 164 |
+
|
| 165 |
+
def forward(self, x, target):
|
| 166 |
+
loss = 0.0
|
| 167 |
+
for block in self.blocks:
|
| 168 |
+
x = block(x)
|
| 169 |
+
with torch.no_grad():
|
| 170 |
+
target = block(target)
|
| 171 |
+
loss += F.l1_loss(x, target)
|
| 172 |
+
return loss
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def main():
|
| 176 |
+
parser = argparse.ArgumentParser(description="Train SR model")
|
| 177 |
+
parser.add_argument("--stage", type=int, choices=[2, 3], required=True, help="Stage 2 (1K→2K) or Stage 3 (2K→4K)")
|
| 178 |
+
parser.add_argument("--input-dir", type=Path, default=None)
|
| 179 |
+
parser.add_argument("--target-dir", type=Path, default=None)
|
| 180 |
+
parser.add_argument("--output-dir", type=Path, default=None)
|
| 181 |
+
parser.add_argument("--batch-size", type=int, default=4)
|
| 182 |
+
parser.add_argument("--learning-rate", type=float, default=2e-4)
|
| 183 |
+
parser.add_argument("--max-steps", type=int, default=200000)
|
| 184 |
+
parser.add_argument("--save-steps", type=int, default=10000)
|
| 185 |
+
parser.add_argument("--base-channels", type=int, default=64)
|
| 186 |
+
parser.add_argument("--perceptual-weight", type=float, default=0.1)
|
| 187 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 188 |
+
parser.add_argument("--use-wandb", action="store_true")
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
|
| 191 |
+
# Set defaults based on stage
|
| 192 |
+
sr_pairs_dir = Path("/home/adminuser/chungcat/data/processed/sr_pairs")
|
| 193 |
+
if args.stage == 2:
|
| 194 |
+
args.input_dir = args.input_dir or sr_pairs_dir / "1k_input"
|
| 195 |
+
args.target_dir = args.target_dir or sr_pairs_dir / "2k_target"
|
| 196 |
+
args.output_dir = args.output_dir or Path("/home/adminuser/chungcat/checkpoints/sr_stage2")
|
| 197 |
+
input_size, target_size = 1024, 2048
|
| 198 |
+
else:
|
| 199 |
+
args.input_dir = args.input_dir or sr_pairs_dir / "2k_input"
|
| 200 |
+
args.target_dir = args.target_dir or sr_pairs_dir / "4k_target"
|
| 201 |
+
args.output_dir = args.output_dir or Path("/home/adminuser/chungcat/checkpoints/sr_stage3")
|
| 202 |
+
input_size, target_size = 2048, 4096
|
| 203 |
+
|
| 204 |
+
# Accelerator
|
| 205 |
+
project_config = ProjectConfiguration(project_dir=str(args.output_dir))
|
| 206 |
+
accelerator = Accelerator(
|
| 207 |
+
mixed_precision="bf16",
|
| 208 |
+
project_config=project_config,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
if accelerator.is_main_process:
|
| 212 |
+
args.output_dir.mkdir(parents=True, exist_ok=True)
|
| 213 |
+
if args.use_wandb:
|
| 214 |
+
wandb.init(project=f"sr-stage{args.stage}", config=vars(args))
|
| 215 |
+
|
| 216 |
+
# Model
|
| 217 |
+
model = SRUNet(
|
| 218 |
+
in_channels=3,
|
| 219 |
+
out_channels=3,
|
| 220 |
+
base_channels=args.base_channels,
|
| 221 |
+
scale_factor=2,
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Losses
|
| 225 |
+
l1_loss = nn.L1Loss()
|
| 226 |
+
perceptual_loss = PerceptualLoss()
|
| 227 |
+
|
| 228 |
+
# Optimizer
|
| 229 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=0.01)
|
| 230 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.max_steps)
|
| 231 |
+
|
| 232 |
+
# Dataset
|
| 233 |
+
dataset = SRDataset(args.input_dir, args.target_dir, input_size, target_size)
|
| 234 |
+
dataloader = DataLoader(
|
| 235 |
+
dataset, batch_size=args.batch_size, shuffle=True,
|
| 236 |
+
num_workers=8, pin_memory=True, drop_last=True,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
# Prepare
|
| 240 |
+
model, optimizer, dataloader, scheduler = accelerator.prepare(
|
| 241 |
+
model, optimizer, dataloader, scheduler
|
| 242 |
+
)
|
| 243 |
+
perceptual_loss.to(accelerator.device)
|
| 244 |
+
|
| 245 |
+
# Training
|
| 246 |
+
global_step = 0
|
| 247 |
+
print(f"Starting SR Stage {args.stage} training...")
|
| 248 |
+
print(f" Input: {input_size}px → Target: {target_size}px")
|
| 249 |
+
print(f" Dataset: {len(dataset)} pairs")
|
| 250 |
+
print(f" Max steps: {args.max_steps}")
|
| 251 |
+
|
| 252 |
+
model.train()
|
| 253 |
+
while global_step < args.max_steps:
|
| 254 |
+
for batch in dataloader:
|
| 255 |
+
if global_step >= args.max_steps:
|
| 256 |
+
break
|
| 257 |
+
|
| 258 |
+
input_imgs = batch["input"]
|
| 259 |
+
target_imgs = batch["target"]
|
| 260 |
+
|
| 261 |
+
# Forward
|
| 262 |
+
pred = model(input_imgs)
|
| 263 |
+
|
| 264 |
+
# Resize pred to match target if needed
|
| 265 |
+
if pred.shape != target_imgs.shape:
|
| 266 |
+
pred = F.interpolate(pred, size=target_imgs.shape[2:], mode="bilinear", align_corners=False)
|
| 267 |
+
|
| 268 |
+
# Losses
|
| 269 |
+
loss_l1 = l1_loss(pred, target_imgs)
|
| 270 |
+
loss_perceptual = perceptual_loss(pred, target_imgs)
|
| 271 |
+
loss = loss_l1 + args.perceptual_weight * loss_perceptual
|
| 272 |
+
|
| 273 |
+
# Backward
|
| 274 |
+
accelerator.backward(loss)
|
| 275 |
+
optimizer.step()
|
| 276 |
+
scheduler.step()
|
| 277 |
+
optimizer.zero_grad()
|
| 278 |
+
|
| 279 |
+
global_step += 1
|
| 280 |
+
|
| 281 |
+
if global_step % 100 == 0 and accelerator.is_main_process:
|
| 282 |
+
print(f"Step {global_step}/{args.max_steps} | L1: {loss_l1.item():.4f} | Perceptual: {loss_perceptual.item():.4f} | Total: {loss.item():.4f}")
|
| 283 |
+
if args.use_wandb:
|
| 284 |
+
wandb.log({
|
| 285 |
+
"loss_l1": loss_l1.item(),
|
| 286 |
+
"loss_perceptual": loss_perceptual.item(),
|
| 287 |
+
"loss_total": loss.item(),
|
| 288 |
+
"lr": scheduler.get_last_lr()[0],
|
| 289 |
+
"step": global_step,
|
| 290 |
+
})
|
| 291 |
+
|
| 292 |
+
if global_step % args.save_steps == 0 and accelerator.is_main_process:
|
| 293 |
+
save_path = args.output_dir / f"checkpoint-{global_step}"
|
| 294 |
+
save_path.mkdir(parents=True, exist_ok=True)
|
| 295 |
+
torch.save(
|
| 296 |
+
accelerator.unwrap_model(model).state_dict(),
|
| 297 |
+
save_path / "model.pt",
|
| 298 |
+
)
|
| 299 |
+
print(f"Saved checkpoint: {save_path}")
|
| 300 |
+
|
| 301 |
+
# Save final
|
| 302 |
+
if accelerator.is_main_process:
|
| 303 |
+
final_path = args.output_dir / "final"
|
| 304 |
+
final_path.mkdir(parents=True, exist_ok=True)
|
| 305 |
+
torch.save(
|
| 306 |
+
accelerator.unwrap_model(model).state_dict(),
|
| 307 |
+
final_path / "model.pt",
|
| 308 |
+
)
|
| 309 |
+
print(f"Training complete! Model saved to {final_path}")
|
| 310 |
+
if args.use_wandb:
|
| 311 |
+
wandb.finish()
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
if __name__ == "__main__":
|
| 315 |
+
main()
|