{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import BertTokenizer, BertModel\n",
    "from datasets import load_dataset\n",
    "from evaluate import load\n",
    "import torch\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from torch.optim import AdamW\n",
    "from tqdm import tqdm\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "#  You can install and import any other libraries if needed"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Some Chinese punctuations will be tokenized as [UNK], so we replace them with English ones\n",
    "token_replacement = [\n",
    "    [\"：\" , \":\"],\n",
    "    [\"，\" , \",\"],\n",
    "    [\"“\" , \"\\\"\"],\n",
    "    [\"”\" , \"\\\"\"],\n",
    "    [\"？\" , \"?\"],\n",
    "    [\"……\" , \"...\"],\n",
    "    [\"！\" , \"!\"]\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "tokenizer = BertTokenizer.from_pretrained(\"google-bert/bert-base-uncased\", cache_dir=\"./cache/\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SemevalDataset(Dataset):\n",
    "    def __init__(self, split=\"train\") -> None:\n",
    "        super().__init__()\n",
    "        assert split in [\"train\", \"validation\", \"test\"]\n",
    "        self.data = load_dataset(\n",
    "            \"sem_eval_2014_task_1\", split=split, trust_remote_code=True, cache_dir=\"./cache/\"\n",
    "        ).to_list()\n",
    "\n",
    "    def __getitem__(self, index):\n",
    "        d = self.data[index]\n",
    "        # Replace Chinese punctuations with English ones\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",
    "# You can modify these values if needed\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\n",
    "dl_test = # 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",
    "        # Please use \"google-bert/bert-base-uncased\" model (https://huggingface.co/google-bert/bert-base-uncased)\n",
    "        # Besides the base model, you may design additional architectures by incorporating linear layers, activation functions, or other neural components.\n",
    "        # Remark: The use of any additional pretrained language models is not permitted.\n",
    "    def forward(self, **kwargs):\n",
    "        # Write your code here\n",
    "        # Forward pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO3: Define your optimizer and loss function\n",
    "\n",
    "model = MultiLabelModel().to(device)\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",
    "psr = load(\"pearsonr\")\n",
    "acc = load(\"accuracy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_score = 0.0\n",
    "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 (PearsonCorr, Accuracy)\n",
    "    pearson_corr = # Write your code here\n",
    "    accuracy = # Write your code here\n",
    "    # print(f\"F1 Score: {f1.compute()}\")\n",
    "    \n",
    "    if pearson_corr + accuracy > best:\n",
    "        best = pearson_corr + accuracy\n",
    "        torch.save(model.state_dict(), f'./saved_models/best_model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the model\n",
    "model = MultiLabelModel().to(device)\n",
    "model.load_state_dict(torch.load(f\"./saved_models/best_model.ckpt\", weights_only=True))\n",
    "\n",
    "# Test Loop\n",
    "pbar = tqdm(dl_test, desc=\"Test\")\n",
    "model.eval()\n",
    "\n",
    "# TODO6: Write the test loop\n",
    "# Write your code here\n",
    "# We have loaded the best model with the highest evaluation score for you\n",
    "# Please implement the test loop to evaluate the model on the test dataset\n",
    "# We will have 10% of the total score for the test accuracy and pearson correlation"
   ]
  }
 ],
 "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
}
