File size: 10,284 Bytes
2d5faf0 | 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 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
"\n",
"[IOAI 2024 (Burgas, Bulgaria), On-Site Round](https://ioai-official.org/bulgaria-2024)\n",
"\n",
"[](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": [
"<img src=\"./figs/Help BOBAI Fig 1.png\" width=\"700\">\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
}
|