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2 |
+
"""Small DCGAN for 64x64 RGB company logos. GPU-enabled.
|
| 3 |
+
Loads /work/logos/logos64.npy (N,3,64,64) float32 in [0,1].
|
| 4 |
+
Usage: python3 train_gan_gpu.py [--steps 12000] [--batch 128] [--seed 7]
|
| 5 |
+
"""
|
| 6 |
+
import os, sys, argparse, time, random
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 11 |
+
from PIL import Image
|
| 12 |
+
|
| 13 |
+
OUT = "gan_out"; os.makedirs(OUT, exist_ok=True)
|
| 14 |
+
LATENT = 100
|
| 15 |
+
CH, SZ = 3, 64
|
| 16 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
+
|
| 18 |
+
def parse():
|
| 19 |
+
p = argparse.ArgumentParser()
|
| 20 |
+
p.add_argument("--steps", type=int, default=12000)
|
| 21 |
+
p.add_argument("--batch", type=int, default=128)
|
| 22 |
+
p.add_argument("--seed", type=int, default=7)
|
| 23 |
+
p.add_argument("--ckpt_every", type=int, default=2000)
|
| 24 |
+
return p.parse_args()
|
| 25 |
+
|
| 26 |
+
class G(nn.Module):
|
| 27 |
+
def __init__(self):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.fc = nn.Linear(LATENT, 512 * 8 * 8)
|
| 30 |
+
self.body = nn.Sequential(
|
| 31 |
+
nn.BatchNorm2d(512), nn.ReLU(inplace=True),
|
| 32 |
+
nn.ConvTranspose2d(512, 256, 4, 2, 1),
|
| 33 |
+
nn.BatchNorm2d(256), nn.ReLU(inplace=True),
|
| 34 |
+
nn.ConvTranspose2d(256, 128, 4, 2, 1),
|
| 35 |
+
nn.BatchNorm2d(128), nn.ReLU(inplace=True),
|
| 36 |
+
nn.ConvTranspose2d(128, 64, 4, 2, 1),
|
| 37 |
+
nn.BatchNorm2d(64), nn.ReLU(inplace=True),
|
| 38 |
+
nn.Conv2d(64, CH, 3, 1, 1),
|
| 39 |
+
nn.Tanh(),
|
| 40 |
+
)
|
| 41 |
+
def forward(self, z):
|
| 42 |
+
x = self.fc(z).view(-1, 512, 8, 8)
|
| 43 |
+
return self.body(x)
|
| 44 |
+
|
| 45 |
+
class D(nn.Module):
|
| 46 |
+
def __init__(self):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.body = nn.Sequential(
|
| 49 |
+
nn.Conv2d(CH, 64, 4, 2, 1), nn.LeakyReLU(0.2, inplace=True),
|
| 50 |
+
nn.Conv2d(64, 128, 4, 2, 1), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, inplace=True),
|
| 51 |
+
nn.Conv2d(128, 256, 4, 2, 1), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, inplace=True),
|
| 52 |
+
nn.Conv2d(256, 512, 4, 2, 1), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, inplace=True),
|
| 53 |
+
nn.Conv2d(512, 1, 4, 1),
|
| 54 |
+
)
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
return self.body(x).view(-1, 1)
|
| 57 |
+
|
| 58 |
+
def make_grid(imgs, ncols=8):
|
| 59 |
+
n = imgs.shape[0]
|
| 60 |
+
rows = (n + ncols - 1) // ncols
|
| 61 |
+
pad = np.zeros((rows * ncols, 3, SZ, SZ), dtype=np.float32) + 1.0
|
| 62 |
+
for i in range(n):
|
| 63 |
+
pad[i] = imgs[i]
|
| 64 |
+
tiles = []
|
| 65 |
+
for r in range(rows):
|
| 66 |
+
row = []
|
| 67 |
+
for c in range(ncols):
|
| 68 |
+
idx = r * ncols + c
|
| 69 |
+
if idx < n:
|
| 70 |
+
arr = (pad[idx] * 0.5 + 0.5).clip(0, 1)
|
| 71 |
+
row.append((arr.transpose(1, 2, 0) * 255).astype(np.uint8))
|
| 72 |
+
else:
|
| 73 |
+
row.append(np.full((SZ, SZ, 3), 255, dtype=np.uint8))
|
| 74 |
+
tiles.append(np.concatenate(row, axis=1))
|
| 75 |
+
return np.concatenate(tiles, axis=0)
|
| 76 |
+
|
| 77 |
+
def main():
|
| 78 |
+
a = parse()
|
| 79 |
+
torch.manual_seed(a.seed); np.random.seed(a.seed); random.seed(a.seed)
|
| 80 |
+
X = np.load("logos/logos64.npy")
|
| 81 |
+
print(f"device={DEVICE}")
|
| 82 |
+
print(f"data {X.shape} min={X.min():.3f} max={X.max():.3f} mean={X.mean():.3f}")
|
| 83 |
+
X = (X * 2.0 - 1.0).astype(np.float32)
|
| 84 |
+
ds = TensorDataset(torch.from_numpy(X))
|
| 85 |
+
dl = DataLoader(ds, batch_size=a.batch, shuffle=True, drop_last=True, num_workers=0)
|
| 86 |
+
|
| 87 |
+
gen = G().to(DEVICE); disc = D().to(DEVICE)
|
| 88 |
+
ng = sum(p.numel() for p in gen.parameters())
|
| 89 |
+
nd = sum(p.numel() for p in disc.parameters())
|
| 90 |
+
print(f"generator params {ng:,} discriminator params {nd:,} total {ng+nd:,}")
|
| 91 |
+
with open(os.path.join(OUT, "param_count.txt"), "w") as f:
|
| 92 |
+
f.write(f"generator={ng}\ndiscriminator={nd}\ntotal={ng+nd}\n")
|
| 93 |
+
|
| 94 |
+
opt_g = torch.optim.Adam(gen.parameters(), lr=2e-4, betas=(0.5, 0.999))
|
| 95 |
+
opt_d = torch.optim.Adam(disc.parameters(), lr=4e-5, betas=(0.5, 0.999))
|
| 96 |
+
bce = nn.BCEWithLogitsLoss()
|
| 97 |
+
|
| 98 |
+
fixed_z = torch.randn(64, LATENT, device=DEVICE)
|
| 99 |
+
step = 0
|
| 100 |
+
t0 = time.time()
|
| 101 |
+
for epoch in range(10_000):
|
| 102 |
+
for xb in dl:
|
| 103 |
+
xb = xb[0].to(DEVICE, non_blocking=True)
|
| 104 |
+
bs = xb.size(0)
|
| 105 |
+
real = xb
|
| 106 |
+
z = torch.randn(bs, LATENT, device=DEVICE)
|
| 107 |
+
fake = gen(z)
|
| 108 |
+
opt_d.zero_grad()
|
| 109 |
+
d_real = disc(real)
|
| 110 |
+
d_fake = disc(fake.detach())
|
| 111 |
+
# label smoothing: real=0.9, fake=0.1
|
| 112 |
+
real_t = torch.full_like(d_real, 0.9)
|
| 113 |
+
fake_t = torch.full_like(d_fake, 0.1)
|
| 114 |
+
loss_d = (bce(d_real, real_t) + bce(d_fake, fake_t)).mean()
|
| 115 |
+
# R1 gradient penalty (regularize D, prevents collapse)
|
| 116 |
+
inp = real.clone().requires_grad_(True)
|
| 117 |
+
out = disc(inp)
|
| 118 |
+
grads = torch.autograd.grad(outputs=out, inputs=inp,
|
| 119 |
+
grad_outputs=torch.ones_like(out),
|
| 120 |
+
create_graph=True, retain_graph=True)[0]
|
| 121 |
+
pen = (grads**2).sum(dim=[1,2,3]).mean()
|
| 122 |
+
loss_d = loss_d + 10.0 * pen
|
| 123 |
+
loss_d.backward(); opt_d.step()
|
| 124 |
+
opt_g.zero_grad()
|
| 125 |
+
loss_g = bce(disc(gen(z)), torch.ones(bs, 1, device=DEVICE)).mean()
|
| 126 |
+
loss_g.backward(); opt_g.step()
|
| 127 |
+
step += 1
|
| 128 |
+
if step % 200 == 0:
|
| 129 |
+
el = (time.time() - t0) / step
|
| 130 |
+
print(f"step {step} d={loss_d.item():.4f} g={loss_g.item():.4f} {el*1000:.0f}ms/step eta {el*(a.steps-step)/60:.1f}m", flush=True)
|
| 131 |
+
if step % a.ckpt_every == 0:
|
| 132 |
+
torch.save({"G": gen.state_dict(), "D": disc.state_dict(), "step": step},
|
| 133 |
+
os.path.join(OUT, f"ckpt_{step}.pt"))
|
| 134 |
+
if step >= a.ckpt_every:
|
| 135 |
+
gen.eval()
|
| 136 |
+
with torch.no_grad():
|
| 137 |
+
samp = gen(fixed_z).cpu().numpy()
|
| 138 |
+
grid = make_grid(samp)
|
| 139 |
+
Image.fromarray(grid).save(os.path.join(OUT, f"samples_{step}.png"))
|
| 140 |
+
gen.train()
|
| 141 |
+
print(f" saved ckpt_{step}.pt + samples_{step}.png", flush=True)
|
| 142 |
+
if step >= a.steps:
|
| 143 |
+
break
|
| 144 |
+
if step >= a.steps:
|
| 145 |
+
break
|
| 146 |
+
torch.save({"G": gen.state_dict(), "D": disc.state_dict(), "step": step}, os.path.join(OUT, "final.pt"))
|
| 147 |
+
gen.eval()
|
| 148 |
+
with torch.no_grad():
|
| 149 |
+
samp = gen(fixed_z).cpu().numpy()
|
| 150 |
+
Image.fromarray(make_grid(samp)).save(os.path.join(OUT, "samples_final.png"))
|
| 151 |
+
print(f"DONE step={step} elapsed {(time.time()-t0)/60:.1f}m", flush=True)
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|