2023-02-19 05:45:37 +08:00
|
|
|
from pathlib import Path
|
2020-12-13 09:58:04 +08:00
|
|
|
import numpy as np
|
2023-02-19 05:45:37 +08:00
|
|
|
from tqdm import trange
|
2023-02-11 02:09:37 +08:00
|
|
|
import torch
|
|
|
|
from torchvision.utils import make_grid, save_image
|
2023-01-30 13:30:47 +08:00
|
|
|
from tinygrad.tensor import Tensor
|
2023-02-01 07:09:09 +08:00
|
|
|
from tinygrad.helpers import getenv
|
2023-02-18 07:22:26 +08:00
|
|
|
from tinygrad.nn import optim
|
2023-01-30 13:30:47 +08:00
|
|
|
from datasets import fetch_mnist
|
2023-02-11 02:09:37 +08:00
|
|
|
|
2020-12-13 09:58:04 +08:00
|
|
|
class LinearGen:
|
|
|
|
def __init__(self):
|
2023-02-19 05:45:37 +08:00
|
|
|
self.l1 = Tensor.scaled_uniform(128, 256)
|
|
|
|
self.l2 = Tensor.scaled_uniform(256, 512)
|
|
|
|
self.l3 = Tensor.scaled_uniform(512, 1024)
|
|
|
|
self.l4 = Tensor.scaled_uniform(1024, 784)
|
2020-12-13 09:58:04 +08:00
|
|
|
|
|
|
|
def forward(self, x):
|
|
|
|
x = x.dot(self.l1).leakyrelu(0.2)
|
|
|
|
x = x.dot(self.l2).leakyrelu(0.2)
|
|
|
|
x = x.dot(self.l3).leakyrelu(0.2)
|
|
|
|
x = x.dot(self.l4).tanh()
|
|
|
|
return x
|
|
|
|
|
|
|
|
class LinearDisc:
|
|
|
|
def __init__(self):
|
2023-02-19 05:45:37 +08:00
|
|
|
self.l1 = Tensor.scaled_uniform(784, 1024)
|
|
|
|
self.l2 = Tensor.scaled_uniform(1024, 512)
|
|
|
|
self.l3 = Tensor.scaled_uniform(512, 256)
|
|
|
|
self.l4 = Tensor.scaled_uniform(256, 2)
|
2020-12-13 09:58:04 +08:00
|
|
|
|
2023-02-19 05:45:37 +08:00
|
|
|
def forward(self, x):
|
|
|
|
x = x.dot(self.l1).leakyrelu(0.2).dropout(0.3)
|
|
|
|
x = x.dot(self.l2).leakyrelu(0.2).dropout(0.3)
|
|
|
|
x = x.dot(self.l3).leakyrelu(0.2).dropout(0.3)
|
2023-02-25 02:11:24 +08:00
|
|
|
x = x.dot(self.l4).log_softmax()
|
2020-12-13 09:58:04 +08:00
|
|
|
return x
|
|
|
|
|
2023-02-19 05:45:37 +08:00
|
|
|
def make_batch(images):
|
|
|
|
sample = np.random.randint(0, len(images), size=(batch_size))
|
|
|
|
image_b = images[sample].reshape(-1, 28*28).astype(np.float32) / 255.0
|
|
|
|
image_b = (image_b - 0.5) / 0.5
|
|
|
|
return Tensor(image_b)
|
|
|
|
|
|
|
|
def make_labels(bs, val):
|
|
|
|
y = np.zeros((bs, 2), np.float32)
|
|
|
|
y[range(bs), [val] * bs] = -2.0 # Can we do label smoothin? i.e -2.0 changed to -1.98789.
|
|
|
|
return Tensor(y)
|
|
|
|
|
|
|
|
def train_discriminator(optimizer, data_real, data_fake):
|
|
|
|
real_labels = make_labels(batch_size, 1)
|
|
|
|
fake_labels = make_labels(batch_size, 0)
|
|
|
|
optimizer.zero_grad()
|
|
|
|
output_real = discriminator.forward(data_real)
|
|
|
|
output_fake = discriminator.forward(data_fake)
|
|
|
|
loss_real = (output_real * real_labels).mean()
|
|
|
|
loss_fake = (output_fake * fake_labels).mean()
|
|
|
|
loss_real.backward()
|
|
|
|
loss_fake.backward()
|
|
|
|
optimizer.step()
|
|
|
|
return (loss_real + loss_fake).cpu().numpy()
|
|
|
|
|
|
|
|
def train_generator(optimizer, data_fake):
|
|
|
|
real_labels = make_labels(batch_size, 1)
|
|
|
|
optimizer.zero_grad()
|
|
|
|
output = discriminator.forward(data_fake)
|
|
|
|
loss = (output * real_labels).mean()
|
|
|
|
loss.backward()
|
|
|
|
optimizer.step()
|
|
|
|
return loss.cpu().numpy()
|
|
|
|
|
2020-12-13 09:58:04 +08:00
|
|
|
if __name__ == "__main__":
|
2023-02-19 05:45:37 +08:00
|
|
|
# data for training and validation
|
|
|
|
images_real = np.vstack(fetch_mnist()[::2])
|
|
|
|
ds_noise = Tensor(np.random.randn(64, 128), requires_grad=False)
|
|
|
|
# parameters
|
|
|
|
epochs, batch_size, k = 300, 512, 1
|
|
|
|
sample_interval = epochs // 10
|
|
|
|
n_steps = len(images_real) // batch_size
|
|
|
|
# models and optimizer
|
2020-12-18 06:37:31 +08:00
|
|
|
generator = LinearGen()
|
|
|
|
discriminator = LinearDisc()
|
2023-02-19 05:45:37 +08:00
|
|
|
# path to store results
|
|
|
|
output_dir = Path(".").resolve() / "outputs"
|
|
|
|
output_dir.mkdir(exist_ok=True)
|
2020-12-18 06:37:31 +08:00
|
|
|
# optimizers
|
2023-02-19 05:45:37 +08:00
|
|
|
optim_g = optim.Adam(optim.get_parameters(generator),lr=0.0002, b1=0.5) # 0.0002 for equilibrium!
|
|
|
|
optim_d = optim.Adam(optim.get_parameters(discriminator),lr=0.0002, b1=0.5)
|
|
|
|
# training loop
|
|
|
|
for epoch in (t := trange(epochs)):
|
|
|
|
loss_g, loss_d = 0.0, 0.0
|
|
|
|
for _ in range(n_steps):
|
|
|
|
data_real = make_batch(images_real)
|
|
|
|
for step in range(k): # Try with k = 5 or 7.
|
2021-01-05 23:41:54 +08:00
|
|
|
noise = Tensor(np.random.randn(batch_size,128))
|
2020-12-18 06:37:31 +08:00
|
|
|
data_fake = generator.forward(noise).detach()
|
2023-02-19 05:45:37 +08:00
|
|
|
loss_d += train_discriminator(optim_d, data_real, data_fake)
|
2021-01-05 23:41:54 +08:00
|
|
|
noise = Tensor(np.random.randn(batch_size,128))
|
2020-12-18 06:37:31 +08:00
|
|
|
data_fake = generator.forward(noise)
|
2023-02-19 05:45:37 +08:00
|
|
|
loss_g += train_generator(optim_g, data_fake)
|
|
|
|
if (epoch + 1) % sample_interval == 0:
|
|
|
|
fake_images = generator.forward(ds_noise).detach().cpu().numpy()
|
|
|
|
fake_images = (fake_images.reshape(-1, 1, 28, 28) + 1) / 2 # 0 - 1 range.
|
|
|
|
save_image(make_grid(torch.tensor(fake_images)), output_dir / f"image_{epoch+1}.jpg")
|
|
|
|
t.set_description(f"Generator loss: {loss_g/n_steps}, Discriminator loss: {loss_d/n_steps}")
|
2023-02-11 02:09:37 +08:00
|
|
|
print("Training Completed!")
|