Skip to content
Snippets Groups Projects
01-DCGAN-PL.ipynb 13.5 KiB
Newer Older
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<img width=\"800px\" src=\"../fidle/img/header.svg\"></img>\n",
    "# <!-- TITLE --> [SHEEP3] - A DCGAN to Draw a Sheep, using Pytorch Lightning\n",
    "<!-- DESC --> \"Draw me a sheep\", revisited with a DCGAN, using Pytorch Lightning\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "<!-- AUTHOR : Jean-Luc Parouty (CNRS/SIMaP) -->\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "## Objectives :\n",
    " - Build and train a DCGAN model with the Quick Draw dataset\n",
    " - Understanding DCGAN\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "The [Quick draw dataset](https://quickdraw.withgoogle.com/data) contains about 50.000.000 drawings, made by real people...  \n",
    "We are using a subset of 117.555 of Sheep drawings  \n",
    "To get the dataset : [https://github.com/googlecreativelab/quickdraw-dataset](https://github.com/googlecreativelab/quickdraw-dataset)  \n",
    "Datasets in numpy bitmap file : [https://console.cloud.google.com/storage/quickdraw_dataset/full/numpy_bitmap](https://console.cloud.google.com/storage/quickdraw_dataset/full/numpy_bitmap)   \n",
    "Sheep dataset : [https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/sheep.npy](https://storage.googleapis.com/quickdraw_dataset/full/numpy_bitmap/sheep.npy) (94.3 Mo)\n",
    "\n",
    "\n",
    "## What we're going to do :\n",
    "\n",
    " - Have a look to the dataset\n",
    " - Defining a GAN model\n",
    " - Build the model\n",
    " - Train it\n",
    " - Have a look of the results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1 - Init and parameters\n",
    "#### Python init"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "import shutil\n",
    "\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "from lightning import LightningDataModule, LightningModule, Trainer\n",
    "from lightning.pytorch.callbacks.progress.tqdm_progress import TQDMProgressBar\n",
    "from lightning.pytorch.callbacks.progress.base          import ProgressBarBase\n",
    "from lightning.pytorch.callbacks                        import ModelCheckpoint\n",
    "from lightning.pytorch.loggers.tensorboard              import TensorBoardLogger\n",
    "\n",
    "from tqdm import tqdm\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "import fidle\n",
    "\n",
    "from modules.SmartProgressBar    import SmartProgressBar\n",
    "from modules.QuickDrawDataModule import QuickDrawDataModule\n",
    "\n",
    "from modules.GAN                 import GAN\n",
    "from modules.WGANGP              import WGANGP\n",
    "from modules.Generators          import *\n",
    "from modules.Discriminators      import *\n",
    "\n",
    "# Init Fidle environment\n",
    "run_id, run_dir, datasets_dir = fidle.init('SHEEP3')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Few parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "latent_dim          = 128\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "gan_class           = 'WGANGP'\n",
    "generator_class     = 'Generator_2'\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "discriminator_class = 'Discriminator_3'    \n",
    "scale               = 0.001\n",
Jean-Luc's avatar
Jean-Luc committed
    "epochs              = 3\n",
    "lr                  = 0.0001\n",
    "b1                  = 0.5\n",
    "b2                  = 0.999\n",
    "batch_size          = 32\n",
Jean-Luc's avatar
Jean-Luc committed
    "num_img             = 48\n",
    "fit_verbosity       = 2\n",
    "    \n",
    "dataset_file        = datasets_dir+'/QuickDraw/origine/sheep.npy' \n",
    "data_shape          = (28,28,1)"
   ]
  },
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Cleaning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# You can comment these lines to keep each run...\n",
    "shutil.rmtree(f'{run_dir}/figs', ignore_errors=True)\n",
    "shutil.rmtree(f'{run_dir}/models', ignore_errors=True)\n",
    "shutil.rmtree(f'{run_dir}/tb_logs', ignore_errors=True)"
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2 - Get some nice data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Get a Nice DataModule\n",
    "Our DataModule is defined in [./modules/QuickDrawDataModule.py](./modules/QuickDrawDataModule.py)   \n",
    "This is a [LightningDataModule](https://pytorch-lightning.readthedocs.io/en/stable/data/datamodule.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "dm = QuickDrawDataModule(dataset_file, scale, batch_size, num_workers=8)\n",
    "dm.setup()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Have a look"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dl         = dm.train_dataloader()\n",
    "batch_data = next(iter(dl))\n",
    "\n",
    "fidle.scrawler.images( batch_data.reshape(-1,28,28), indices=range(batch_size), columns=12, x_size=1, y_size=1, \n",
    "                       y_padding=0,spines_alpha=0, save_as='01-Sheeps')"
   ]
  },
  {
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3 - Get a nice GAN model\n",
    "\n",
    "Our Generators are defined in [./modules/Generators.py](./modules/Generators.py)  \n",
    "Our Discriminators are defined in [./modules/Discriminators.py](./modules/Discriminators.py)  \n",
    "\n",
    "\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "Our GAN is defined in [./modules/GAN.py](./modules/GAN.py)  \n",
    "\n",
    "#### Class loader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_class(class_name):\n",
    "    module=sys.modules['__main__']\n",
    "    class_    = getattr(module, class_name)\n",
    "    return class_\n",
    "    \n",
    "def get_instance(class_name, **args):\n",
    "    module=sys.modules['__main__']\n",
    "    class_    = getattr(module, class_name)\n",
    "    instance_ = class_(**args)\n",
    "    return instance_"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Basic test - Just to be sure it (could) works... ;-)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# ---- A little piece of black magic to instantiate a class from its name\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "#\n",
    "def get_classByName(class_name, **args):\n",
    "    module=sys.modules['__main__']\n",
    "    class_    = getattr(module, class_name)\n",
    "    instance_ = class_(**args)\n",
    "    return instance_\n",
    "\n",
    "# ----Get it, and play with them\n",
    "#\n",
    "print('\\nInstantiation :\\n')\n",
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "\n",
    "Generator_     = get_class(generator_class)\n",
    "Discriminator_ = get_class(discriminator_class)\n",
    "\n",
    "generator     = Generator_( latent_dim=latent_dim, data_shape=data_shape)\n",
    "discriminator = Discriminator_( latent_dim=latent_dim, data_shape=data_shape)\n",
    "\n",
    "print('\\nFew tests :\\n')\n",
    "z = torch.randn(batch_size, latent_dim)\n",
    "print('z size        : ',z.size())\n",
    "\n",
    "fake_img = generator.forward(z)\n",
    "print('fake_img      : ', fake_img.size())\n",
    "\n",
    "p = discriminator.forward(fake_img)\n",
    "print('pred fake     : ', p.size())\n",
    "\n",
    "print('batch_data    : ',batch_data.size())\n",
    "\n",
    "p = discriminator.forward(batch_data)\n",
    "print('pred real     : ', p.size())\n",
    "\n",
    "nimg = fake_img.detach().numpy()\n",
    "fidle.scrawler.images( nimg.reshape(-1,28,28), indices=range(batch_size), columns=12, x_size=1, y_size=1, \n",
    "                       y_padding=0,spines_alpha=0, save_as='01-Sheeps')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "print(fake_img.size())\n",
    "print(batch_data.size())\n",
    "e = torch.distributions.uniform.Uniform(0, 1).sample([32,1])\n",
    "e = e[:None,None,None]\n",
    "i = fake_img * e + (1-e)*batch_data\n",
    "\n",
    "\n",
    "nimg = i.detach().numpy()\n",
    "fidle.scrawler.images( nimg.reshape(-1,28,28), indices=range(batch_size), columns=12, x_size=1, y_size=1, \n",
    "                       y_padding=0,spines_alpha=0, save_as='01-Sheeps')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### GAN model\n",
    "To simplify our code, the GAN class is defined separately in the module [./modules/GAN.py](./modules/GAN.py)  \n",
    "Passing the classe names for generator/discriminator by parameter allows to stay modular and to use the PL checkpoints."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "GAN_           = get_class(gan_class)\n",
    "\n",
    "gan = GAN_( data_shape          = data_shape,\n",
    "            lr                  = lr,\n",
    "            b1                  = b1,\n",
    "            b2                  = b2,\n",
    "            batch_size          = batch_size, \n",
    "            latent_dim          = latent_dim, \n",
    "            generator_class     = generator_class, \n",
    "            discriminator_class = discriminator_class)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5 - Train it !\n",
    "#### Instantiate Callbacks, Logger & co.\n",
    "More about :\n",
    "- [Checkpoints](https://pytorch-lightning.readthedocs.io/en/stable/common/checkpointing_basic.html)\n",
    "- [modelCheckpoint](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.callbacks.ModelCheckpoint.html#pytorch_lightning.callbacks.ModelCheckpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "\n",
    "# ---- for tensorboard logs\n",
    "#\n",
    "logger       = TensorBoardLogger(       save_dir       = f'{run_dir}',\n",
    "                                        name           = 'tb_logs'  )\n",
    "\n",
    "log_dir = os.path.abspath(f'{run_dir}/tb_logs')\n",
    "print('To access the logs with tensorboard, use this command line :')\n",
    "print(f'tensorboard --logdir {log_dir}')\n",
    "\n",
    "# ---- To save checkpoints\n",
    "#\n",
    "callback_checkpoints = ModelCheckpoint( dirpath        = f'{run_dir}/models', \n",
    "                                        filename       = 'bestModel', \n",
    "                                        save_top_k     = 1, \n",
    "                                        save_last      = True,\n",
    "                                        every_n_epochs = 1, \n",
    "                                        monitor        = \"g_loss\")\n",
    "\n",
    "# ---- To have a nive progress bar\n",
    "#\n",
    "callback_progressBar = SmartProgressBar(verbosity=2)          # Usable evertywhere\n",
    "# progress_bar = TQDMProgressBar(refresh_rate=1)              # Usable in real jupyter lab (bug in vscode)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Train it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "\n",
    "trainer = Trainer(\n",
    "    accelerator        = \"auto\",\n",
    "    max_epochs         = epochs,\n",
    "    callbacks          = [callback_progressBar, callback_checkpoints],\n",
    "    log_every_n_steps  = batch_size,\n",
    "    logger             = logger\n",
    ")\n",
    "\n",
    "trainer.fit(gan, dm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
    "## Step 6 - Reload our best model\n",
    "Note : "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gan = WGANGP.load_from_checkpoint('./run/SHEEP3/models/bestModel.ckpt')"
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Jean-Luc's avatar
Jean-Luc committed
    "nb_images = 96\n",
    "\n",
    "z = torch.randn(nb_images, latent_dim)\n",
    "print('z size        : ',z.size())\n",
    "\n",
    "fake_img = gan.generator.forward(z)\n",
    "print('fake_img      : ', fake_img.size())\n",
    "\n",
    "nimg = fake_img.detach().numpy()\n",
    "fidle.scrawler.images( nimg.reshape(-1,28,28), indices=range(nb_images), columns=12, x_size=1, y_size=1, \n",
    "                       y_padding=0,spines_alpha=0, save_as='01-Sheeps')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
   "source": [
    "fidle.end()"
   ]
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
   "cell_type": "markdown",
   "metadata": {},
Jean-Luc Parouty's avatar
Jean-Luc Parouty committed
   "source": [
    "---\n",
    "<img width=\"80px\" src=\"../fidle/img/logo-paysage.svg\"></img>"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "fidle-env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}