{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Model training\n",
    "---\n",
    "\n",
    "Experimenting with training some models over the dataset."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import timm\n",
    "from lightning import Trainer\n",
    "from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from coal_emissions_monitoring.dataset import CoalEmissionsDataModule\n",
    "from coal_emissions_monitoring.model import CoalEmissionsModel, SmallCNN\n",
    "from coal_emissions_monitoring.transforms import efficientnet_transform"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size = 128\n",
    "crop_size = 52\n",
    "num_workers = 0\n",
    "learning_rate = 1e-3"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create the dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data = CoalEmissionsDataModule(\n",
    "    final_dataset_path=\"/Users/adminuser/GitHub/ccai-ss23-ai-monitoring-tutorial/data/google/final_dataset.csv\",\n",
    "    batch_size=batch_size,\n",
    "    num_workers=num_workers,\n",
    "    predownload_images=True,\n",
    "    download_missing_images=False,\n",
    "    images_dir=\"/Users/adminuser/GitHub/ccai-ss23-ai-monitoring-tutorial/data/google/images/visual\",\n",
    "    crop_size=crop_size,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.setup(\"fit\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# model = timm.create_model(\"efficientnet_b0\", pretrained=True, num_classes=1)\n",
    "model = SmallCNN(num_input_channels=3, num_classes=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = model.float().to(\"cpu\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lit_model = CoalEmissionsModel(\n",
    "    model=model,\n",
    "    learning_rate=learning_rate,\n",
    "    pos_weight=data.pos_weight,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Confirm that the model can be run on a batch of data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "data.setup(stage=\"fit\")\n",
    "for batch in data.train_dataloader():\n",
    "    break\n",
    "print(f\"Keys in batch: {batch.keys()}\")\n",
    "print(f\"Image shape: {batch['image'].shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "y_pred = lit_model(batch[\"image\"])\n",
    "y_pred"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Check that the model can overfit a single batch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "trainer = Trainer(\n",
    "    max_epochs=1,\n",
    "    callbacks=[\n",
    "        EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=10),\n",
    "        ModelCheckpoint(\n",
    "            monitor=\"val_loss\",\n",
    "            mode=\"min\",\n",
    "            filename=\"{val_loss:2f}-{val_balanced_accuracy:.2f}-{epoch}-64crop_full_data\",\n",
    "            save_top_k=1,\n",
    "            dirpath=\"/Users/adminuser/GitHub/ccai-ss23-ai-monitoring-tutorial/data/models/\",\n",
    "        )\n",
    "    ],\n",
    "    limit_train_batches=round(0.1 * len(data.train_dataset.gdf) / batch_size),\n",
    "    limit_val_batches=round(0.4 * len(data.val_dataset.gdf) / batch_size),\n",
    "    reload_dataloaders_every_n_epochs=1,\n",
    "    precision=\"16-mixed\",\n",
    "    accelerator=\"cpu\",\n",
    "    devices=1,\n",
    "    log_every_n_steps=5,\n",
    "    # overfit_batches=1,\n",
    ")\n",
    "trainer.fit(lit_model, data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "_ = trainer.test(\n",
    "    model=lit_model,\n",
    "    datamodule=data,\n",
    "    ckpt_path=\"best\",\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ccai_ss23",
   "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.10.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
