Upload folder using huggingface_hub
Browse files- run.py +53 -0
- run_onnx.py +69 -0
- scrape.py +57 -0
- train.py +278 -0
- weights/checkpoint_latest.pth +3 -0
- weights/unface.onnx +3 -0
- weights/unface_fp16.onnx +3 -0
- weights/unface_int8.onnx +3 -0
run.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import random
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from contextlib import asynccontextmanager
|
| 6 |
+
from fastapi import FastAPI, HTTPException
|
| 7 |
+
from fastapi.responses import Response
|
| 8 |
+
from torchvision.utils import save_image
|
| 9 |
+
|
| 10 |
+
from train import FlowMatchingUNet, sample_images, DEVICE
|
| 11 |
+
|
| 12 |
+
model = FlowMatchingUNet()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def load_model():
|
| 16 |
+
ckpt = torch.load("weights/checkpoint_latest.pth", map_location="cpu", weights_only=True)
|
| 17 |
+
model.load_state_dict(ckpt["ema"])
|
| 18 |
+
model.to(DEVICE)
|
| 19 |
+
model.eval()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def generate_png(steps: int = 20) -> bytes:
|
| 23 |
+
"""Generate one image and return it as PNG bytes."""
|
| 24 |
+
with torch.no_grad():
|
| 25 |
+
samples = sample_images(model, num_samples=1, steps=steps)
|
| 26 |
+
big = F.interpolate(samples, scale_factor=2, mode="bicubic", align_corners=False)
|
| 27 |
+
big = big.clamp(0, 1)
|
| 28 |
+
buffer = io.BytesIO()
|
| 29 |
+
save_image(big.cpu(), buffer, format="png", nrow=1)
|
| 30 |
+
return buffer.getvalue()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@asynccontextmanager
|
| 34 |
+
async def lifespan(app: FastAPI):
|
| 35 |
+
load_model()
|
| 36 |
+
yield
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
app = FastAPI(lifespan=lifespan)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@app.get("/", response_class=Response)
|
| 43 |
+
async def get_image():
|
| 44 |
+
try:
|
| 45 |
+
png = generate_png()
|
| 46 |
+
except Exception as e:
|
| 47 |
+
raise HTTPException(status_code=500, detail=f"Generation failed: {e}")
|
| 48 |
+
return Response(content=png, media_type="image/png")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
if __name__ == "__main__":
|
| 52 |
+
import uvicorn
|
| 53 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
run_onnx.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import numpy as np
|
| 3 |
+
import onnxruntime as ort
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
from fastapi import FastAPI, HTTPException
|
| 6 |
+
from fastapi.responses import Response
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
IMAGE_SIZE = 64
|
| 10 |
+
CHANNELS = 3
|
| 11 |
+
MODEL_PATH = "weights/unface_fp16.onnx"
|
| 12 |
+
|
| 13 |
+
session = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def load_model():
|
| 17 |
+
global session
|
| 18 |
+
session = ort.InferenceSession(MODEL_PATH, providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sample_images(num_samples: int = 1, steps: int = 20, seed: int | None = None) -> np.ndarray:
|
| 22 |
+
rng = np.random.default_rng(seed)
|
| 23 |
+
x = rng.standard_normal((num_samples, CHANNELS, IMAGE_SIZE, IMAGE_SIZE)).astype(np.float32)
|
| 24 |
+
dt = 1.0 / steps
|
| 25 |
+
|
| 26 |
+
for step in range(steps):
|
| 27 |
+
t = np.full((num_samples,), step / steps, dtype=np.float32)
|
| 28 |
+
v = session.run(None, {"x": x, "t": t})[0]
|
| 29 |
+
x = np.clip(x + v * dt, -1.5, 1.5).astype(np.float32)
|
| 30 |
+
|
| 31 |
+
return np.clip(x, -1.0, 1.0)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def generate_png(steps: int = 20) -> bytes:
|
| 35 |
+
"""Generate one image and return it as PNG bytes."""
|
| 36 |
+
x = sample_images(num_samples=1, steps=steps)
|
| 37 |
+
# [-1, 1] -> [0, 255], HWC
|
| 38 |
+
img = ((x[0] + 1.0) / 2.0 * 255.0).round().clip(0, 255).astype(np.uint8)
|
| 39 |
+
img = img.transpose(1, 2, 0)
|
| 40 |
+
|
| 41 |
+
# 2x bicubic upscale, matching the original F.interpolate step
|
| 42 |
+
pil = Image.fromarray(img).resize((IMAGE_SIZE * 2, IMAGE_SIZE * 2), Image.BICUBIC)
|
| 43 |
+
|
| 44 |
+
buffer = io.BytesIO()
|
| 45 |
+
pil.save(buffer, format="PNG")
|
| 46 |
+
return buffer.getvalue()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@asynccontextmanager
|
| 50 |
+
async def lifespan(app: FastAPI):
|
| 51 |
+
load_model()
|
| 52 |
+
yield
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
app = FastAPI(lifespan=lifespan)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@app.get("/", response_class=Response)
|
| 59 |
+
async def get_image():
|
| 60 |
+
try:
|
| 61 |
+
png = generate_png()
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise HTTPException(status_code=500, detail=f"Generation failed: {e}")
|
| 64 |
+
return Response(content=png, media_type="image/png")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
if __name__ == "__main__":
|
| 68 |
+
import uvicorn
|
| 69 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
scrape.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import requests
|
| 4 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 5 |
+
|
| 6 |
+
# Directory where images will be saved
|
| 7 |
+
OUTPUT_DIR = os.path.join("data", "faces")
|
| 8 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 9 |
+
|
| 10 |
+
# URL serves a new face on every GET request
|
| 11 |
+
URL = "https://thispersondoesnotexist.com/random-person.jpeg"
|
| 12 |
+
|
| 13 |
+
# Set a standard User-Agent header to prevent requests from being blocked
|
| 14 |
+
HEADERS = {
|
| 15 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
NUM_IMAGES = 700
|
| 19 |
+
DELAY_SECONDS = 0.00 # Polite delay between requests per worker
|
| 20 |
+
NUM_WORKERS = 6
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def download_face(image_index: int) -> None:
|
| 24 |
+
"""Worker function to download a single face image."""
|
| 25 |
+
file_path = os.path.join(OUTPUT_DIR, f"face_{image_index:03d}.jpg")
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
response = requests.get(URL, headers=HEADERS, timeout=10)
|
| 29 |
+
|
| 30 |
+
if response.status_code == 200:
|
| 31 |
+
with open(file_path, "wb") as f:
|
| 32 |
+
f.write(response.content)
|
| 33 |
+
print(f"[{image_index}/{NUM_IMAGES}] Saved: {file_path}")
|
| 34 |
+
else:
|
| 35 |
+
print(
|
| 36 |
+
f"[{image_index}/{NUM_IMAGES}] Failed with status code: {response.status_code}"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"[{image_index}/{NUM_IMAGES}] Error: {e}")
|
| 41 |
+
|
| 42 |
+
time.sleep(DELAY_SECONDS)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main():
|
| 46 |
+
print(
|
| 47 |
+
f"Starting download of {NUM_IMAGES} faces using {NUM_WORKERS} workers..."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
with ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor:
|
| 51 |
+
executor.map(download_face, range(1, NUM_IMAGES + 1))
|
| 52 |
+
|
| 53 |
+
print("Download complete!")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
main()
|
train.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
import torch.optim as optim
|
| 7 |
+
from torchvision import datasets, transforms
|
| 8 |
+
from torchvision.utils import save_image
|
| 9 |
+
|
| 10 |
+
IMAGE_SIZE = 64
|
| 11 |
+
CHANNELS = 3
|
| 12 |
+
BATCH_SIZE = 64
|
| 13 |
+
EPOCHS = 1000
|
| 14 |
+
SAMPLE_STEPS = 20
|
| 15 |
+
LR = 2e-4
|
| 16 |
+
SAVE_EVERY = 10
|
| 17 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
+
|
| 19 |
+
CHECKPOINT_DIR = "weights"
|
| 20 |
+
OUTPUT_DIR = "outputs"
|
| 21 |
+
LATEST_CHECKPOINT = os.path.join(CHECKPOINT_DIR, "checkpoint_latest.pth")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# --- 1. EMA Helper ---
|
| 25 |
+
class EMA:
|
| 26 |
+
def __init__(self, model, decay=0.999):
|
| 27 |
+
self.decay = decay
|
| 28 |
+
self.shadow = {k: v.clone().detach() for k, v in model.state_dict().items()}
|
| 29 |
+
|
| 30 |
+
def update(self, model):
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
for k, v in model.state_dict().items():
|
| 33 |
+
self.shadow[k].data.mul_(self.decay).add_(v.data, alpha=1 - self.decay)
|
| 34 |
+
|
| 35 |
+
def apply_shadow(self, model):
|
| 36 |
+
self.backup = {k: v.clone().detach() for k, v in model.state_dict().items()}
|
| 37 |
+
model.load_state_dict(self.shadow)
|
| 38 |
+
|
| 39 |
+
def restore(self, model):
|
| 40 |
+
model.load_state_dict(self.backup)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# --- 2. Continuous Time Position Embeddings ---
|
| 44 |
+
class SinusoidalPositionEmbeddings(nn.Module):
|
| 45 |
+
def __init__(self, dim):
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.dim = dim
|
| 48 |
+
|
| 49 |
+
def forward(self, time):
|
| 50 |
+
device = time.device
|
| 51 |
+
half_dim = self.dim // 2
|
| 52 |
+
embeddings = math.log(10000) / (half_dim - 1)
|
| 53 |
+
embeddings = torch.exp(torch.arange(half_dim, device=device) * -embeddings)
|
| 54 |
+
embeddings = time[:, None] * embeddings[None, :]
|
| 55 |
+
embeddings = torch.cat((embeddings.sin(), embeddings.cos()), dim=-1)
|
| 56 |
+
return embeddings
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# --- 3. Residual Block with GroupNorm ---
|
| 60 |
+
class ResBlock(nn.Module):
|
| 61 |
+
def __init__(self, in_ch, out_ch, time_emb_dim):
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.time_mlp = nn.Linear(time_emb_dim, out_ch)
|
| 64 |
+
|
| 65 |
+
self.gn1 = nn.GroupNorm(8 if in_ch >= 8 else 1, in_ch)
|
| 66 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, padding=1)
|
| 67 |
+
|
| 68 |
+
self.gn2 = nn.GroupNorm(8 if out_ch >= 8 else 1, out_ch)
|
| 69 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1)
|
| 70 |
+
|
| 71 |
+
if in_ch != out_ch:
|
| 72 |
+
self.shortcut = nn.Conv2d(in_ch, out_ch, 1)
|
| 73 |
+
else:
|
| 74 |
+
self.shortcut = nn.Identity()
|
| 75 |
+
|
| 76 |
+
def forward(self, x, t_emb):
|
| 77 |
+
h = F.silu(self.gn1(x))
|
| 78 |
+
h = self.conv1(h)
|
| 79 |
+
|
| 80 |
+
# Add time conditioning
|
| 81 |
+
t_proj = F.silu(self.time_mlp(t_emb))[(..., None, None)]
|
| 82 |
+
h = h + t_proj
|
| 83 |
+
|
| 84 |
+
h = F.silu(self.gn2(h))
|
| 85 |
+
h = self.conv2(h)
|
| 86 |
+
|
| 87 |
+
return h + self.shortcut(x)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class FlowMatchingUNet(nn.Module):
|
| 91 |
+
def __init__(self, in_channels=CHANNELS, time_emb_dim=128):
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.time_mlp = nn.Sequential(
|
| 94 |
+
SinusoidalPositionEmbeddings(time_emb_dim),
|
| 95 |
+
nn.Linear(time_emb_dim, time_emb_dim),
|
| 96 |
+
nn.SiLU(),
|
| 97 |
+
nn.Linear(time_emb_dim, time_emb_dim),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
self.in_conv = nn.Conv2d(in_channels, 64, 3, padding=1)
|
| 101 |
+
|
| 102 |
+
# Downsampling path
|
| 103 |
+
self.down1 = ResBlock(64, 64, time_emb_dim)
|
| 104 |
+
self.down2_conv = nn.Conv2d(64, 128, 4, stride=2, padding=1)
|
| 105 |
+
self.down2 = ResBlock(128, 128, time_emb_dim)
|
| 106 |
+
|
| 107 |
+
self.down3_conv = nn.Conv2d(128, 256, 4, stride=2, padding=1)
|
| 108 |
+
self.down3 = ResBlock(256, 256, time_emb_dim)
|
| 109 |
+
|
| 110 |
+
# Bottleneck
|
| 111 |
+
self.bot1 = ResBlock(256, 256, time_emb_dim)
|
| 112 |
+
self.bot2 = ResBlock(256, 256, time_emb_dim)
|
| 113 |
+
|
| 114 |
+
# Upsampling path
|
| 115 |
+
self.up1_conv = nn.ConvTranspose2d(256, 128, 4, stride=2, padding=1)
|
| 116 |
+
self.up1 = ResBlock(256, 128, time_emb_dim)
|
| 117 |
+
|
| 118 |
+
self.up2_conv = nn.ConvTranspose2d(128, 64, 4, stride=2, padding=1)
|
| 119 |
+
self.up2 = ResBlock(128, 64, time_emb_dim)
|
| 120 |
+
|
| 121 |
+
self.out_gn = nn.GroupNorm(8, 64)
|
| 122 |
+
self.out_conv = nn.Conv2d(64, in_channels, 3, padding=1)
|
| 123 |
+
|
| 124 |
+
def forward(self, x, t):
|
| 125 |
+
t_emb = self.time_mlp(t)
|
| 126 |
+
|
| 127 |
+
x_in = self.in_conv(x)
|
| 128 |
+
|
| 129 |
+
# Downsample
|
| 130 |
+
x1 = self.down1(x_in, t_emb) # [B, 64, 64, 64]
|
| 131 |
+
x2 = self.down2(self.down2_conv(x1), t_emb) # [B, 128, 32, 32]
|
| 132 |
+
x3 = self.down3(self.down3_conv(x2), t_emb) # [B, 256, 16, 16]
|
| 133 |
+
|
| 134 |
+
# Bottleneck
|
| 135 |
+
h = self.bot1(x3, t_emb)
|
| 136 |
+
h = self.bot2(h, t_emb)
|
| 137 |
+
|
| 138 |
+
# Upsample with Skip Connections
|
| 139 |
+
h = self.up1_conv(h) # [B, 128, 32, 32]
|
| 140 |
+
h = self.up1(torch.cat([h, x2], dim=1), t_emb) # [B, 256, 32, 32] -> [B, 128, 32, 32]
|
| 141 |
+
|
| 142 |
+
h = self.up2_conv(h) # [B, 64, 64, 64]
|
| 143 |
+
h = self.up2(torch.cat([h, x1], dim=1), t_emb) # [B, 128, 64, 64] -> [B, 64, 64, 64]
|
| 144 |
+
|
| 145 |
+
h = F.silu(self.out_gn(h))
|
| 146 |
+
return self.out_conv(h)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
# --- 4. Euler ODE Sampler ---
|
| 150 |
+
@torch.no_grad()
|
| 151 |
+
def sample_images(model, num_samples=16, steps=SAMPLE_STEPS):
|
| 152 |
+
model.eval()
|
| 153 |
+
x_t = torch.randn(num_samples, CHANNELS, IMAGE_SIZE, IMAGE_SIZE, device=DEVICE)
|
| 154 |
+
dt = 1.0 / steps
|
| 155 |
+
|
| 156 |
+
for step in range(steps):
|
| 157 |
+
t_val = step / steps
|
| 158 |
+
t_batch = torch.full((num_samples,), t_val, device=DEVICE, dtype=torch.float32)
|
| 159 |
+
|
| 160 |
+
v_pred = model(x_t, t_batch)
|
| 161 |
+
x_t = x_t + v_pred * dt
|
| 162 |
+
|
| 163 |
+
# Step clamp to prevent trajectory drift
|
| 164 |
+
x_t = x_t.clamp(-1.5, 1.5)
|
| 165 |
+
|
| 166 |
+
return (x_t.clamp(-1.0, 1.0) + 1.0) / 2.0
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == '__main__':
|
| 170 |
+
if DEVICE.type == "cuda":
|
| 171 |
+
torch.backends.cudnn.benchmark = True
|
| 172 |
+
|
| 173 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 174 |
+
os.makedirs(CHECKPOINT_DIR, exist_ok=True)
|
| 175 |
+
|
| 176 |
+
transform = transforms.Compose([
|
| 177 |
+
transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
|
| 178 |
+
transforms.CenterCrop(IMAGE_SIZE),
|
| 179 |
+
transforms.RandomHorizontalFlip(p=0.5),
|
| 180 |
+
transforms.ToTensor(),
|
| 181 |
+
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
|
| 182 |
+
])
|
| 183 |
+
|
| 184 |
+
dataset = datasets.ImageFolder(root="data", transform=transform)
|
| 185 |
+
|
| 186 |
+
dataloader = torch.utils.data.DataLoader(
|
| 187 |
+
dataset,
|
| 188 |
+
batch_size=BATCH_SIZE,
|
| 189 |
+
shuffle=True,
|
| 190 |
+
drop_last=True,
|
| 191 |
+
num_workers=4 if os.cpu_count() >= 4 else 2,
|
| 192 |
+
pin_memory=True if DEVICE.type == "cuda" else False,
|
| 193 |
+
persistent_workers=True,
|
| 194 |
+
prefetch_factor=2
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
model = FlowMatchingUNet().to(DEVICE)
|
| 198 |
+
ema = EMA(model, decay=0.999)
|
| 199 |
+
optimizer = optim.AdamW(model.parameters(), lr=LR, weight_decay=1e-4)
|
| 200 |
+
scaler = torch.amp.GradScaler('cuda', enabled=(DEVICE.type == "cuda"))
|
| 201 |
+
|
| 202 |
+
start_epoch = 0
|
| 203 |
+
|
| 204 |
+
if os.path.exists(LATEST_CHECKPOINT):
|
| 205 |
+
print(f"Loading checkpoint from {LATEST_CHECKPOINT}...")
|
| 206 |
+
try:
|
| 207 |
+
ckpt = torch.load(LATEST_CHECKPOINT, map_location=DEVICE, weights_only=True)
|
| 208 |
+
model.load_state_dict(ckpt['model'])
|
| 209 |
+
optimizer.load_state_dict(ckpt['optimizer'])
|
| 210 |
+
scaler.load_state_dict(ckpt['scaler'])
|
| 211 |
+
if 'ema' in ckpt:
|
| 212 |
+
ema.shadow = ckpt['ema']
|
| 213 |
+
start_epoch = ckpt['epoch'] + 1
|
| 214 |
+
print(f"Resumed successfully at Epoch {start_epoch + 1}.")
|
| 215 |
+
except (KeyError, RuntimeError) as e:
|
| 216 |
+
print(f"Incompatible checkpoint detected ({e}). Starting fresh from Epoch 1...")
|
| 217 |
+
start_epoch = 0
|
| 218 |
+
|
| 219 |
+
print("Starting Flow Matching Training Loop...")
|
| 220 |
+
for epoch in range(start_epoch, EPOCHS):
|
| 221 |
+
model.train()
|
| 222 |
+
total_loss = 0.0
|
| 223 |
+
|
| 224 |
+
for i, (x1, _) in enumerate(dataloader):
|
| 225 |
+
x1 = x1.to(DEVICE, non_blocking=True)
|
| 226 |
+
b_size = x1.size(0)
|
| 227 |
+
|
| 228 |
+
x0 = torch.randn_like(x1)
|
| 229 |
+
t = torch.rand(b_size, device=DEVICE)
|
| 230 |
+
t_expanded = t[:, None, None, None]
|
| 231 |
+
|
| 232 |
+
x_t = (1.0 - t_expanded) * x0 + t_expanded * x1
|
| 233 |
+
v_target = x1 - x0
|
| 234 |
+
|
| 235 |
+
optimizer.zero_grad(set_to_none=True)
|
| 236 |
+
|
| 237 |
+
with torch.amp.autocast('cuda', enabled=(DEVICE.type == "cuda")):
|
| 238 |
+
v_pred = model(x_t, t)
|
| 239 |
+
loss = F.mse_loss(v_pred, v_target)
|
| 240 |
+
|
| 241 |
+
scaler.scale(loss).backward()
|
| 242 |
+
|
| 243 |
+
# Gradient clipping to prevent exploding velocity vectors
|
| 244 |
+
scaler.unscale_(optimizer)
|
| 245 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 246 |
+
|
| 247 |
+
scaler.step(optimizer)
|
| 248 |
+
scaler.update()
|
| 249 |
+
|
| 250 |
+
# Update EMA weights
|
| 251 |
+
ema.update(model)
|
| 252 |
+
|
| 253 |
+
total_loss += loss.item()
|
| 254 |
+
|
| 255 |
+
avg_loss = total_loss / len(dataloader)
|
| 256 |
+
|
| 257 |
+
if (epoch + 1) % SAVE_EVERY == 0 or (epoch + 1) == EPOCHS:
|
| 258 |
+
print(f"Epoch [{epoch+1}/{EPOCHS}] | Velocity MSE Loss: {avg_loss:.5f}")
|
| 259 |
+
|
| 260 |
+
# Sample using EMA weights
|
| 261 |
+
ema.apply_shadow(model)
|
| 262 |
+
samples = sample_images(model, num_samples=16, steps=SAMPLE_STEPS)
|
| 263 |
+
ema.restore(model)
|
| 264 |
+
|
| 265 |
+
save_image(samples, os.path.join(OUTPUT_DIR, f"epoch_{epoch+1:03d}.png"), nrow=4)
|
| 266 |
+
|
| 267 |
+
# Save state including EMA
|
| 268 |
+
checkpoint_data = {
|
| 269 |
+
'epoch': epoch,
|
| 270 |
+
'model': model.state_dict(),
|
| 271 |
+
'ema': ema.shadow,
|
| 272 |
+
'optimizer': optimizer.state_dict(),
|
| 273 |
+
'scaler': scaler.state_dict(),
|
| 274 |
+
}
|
| 275 |
+
torch.save(checkpoint_data, LATEST_CHECKPOINT)
|
| 276 |
+
torch.save(model.state_dict(), os.path.join(CHECKPOINT_DIR, f"model_epoch_{epoch+1:03d}.pth"))
|
| 277 |
+
|
| 278 |
+
print("Training finished.")
|
weights/checkpoint_latest.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:637a8add22dacea91bc6e1eb9b4baf189ec6a961a0a668015f09d1a505337260
|
| 3 |
+
size 96230266
|
weights/unface.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6c65910754c6cf62036d162385db792f342339f958f2f663d5a7daa214d02537
|
| 3 |
+
size 24057041
|
weights/unface_fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:83990b62833392449db10d1499a830d2750bb02121d3d7fb0bf6e6d6612c435f
|
| 3 |
+
size 12061463
|
weights/unface_int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b436419ea6a6f0153aa807e7a2cedbe7c4c9b788f5112ce29ba6f0590e74cb6
|
| 3 |
+
size 8083786
|