{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/workspace/P78123011/miniconda3/envs/py31014/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import transformers as T\n",
    "from datasets import load_dataset\n",
    "import torch\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from torch.optim import AdamW\n",
    "from tqdm import tqdm\n",
    "from torchmetrics import SpearmanCorrCoef, Accuracy, F1Score\n",
    "device = \"cuda:3\" if torch.cuda.is_available() else \"cpu\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 有些中文的標點符號在tokenizer編碼以後會變成[UNK]，所以將其換成英文標點\n",
    "token_replacement = [\n",
    "    [\"：\" , \":\"],\n",
    "    [\"，\" , \",\"],\n",
    "    [\"“\" , \"\\\"\"],\n",
    "    [\"”\" , \"\\\"\"],\n",
    "    [\"？\" , \"?\"],\n",
    "    [\"……\" , \"...\"],\n",
    "    [\"！\" , \"!\"]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/workspace/P78123011/miniconda3/envs/py31014/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:1601: FutureWarning: `clean_up_tokenization_spaces` was not set. It will be set to `True` by default. This behavior will be depracted in transformers v4.45, and will be then set to `False` by default. For more details check this issue: https://github.com/huggingface/transformers/issues/31884\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "model = MultiLabelModel().to(device)\n",
    "tokenizer = T.BertTokenizer.from_pretrained(\"google-bert/bert-base-uncased\", cache_dir=\"./cache/\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset example: \n",
      "{'sentence_pair_id': 1, 'premise': 'A group of kids is playing in a yard and an old man is standing in the background', 'hypothesis': 'A group of boys in a yard is playing and a man is standing in the background', 'relatedness_score': 4.5, 'entailment_judgment': 0} \n",
      "{'sentence_pair_id': 2, 'premise': 'A group of children is playing in the house and there is no man standing in the background', 'hypothesis': 'A group of kids is playing in a yard and an old man is standing in the background', 'relatedness_score': 3.200000047683716, 'entailment_judgment': 0} \n",
      "{'sentence_pair_id': 3, 'premise': 'The young boys are playing outdoors and the man is smiling nearby', 'hypothesis': 'The kids are playing outdoors near a man with a smile', 'relatedness_score': 4.699999809265137, 'entailment_judgment': 1}\n"
     ]
    }
   ],
   "source": [
    "class SemevalDataset(Dataset):\n",
    "    def __init__(self, split=\"train\") -> None:\n",
    "        super().__init__()\n",
    "        assert split in [\"train\", \"validation\"]\n",
    "        self.data = load_dataset(\n",
    "            \"sem_eval_2014_task_1\", split=split, cache_dir=\"./cache/\"\n",
    "        ).to_list()\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        d = self.data[index]\n",
    "        # 把中文標點替換掉\n",
    "        for k in [\"premise\", \"hypothesis\"]:\n",
    "            for tok in token_replacement:\n",
    "                d[k] = d[k].replace(tok[0], tok[1])\n",
    "        return d\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.data)\n",
    "\n",
    "data_sample = SemevalDataset(split=\"train\").data[:3]\n",
    "print(f\"Dataset example: \\n{data_sample[0]} \\n{data_sample[1]} \\n{data_sample[2]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define the hyperparameters\n",
    "lr = 3e-5\n",
    "epochs = 3\n",
    "train_batch_size = 8\n",
    "validation_batch_size = 8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO1: Create batched data for DataLoader\n",
    "# `collate_fn` is a function that defines how the data batch should be packed.\n",
    "# This function will be called in the DataLoader to pack the data batch.\n",
    "\n",
    "def collate_fn(batch):\n",
    "    # TODO1-1: Implement the collate_fn function\n",
    "    # Write your code here\n",
    "    # The input parameter is a data batch (tuple), and this function packs it into tensors.\n",
    "    # Use tokenizer to pack tokenize and pack the data and its corresponding labels.\n",
    "    # Return the data batch and labels for each sub-task.\n",
    "\n",
    "# TODO1-2: Define your DataLoader\n",
    "dl_train = # Write your code here\n",
    "dl_validation = # Write your code here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO2: Construct your model\n",
    "class MultiLabelModel(torch.nn.Module):\n",
    "    def __init__(self, *args, **kwargs):\n",
    "        super().__init__(*args, **kwargs)\n",
    "        # Write your code here\n",
    "        # Define what modules you will use in the model\n",
    "    def forward(self, **kwargs):\n",
    "        # Write your code here\n",
    "        # Forward pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO3: Define your optimizer and loss function\n",
    "\n",
    "# TODO3-1: Define your Optimizer\n",
    "optimizer = # Write your code here\n",
    "\n",
    "# TODO3-2: Define your loss functions (you should have two)\n",
    "# Write your code here\n",
    "\n",
    "# scoring functions\n",
    "spc = SpearmanCorrCoef()\n",
    "acc = Accuracy(task=\"multiclass\", num_classes=3)\n",
    "f1 = F1Score(task=\"multiclass\", num_classes=3, average='macro')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Training epoch [1/3]: 100%|██████████| 563/563 [00:17<00:00, 32.56it/s, loss=2]    \n",
      "Validation epoch [1/3]: 100%|██████████| 63/63 [00:00<00:00, 92.42it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Spearman Corr: 0.7439783811569214 \n",
      "Accuracy: 0.8240000009536743 \n",
      "F1 Score: 0.8317749500274658\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Training epoch [2/3]: 100%|██████████| 563/563 [00:16<00:00, 34.44it/s, loss=2.83] \n",
      "Validation epoch [2/3]: 100%|██████████| 63/63 [00:01<00:00, 56.86it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Spearman Corr: 0.7545040845870972 \n",
      "Accuracy: 0.8479999899864197 \n",
      "F1 Score: 0.8453624248504639\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Training epoch [3/3]: 100%|██████████| 563/563 [00:17<00:00, 31.83it/s, loss=0.933]\n",
      "Validation epoch [3/3]: 100%|██████████| 63/63 [00:00<00:00, 90.68it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Spearman Corr: 0.6313151121139526 \n",
      "Accuracy: 0.8560000061988831 \n",
      "F1 Score: 0.8557099103927612\n"
     ]
    }
   ],
   "source": [
    "for ep in range(epochs):\n",
    "    pbar = tqdm(dl_train)\n",
    "    pbar.set_description(f\"Training epoch [{ep+1}/{epochs}]\")\n",
    "    model.train()\n",
    "    # TODO4: Write the training loop\n",
    "    # Write your code here\n",
    "    # train your model\n",
    "    # clear gradient\n",
    "    # forward pass\n",
    "    # compute loss\n",
    "    # back-propagation\n",
    "    # model optimization\n",
    "\n",
    "    pbar = tqdm(dl_validation)\n",
    "    pbar.set_description(f\"Validation epoch [{ep+1}/{epochs}]\")\n",
    "    model.eval()\n",
    "    # TODO5: Write the evaluation loop\n",
    "    # Write your code here\n",
    "    # Evaluate your model\n",
    "    # Output all the evaluation scores (SpearmanCorrCoef, Accuracy, F1Score)\n",
    "    torch.save(model, f'./saved_models/ep{ep}.ckpt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For test set predictions, you can write perform evaluation simlar to #TODO5."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py31014",
   "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.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
