{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"IOAI\n", "\n", "[IOAI 2024 (Burgas, Bulgaria), On-Site Round](https://ioai-official.org/bulgaria-2024)\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2024/blob/main/On-Site-Round/Help_BOBAI/Help_BOBAI.ipynb)" ] }, { "cell_type": "markdown", "metadata": { "id": "bqAFpqJlnt77" }, "source": [ "# Help BOBAI: More classification in an unknown language" ] }, { "cell_type": "markdown", "metadata": { "id": "vu6E-5QWIjlv" }, "source": [ "\n", "\n", "## Background\n", "Last time you heard from Bob, he asked you to help him by building a classifier for a new unknown language. The client, Amoira, was happy with your solution so Bob instructed his team to deploy the new model and after some heavy optimization and careful unit testing, the service was deployed and has been running smoothly since.\n", "\n", "## Task\n", "\n", "This very morning, Amoira returned with a request to extend the number of classes which the classifier can handle from 5 to 7. And this has to be done *today*!\n", "\n", "Amoira has provided labeled data for the new classes. With more time, Bob could just use your earlier solution to train a new model on the union of the old and new data, right? The trouble is that the deployment of a new model is a complex process and cannot be done in a day, so the solution has to be built entirely around the model already deployed. Bob has once more come to you for help, as you know the task best.\n", "\n", "Whatsmore, Amoira's security concerns have grown even further with the addition of the new data, so they have requested that Bob does not release the text in any form - what if someone managed to decrypt it! So Bob has provided you with a precomputed and cached encoding of all available data: the train and dev set previously used for the 5-way classification, and the new data Amoira provided for the 2 additional classes. The encoding is the output of the pooling layer in mBERT, so is fits right into the classifier previously trained.\n", "\n", "Your task is to build a solution for 7-way classification, while operating within the following constraints:\n", "\n", "* The solution can use the 5-way classifier, but cannot change the parameters of the classifier or add any new learned parameters.\n", "\n", "* You are allowed to compute averages and distances between the data encodings.\n", "\n", "* The solution should be reproducible in under 1 hour on an L4 GPU card.\n", "\n", "* The classifier has to perform inference on any random 500 data samples in under 2 minutes on an L4 GPU card.\n", "\n", "## Deliverables\n", "\n", "You need to submit:\n", "\n", "* Working code that can be used to reproduce and test your best model.\n", " * In this Colab notebook.\n", " * Reproducing your best model means that starting from the baseline classifier, we should be able to arrive at your final best model by executing the cells of the notebook.\n", "* The predictions on the test data (released two hours before the end of the competition).\n", "\n", "**You absolutely need to ensure that:**\n", "\n", "(1) your notebook is executable from top to bottom\n", "\n", "(2) that the notebook contains the full code needed to reproduce your model\n", "\n", "(3) that it can run on an L4 GPU\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Ne5Qh1_L_I6G" }, "source": [ "## Training Dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "XFs3soFJCC9h" }, "outputs": [], "source": [ "import torch\n", "\n", "dataset = torch.load('./training_set/train-dev_dataset_with_labels.pt')\n", "\n", "inputs = dataset[:,:,:-1]\n", "labels = dataset[:, :, -1]\n" ] }, { "cell_type": "markdown", "metadata": { "id": "cv9MBElmMs6G" }, "source": [ "## Baseline Solution\n", "\n", "Below you will find a very naive baseline solution: given an input vector, we use either randomly assign one of the new labels (5 and 6) with uniform probability over a 7-way classification, or we use the base classifier to make a prediction.\n", "\n", "You can replace the code below with your solution." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "cafvT54icF0S" }, "outputs": [], "source": [ "import torch\n", "import random\n", "\n", "class SevenWayClassifier():\n", " def __init__(self, ):\n", " base_clf = torch.nn.Linear(in_features=768, out_features=5, bias=True)\n", " base_clf.load_state_dict(torch.load(\"training_set/base_classifier.pth\"))\n", " self.base_clf = base_clf\n", "\n", " def base_classification(self, input_vector):\n", "\n", " with torch.no_grad():\n", " logits = self.base_clf(input_vector)\n", " preds = torch.softmax(logits, 1)\n", " predicted_class = preds.argmax(dim=1).numpy()[0]\n", "\n", " return predicted_class\n", "\n", " def __call__(self, input_vector):\n", "\n", " random_class = random.choice([0,1,2,3,4,5,6])\n", " if random_class in [5,6]:\n", " predicted_class = random_class\n", " else:\n", " predicted_class = self.base_classification(input_vector)\n", "\n", " return predicted_class\n", "\n", "clf = SevenWayClassifier()" ] }, { "cell_type": "markdown", "metadata": { "id": "lZUf3V_8Re0b" }, "source": [ "## Inference and Evaluation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TPXFo8pFRe0i" }, "outputs": [], "source": [ "from sklearn.metrics import f1_score\n", "\n", "def compute_f1(labels, predictions):\n", " return f1_score(labels, predictions, average='macro')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0ed-lh6ERe0h" }, "outputs": [], "source": [ "from tqdm import tqdm\n", "\n", "def inference(clf, input_vectors):\n", " predictions = []\n", " for sample in tqdm(input_vectors):\n", " predictions.append(clf(sample))\n", " return predictions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "2A47J-tgWdQI" }, "outputs": [], "source": [ "\n", "predictions = inference(clf, inputs)\n", "\n", "f1 = compute_f1(labels, predictions)\n", "print('\\nNaive solution F1', f1)" ] }, { "cell_type": "markdown", "metadata": { "id": "AixBMbqHHVOB" }, "source": [ "## Validation Dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "oiznNPDfHW60" }, "outputs": [], "source": [ "# The leaderboard may or may not work... If it doesn't forgive us. We will try to get it running.\n", "\n", "import pandas as pd\n", "import numpy as np\n", "\n", "def submission_to_csv(pred: np.ndarray, output_fpath: str = \"submission.csv\"):\n", " pred = np.array(pred).flatten()\n", " data_size = pred.size\n", " df = pd.DataFrame({\n", " \"ID\": np.arange(data_size),\n", " \"class\": pred\n", " })\n", "\n", " df.to_csv(output_fpath, index=False)\n", "\n", "eval_inputs = torch.load('./Solution/validation_set/eval_dataset.pt')\n", "\n", "eval_predictions = inference(clf, eval_inputs)\n", "\n", "submission_to_csv(eval_predictions)" ] }, { "cell_type": "markdown", "metadata": { "id": "engFIUpCJb4D" }, "source": [ "## Test Dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "-_htHBvBJf0v" }, "outputs": [], "source": [ "# DO NOT CHANGE THIS CELL\n", "\n", "# this download link will not work until two hours before the end of the competition\n", "test_inputs = torch.load('Solution/test_set/test_dataset.pt')\n", "\n", "split='test'\n", "\n", "test_predictions = inference(clf, test_inputs)\n", "\n", "with open('{}_predictions.txt'.format(\"Team Name\"), 'w') as outfile:\n", " outfile.write('\\n'.join([str(p) for p in test_predictions]))" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "machine_shape": "hm", "provenance": [ { "file_id": "1Tjsagm_BvzF7dfxIqRLI5njtsYHpyRcv", "timestamp": 1723325793772 }, { "file_id": "1bnKOPn0TE3f_E0LK1Tb09P0YcIEzuRTF", "timestamp": 1723143817001 }, { "file_id": "1pl47kQudDiSxEzU8iQWfuxlhiVuNX-R-", "timestamp": 1723137143378 }, { "file_id": "17x0w277MiY5ivEWz8uyWo31bJOImWmP5", "timestamp": 1723113587188 }, { "file_id": "1UywhX5YevChc5stK6azqyMBOxBjgB4YL", "timestamp": 1723101313203 }, { "file_id": "13KoS5TcPLNrCujtp9KhfCZGXLnL7w7Qm", "timestamp": 1719644856617 } ] }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.12.9" } }, "nbformat": 4, "nbformat_minor": 4 }