Spaces:
Runtime error
Runtime error
File size: 31,329 Bytes
cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d e623e7e cf8627d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 |
{
"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": 3,
"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": 4,
"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": 5,
"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": 6,
"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": 7,
"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": 10,
"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",
" # Ensure these are actually datasets, not dataloaders\n",
" if isinstance(self.train_dataset, DataLoader):\n",
" self.train_dataset = self.train_dataset.dataset\n",
" if isinstance(self.test_dataset, DataLoader):\n",
" self.test_dataset = self.test_dataset.dataset\n",
" \n",
" def create_dataloaders(self):\n",
" self.train_dataloader = DataLoader(\n",
" self.train_dataset, \n",
" batch_size=self.config.BATCH_SIZE, \n",
" shuffle=True,\n",
" )\n",
" self.test_dataloader = DataLoader(\n",
" self.test_dataset, \n",
" batch_size=self.config.BATCH_SIZE, \n",
" shuffle=False,\n",
" )\n",
" \n",
" for batch in self.test_dataloader:\n",
" ab, L = batch\n",
" print(f\"Train loader batch - ab shape: {ab.shape}, L shape: {L.shape}\")\n",
" break # Remove break to check shapes for all batches if needed\n",
"\n",
" for batch in self.train_dataloader:\n",
" ab, L = batch\n",
" print(f\"Test loader batch - ab shape: {ab.shape}, L shape: {L.shape}\")\n",
" break\n",
" \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": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2024-08-24 19:39:49,395: INFO: common: yaml file: config\\config.yaml loaded successfully]\n",
"[2024-08-24 19:39:49,400: INFO: common: yaml file: params.yaml loaded successfully]\n",
"[2024-08-24 19:39:49,404: INFO: common: created directory at: artifacts]\n",
"[2024-08-24 19:39:49,405: INFO: common: created directory at: artifacts/trained_model]\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"C:\\Users\\azizu\\AppData\\Local\\Temp\\ipykernel_19820\\1928993369.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_19820\\1928993369.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 19:39:58,617: ERROR: 129140692: Error during model training: pic should be 2/3 dimensional. Got 4 dimensions.]\n"
]
},
{
"ename": "ValueError",
"evalue": "pic should be 2/3 dimensional. Got 4 dimensions.",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[1;32mIn[11], line 15\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[0;32m 14\u001b[0m logger\u001b[38;5;241m.\u001b[39merror(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mError during model training: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00me\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m---> 15\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m e\n",
"Cell \u001b[1;32mIn[11], line 6\u001b[0m\n\u001b[0;32m 4\u001b[0m model_trainer \u001b[38;5;241m=\u001b[39m ModelTrainer(config\u001b[38;5;241m=\u001b[39mmodel_trainer_config)\n\u001b[0;32m 5\u001b[0m model_trainer\u001b[38;5;241m.\u001b[39mload_datasets()\n\u001b[1;32m----> 6\u001b[0m \u001b[43mmodel_trainer\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mcreate_dataloaders\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 10\u001b[0m model_trainer\u001b[38;5;241m.\u001b[39minitialize_model()\n\u001b[0;32m 11\u001b[0m model_trainer\u001b[38;5;241m.\u001b[39mtrain_model()\n",
"Cell \u001b[1;32mIn[10], line 28\u001b[0m, in \u001b[0;36mModelTrainer.create_dataloaders\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 17\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtrain_dataloader \u001b[38;5;241m=\u001b[39m DataLoader(\n\u001b[0;32m 18\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtrain_dataset, \n\u001b[0;32m 19\u001b[0m batch_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconfig\u001b[38;5;241m.\u001b[39mBATCH_SIZE, \n\u001b[0;32m 20\u001b[0m shuffle\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m,\n\u001b[0;32m 21\u001b[0m )\n\u001b[0;32m 22\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtest_dataloader \u001b[38;5;241m=\u001b[39m DataLoader(\n\u001b[0;32m 23\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mtest_dataset, \n\u001b[0;32m 24\u001b[0m batch_size\u001b[38;5;241m=\u001b[39m\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mconfig\u001b[38;5;241m.\u001b[39mBATCH_SIZE, \n\u001b[0;32m 25\u001b[0m shuffle\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m,\n\u001b[0;32m 26\u001b[0m )\n\u001b[1;32m---> 28\u001b[0m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mbatch\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mtest_dataloader\u001b[49m\u001b[43m:\u001b[49m\n\u001b[0;32m 29\u001b[0m \u001b[43m \u001b[49m\u001b[43mab\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mL\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m \u001b[49m\u001b[43mbatch\u001b[49m\n\u001b[0;32m 30\u001b[0m \u001b[43m \u001b[49m\u001b[38;5;28;43mprint\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;124;43mf\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mTrain loader batch - ab shape: \u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mab\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mshape\u001b[49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m, L shape: \u001b[39;49m\u001b[38;5;132;43;01m{\u001b[39;49;00m\u001b[43mL\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mshape\u001b[49m\u001b[38;5;132;43;01m}\u001b[39;49;00m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torch\\utils\\data\\dataloader.py:630\u001b[0m, in \u001b[0;36m_BaseDataLoaderIter.__next__\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 627\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_sampler_iter \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[0;32m 628\u001b[0m \u001b[38;5;66;03m# TODO(https://github.com/pytorch/pytorch/issues/76750)\u001b[39;00m\n\u001b[0;32m 629\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_reset() \u001b[38;5;66;03m# type: ignore[call-arg]\u001b[39;00m\n\u001b[1;32m--> 630\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_next_data\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 631\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m+\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m1\u001b[39m\n\u001b[0;32m 632\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_dataset_kind \u001b[38;5;241m==\u001b[39m _DatasetKind\u001b[38;5;241m.\u001b[39mIterable \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[0;32m 633\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \\\n\u001b[0;32m 634\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_num_yielded \u001b[38;5;241m>\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_IterableDataset_len_called:\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torch\\utils\\data\\dataloader.py:673\u001b[0m, in \u001b[0;36m_SingleProcessDataLoaderIter._next_data\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 671\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m_next_data\u001b[39m(\u001b[38;5;28mself\u001b[39m):\n\u001b[0;32m 672\u001b[0m index \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_next_index() \u001b[38;5;66;03m# may raise StopIteration\u001b[39;00m\n\u001b[1;32m--> 673\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43m_dataset_fetcher\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mfetch\u001b[49m\u001b[43m(\u001b[49m\u001b[43mindex\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;66;03m# may raise StopIteration\u001b[39;00m\n\u001b[0;32m 674\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_pin_memory:\n\u001b[0;32m 675\u001b[0m data \u001b[38;5;241m=\u001b[39m _utils\u001b[38;5;241m.\u001b[39mpin_memory\u001b[38;5;241m.\u001b[39mpin_memory(data, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_pin_memory_device)\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torch\\utils\\data\\_utils\\fetch.py:52\u001b[0m, in \u001b[0;36m_MapDatasetFetcher.fetch\u001b[1;34m(self, possibly_batched_index)\u001b[0m\n\u001b[0;32m 50\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset\u001b[38;5;241m.\u001b[39m__getitems__(possibly_batched_index)\n\u001b[0;32m 51\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m---> 52\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[43m[\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdataset\u001b[49m\u001b[43m[\u001b[49m\u001b[43midx\u001b[49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43midx\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mpossibly_batched_index\u001b[49m\u001b[43m]\u001b[49m\n\u001b[0;32m 53\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 54\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset[possibly_batched_index]\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torch\\utils\\data\\_utils\\fetch.py:52\u001b[0m, in \u001b[0;36m<listcomp>\u001b[1;34m(.0)\u001b[0m\n\u001b[0;32m 50\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset\u001b[38;5;241m.\u001b[39m__getitems__(possibly_batched_index)\n\u001b[0;32m 51\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[1;32m---> 52\u001b[0m data \u001b[38;5;241m=\u001b[39m [\u001b[38;5;28;43mself\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mdataset\u001b[49m\u001b[43m[\u001b[49m\u001b[43midx\u001b[49m\u001b[43m]\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m idx \u001b[38;5;129;01min\u001b[39;00m possibly_batched_index]\n\u001b[0;32m 53\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m 54\u001b[0m data \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset[possibly_batched_index]\n",
"File \u001b[1;32mc:\\mlops project\\image-colorization-mlops\\src\\imagecolorization\\conponents\\data_tranformation.py:22\u001b[0m, in \u001b[0;36mImageColorizationDataset.__getitem__\u001b[1;34m(self, idx)\u001b[0m\n\u001b[0;32m 20\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__getitem__\u001b[39m(\u001b[38;5;28mself\u001b[39m, idx):\n\u001b[0;32m 21\u001b[0m L \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset[\u001b[38;5;241m0\u001b[39m][idx])\u001b[38;5;241m.\u001b[39mreshape(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mimage_size \u001b[38;5;241m+\u001b[39m (\u001b[38;5;241m1\u001b[39m,))\n\u001b[1;32m---> 22\u001b[0m L \u001b[38;5;241m=\u001b[39m \u001b[43mtransforms\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mToTensor\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m(\u001b[49m\u001b[43mL\u001b[49m\u001b[43m)\u001b[49m\n\u001b[0;32m 24\u001b[0m ab \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray(\u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdataset[\u001b[38;5;241m1\u001b[39m][idx])\n\u001b[0;32m 25\u001b[0m ab \u001b[38;5;241m=\u001b[39m transforms\u001b[38;5;241m.\u001b[39mToTensor()(ab)\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torchvision\\transforms\\transforms.py:137\u001b[0m, in \u001b[0;36mToTensor.__call__\u001b[1;34m(self, pic)\u001b[0m\n\u001b[0;32m 129\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21m__call__\u001b[39m(\u001b[38;5;28mself\u001b[39m, pic):\n\u001b[0;32m 130\u001b[0m \u001b[38;5;250m \u001b[39m\u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m 131\u001b[0m \u001b[38;5;124;03m Args:\u001b[39;00m\n\u001b[0;32m 132\u001b[0m \u001b[38;5;124;03m pic (PIL Image or numpy.ndarray): Image to be converted to tensor.\u001b[39;00m\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 135\u001b[0m \u001b[38;5;124;03m Tensor: Converted image.\u001b[39;00m\n\u001b[0;32m 136\u001b[0m \u001b[38;5;124;03m \"\"\"\u001b[39;00m\n\u001b[1;32m--> 137\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mF\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mto_tensor\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpic\u001b[49m\u001b[43m)\u001b[49m\n",
"File \u001b[1;32mc:\\Users\\azizu\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\torchvision\\transforms\\functional.py:145\u001b[0m, in \u001b[0;36mto_tensor\u001b[1;34m(pic)\u001b[0m\n\u001b[0;32m 142\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mTypeError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mpic should be PIL Image or ndarray. Got \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mtype\u001b[39m(pic)\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 144\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m _is_numpy(pic) \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m _is_numpy_image(pic):\n\u001b[1;32m--> 145\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mValueError\u001b[39;00m(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mpic should be 2/3 dimensional. Got \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpic\u001b[38;5;241m.\u001b[39mndim\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m dimensions.\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[0;32m 147\u001b[0m default_float_dtype \u001b[38;5;241m=\u001b[39m torch\u001b[38;5;241m.\u001b[39mget_default_dtype()\n\u001b[0;32m 149\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(pic, np\u001b[38;5;241m.\u001b[39mndarray):\n\u001b[0;32m 150\u001b[0m \u001b[38;5;66;03m# handle numpy array\u001b[39;00m\n",
"\u001b[1;31mValueError\u001b[0m: pic should be 2/3 dimensional. Got 4 dimensions."
]
}
],
"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",
" \n",
" \n",
"\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": []
},
{
"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
}
|