diff --git "a/research/model_trainer.ipynb" "b/research/model_trainer.ipynb" new file mode 100644--- /dev/null +++ "b/research/model_trainer.ipynb" @@ -0,0 +1,487 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "os.chdir('../')" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'c:\\\\mlops project\\\\image-colorization-mlops'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "%pwd" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Assuming all necessary imports are here\n", + "from dataclasses import dataclass\n", + "from pathlib import Path\n", + "\n", + "@dataclass(frozen=True)\n", + "class ModelTrainerConfig:\n", + " root_dir: Path\n", + " test_data_path: Path\n", + " train_data_path: Path\n", + " LEARNING_RATE: float\n", + " LAMBDA_RECON: int\n", + " DISPLAY_STEP: int\n", + " IMAGE_SIZE: list\n", + " INPUT_CHANNELS: int\n", + " OUTPUT_CHANNELS: int\n", + " EPOCH: int\n", + " BATCH_SIZE : int" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "from src.imagecolorization.constants import *\n", + "from src.imagecolorization.utils.common import read_yaml, create_directories\n", + "\n", + "class ConfigurationManager:\n", + " def __init__(self, config_filepath=CONFIG_FILE_PATH, params_filepath=PARAMS_FILE_PATH):\n", + " self.config = read_yaml(config_filepath)\n", + " self.params = read_yaml(params_filepath)\n", + " create_directories([self.config.artifacts_root])\n", + "\n", + " def get_model_trainer_config(self) -> ModelTrainerConfig:\n", + " config = self.config.model_trainer\n", + " params = self.params\n", + " \n", + " create_directories([config.root_dir])\n", + " \n", + " # Convert LEARNING_RATE to float explicitly\n", + " learning_rate = float(params.LEARNING_RATE)\n", + " \n", + " model_trainer_config = ModelTrainerConfig(\n", + " root_dir=config.root_dir,\n", + " test_data_path=config.test_data_path,\n", + " train_data_path=config.train_data_path,\n", + " LEARNING_RATE=learning_rate, # Use the converted float value\n", + " LAMBDA_RECON=params.LAMBDA_RECON,\n", + " DISPLAY_STEP=params.DISPLAY_STEP,\n", + " IMAGE_SIZE=params.IMAGE_SIZE,\n", + " INPUT_CHANNELS=params.INPUT_CHANNELS,\n", + " OUTPUT_CHANNELS=params.OUTPUT_CHANNELS,\n", + " EPOCH=params.EPOCH,\n", + " BATCH_SIZE= params.BATCH_SIZE\n", + " )\n", + " return model_trainer_config\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "import numpy as np\n", + "from skimage.color import rgb2lab, lab2rgb\n", + "def lab_to_rgb(L, ab):\n", + " L = L * 100\n", + " ab = (ab - 0.5) * 128 * 2\n", + " Lab = torch.cat([L, ab], dim = 2).numpy()\n", + " rgb_img = []\n", + " for img in Lab:\n", + " img_rgb = lab2rgb(img)\n", + " rgb_img.append(img_rgb)\n", + " \n", + " return np.stack(rgb_img, axis = 0)" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "import matplotlib.pyplot as plt\n", + "def display_progress(cond, real, fake, current_epoch = 0, figsize=(20,15)):\n", + " \"\"\"\n", + " Save cond, real (original) and generated (fake)\n", + " images in one panel \n", + " \"\"\"\n", + " cond = cond.detach().cpu().permute(1, 2, 0) \n", + " real = real.detach().cpu().permute(1, 2, 0)\n", + " fake = fake.detach().cpu().permute(1, 2, 0)\n", + " \n", + " images = [cond, real, fake]\n", + " titles = ['input','real','generated']\n", + " print(f'Epoch: {current_epoch}')\n", + " fig, ax = plt.subplots(1, 3, figsize=figsize)\n", + " for idx,img in enumerate(images):\n", + " if idx == 0:\n", + " ab = torch.zeros((224,224,2))\n", + " img = torch.cat([images[0]* 100, ab], dim=2).numpy()\n", + " imgan = lab2rgb(img)\n", + " else:\n", + " imgan = lab_to_rgb(images[0],img)\n", + " ax[idx].imshow(imgan)\n", + " ax[idx].axis(\"off\")\n", + " for idx, title in enumerate(titles): \n", + " ax[idx].set_title('{}'.format(title))\n", + " plt.show()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "import torch\n", + "from torch import nn, optim\n", + "from torchvision import transforms\n", + "from torch.utils.data import Dataset, DataLoader\n", + "from torch.autograd import Variable\n", + "from torchvision import models\n", + "from torch.nn import functional as F\n", + "import torch.utils.data\n", + "from torchvision.models.inception import inception_v3\n", + "from scipy.stats import entropy\n", + "import pytorch_lightning as pl\n", + "from torchsummary import summary\n", + "from src.imagecolorization.conponents.model_building import Generator, Critic\n", + "from src.imagecolorization.conponents.data_tranformation import ImageColorizationDataset\n", + "from src.imagecolorization.logging import logger\n", + "import gc\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "class CWGAN(pl.LightningModule):\n", + " def __init__(self, in_channels, out_channels, learning_rate=0.0002, lambda_recon=100, display_step=10, lambda_gp=10, lambda_r1=10):\n", + " super().__init__()\n", + " self.save_hyperparameters()\n", + " self.display_step = display_step\n", + " self.generator = Generator(in_channels, out_channels)\n", + " self.critic = Critic(in_channels + out_channels)\n", + " self.lambda_recon = lambda_recon\n", + " self.lambda_gp = lambda_gp\n", + " self.lambda_r1 = lambda_r1\n", + " self.recon_criterion = nn.L1Loss()\n", + " self.generator_losses, self.critic_losses = [], []\n", + " self.automatic_optimization = False # Disable automatic optimization\n", + "\n", + " def configure_optimizers(self):\n", + " optimizer_G = optim.Adam(self.generator.parameters(), lr=self.hparams.learning_rate, betas=(0.5, 0.9))\n", + " optimizer_C = optim.Adam(self.critic.parameters(), lr=self.hparams.learning_rate, betas=(0.5, 0.9))\n", + " return [optimizer_C, optimizer_G]\n", + "\n", + " def generator_step(self, real_images, conditioned_images, optimizer_G):\n", + " optimizer_G.zero_grad()\n", + " fake_images = self.generator(conditioned_images)\n", + " recon_loss = self.recon_criterion(fake_images, real_images)\n", + " recon_loss.backward()\n", + " optimizer_G.step()\n", + " self.generator_losses.append(recon_loss.item())\n", + "\n", + " def critic_step(self, real_images, conditioned_images, optimizer_C):\n", + " optimizer_C.zero_grad()\n", + " fake_images = self.generator(conditioned_images)\n", + "\n", + " # Separate L and ab channels\n", + " l_real = conditioned_images\n", + " ab_real = real_images\n", + " ab_fake = fake_images\n", + "\n", + " # Compute logits\n", + " fake_logits = self.critic(ab_fake, l_real) # Pass two arguments\n", + " real_logits = self.critic(ab_real, l_real) # Pass two arguments\n", + "\n", + " # Compute the loss for the critic\n", + " loss_C = real_logits.mean() - fake_logits.mean()\n", + "\n", + " # Compute the gradient penalty\n", + " alpha = torch.rand(real_images.size(0), 1, 1, 1, requires_grad=True).to(real_images.device)\n", + " interpolated = (alpha * ab_real + (1 - alpha) * ab_fake.detach()).requires_grad_(True)\n", + " interpolated_logits = self.critic(interpolated, l_real)\n", + "\n", + " gradients = torch.autograd.grad(outputs=interpolated_logits, inputs=interpolated,\n", + " grad_outputs=torch.ones_like(interpolated_logits), create_graph=True, retain_graph=True)[0]\n", + " gradients = gradients.view(len(gradients), -1)\n", + " gradients_penalty = ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n", + " loss_C += self.lambda_gp * gradients_penalty\n", + "\n", + " # Compute the R1 regularization loss\n", + " r1_reg = gradients.pow(2).sum(1).mean()\n", + " loss_C += self.lambda_r1 * r1_reg\n", + "\n", + " # Backpropagation\n", + " loss_C.backward()\n", + " optimizer_C.step()\n", + " self.critic_losses.append(loss_C.item())\n", + "\n", + " def training_step(self, batch, batch_idx):\n", + " optimizer_C, optimizer_G = self.optimizers()\n", + " real_images, conditioned_images = batch\n", + "\n", + " self.critic_step(real_images, conditioned_images, optimizer_C)\n", + " self.generator_step(real_images, conditioned_images, optimizer_G)\n", + "\n", + " if self.current_epoch % self.display_step == 0 and batch_idx == 0:\n", + " with torch.no_grad():\n", + " fake_images = self.generator(conditioned_images)\n", + " display_progress(conditioned_images[0], real_images[0], fake_images[0], self.current_epoch)\n", + "\n", + " def on_epoch_end(self):\n", + " gc.collect()\n", + " torch.cuda.empty_cache()\n", + "\n", + " def forward(self, x):\n", + " return self.generator(x)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "class ModelTrainer:\n", + " def __init__(self, config):\n", + " self.config = config\n", + " \n", + " def load_datasets(self):\n", + " self.train_dataset = torch.load(self.config.train_data_path)\n", + " self.test_dataset = torch.load(self.config.test_data_path)\n", + " \n", + " def create_dataloaders(self):\n", + " self.train_dataloader = DataLoader(\n", + " self.train_dataset, batch_size=self.config.BATCH_SIZE, shuffle=True\n", + " )\n", + " self.test_dataloader = DataLoader(\n", + " self.test_dataset, batch_size=self.config.BATCH_SIZE, shuffle=False\n", + " )\n", + " \n", + " def initialize_model(self):\n", + " self.model = CWGAN(\n", + " in_channels=self.config.INPUT_CHANNELS,\n", + " out_channels=self.config.OUTPUT_CHANNELS,\n", + " learning_rate=self.config.LEARNING_RATE,\n", + " lambda_recon=self.config.LAMBDA_RECON,\n", + " display_step=self.config.DISPLAY_STEP,\n", + " lambda_gp=10, # Default value, you can make it configurable\n", + " lambda_r1=10 # Default value, you can make it configurable\n", + " )\n", + " \n", + " def train_model(self):\n", + " checkpoint_callback = pl.callbacks.ModelCheckpoint(\n", + " dirpath=self.config.root_dir,\n", + " filename='cwgan-{epoch:02d}-{generator_loss:.2f}',\n", + " save_top_k=-1, # Save all checkpoints\n", + " verbose=True\n", + " )\n", + " \n", + " trainer = pl.Trainer(\n", + " max_epochs=self.config.EPOCH,\n", + " callbacks=[checkpoint_callback],\n", + " \n", + " )\n", + " \n", + " trainer.fit(self.model, self.train_dataloader)\n", + " \n", + " def save_model(self):\n", + " trained_model_dir = self.config.root_dir\n", + " os.makedirs(trained_model_dir, exist_ok=True)\n", + " \n", + " generator_path = os.path.join(trained_model_dir, \"cwgan_generator_final.pt\")\n", + " critic_path = os.path.join(trained_model_dir, \"cwgan_critic_final.pt\")\n", + " \n", + " torch.save(self.model.generator.state_dict(), generator_path)\n", + " torch.save(self.model.critic.state_dict(), critic_path)\n", + " logger.info(f\"Final models saved at {trained_model_dir}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2024-08-24 01:20:51,034: INFO: common: yaml file: config\\config.yaml loaded successfully]\n", + "[2024-08-24 01:20:51,037: INFO: common: yaml file: params.yaml loaded successfully]\n", + "[2024-08-24 01:20:51,038: INFO: common: created directory at: artifacts]\n", + "[2024-08-24 01:20:51,038: INFO: common: created directory at: artifacts/trained_model]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_20540\\2004391108.py:7: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", + " self.train_dataset = torch.load(self.config.train_data_path)\n", + "C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_20540\\2004391108.py:8: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n", + " self.test_dataset = torch.load(self.config.test_data_path)\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2024-08-24 01:20:56,993: INFO: rank_zero: GPU available: True (cuda), used: True]\n", + "[2024-08-24 01:20:56,993: INFO: rank_zero: TPU available: False, using: 0 TPU cores]\n", + "[2024-08-24 01:20:56,994: INFO: rank_zero: IPU available: False, using: 0 IPUs]\n", + "[2024-08-24 01:20:56,994: INFO: rank_zero: HPU available: False, using: 0 HPUs]\n", + "[2024-08-24 01:20:57,066: INFO: cuda: LOCAL_RANK: 0 - CUDA_VISIBLE_DEVICES: [0]]\n", + "[2024-08-24 01:20:57,069: INFO: model_summary: \n", + " | Name | Type | Params\n", + "----------------------------------------------\n", + "0 | generator | Generator | 8.2 M \n", + "1 | critic | Critic | 2.8 M \n", + "2 | recon_criterion | L1Loss | 0 \n", + "----------------------------------------------\n", + "11.0 M Trainable params\n", + "0 Non-trainable params\n", + "11.0 M Total params\n", + "43.893 Total estimated model params size (MB)]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "c:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\pytorch_lightning\\callbacks\\model_checkpoint.py:630: Checkpoint directory artifacts/trained_model exists and is not empty.\n", + "c:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\pytorch_lightning\\trainer\\connectors\\data_connector.py:441: The 'train_dataloader' does not have many workers which may be a bottleneck. Consider increasing the value of the `num_workers` argument` to `num_workers=23` in the `DataLoader` to improve performance.\n" + ] + }, + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "f44f96188b244aaea275c8aa3edc7e1c", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + "Training: | | 0/? [00:00" + ] + }, + "metadata": {}, + "output_type": "display_data" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2024-08-24 01:28:31,989: INFO: rank_zero: `Trainer.fit` stopped: `max_epochs=1` reached.]\n", + "[2024-08-24 01:28:32,111: INFO: 2004391108: Final models saved at artifacts/trained_model]\n" + ] + } + ], + "source": [ + "try:\n", + " config_manager = ConfigurationManager()\n", + " model_trainer_config = config_manager.get_model_trainer_config()\n", + " model_trainer = ModelTrainer(config=model_trainer_config)\n", + " model_trainer.load_datasets()\n", + " model_trainer.create_dataloaders()\n", + " model_trainer.initialize_model()\n", + " model_trainer.train_model()\n", + " model_trainer.save_model()\n", + "except Exception as e:\n", + " logger.error(f\"Error during model training: {e}\")\n", + " raise e" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "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.11.0" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +}