{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
""
]
},
{
"cell_type": "markdown",
"source": [
"# 🎧 Operation Night Watch: Teaching an Old Classifier New Sounds\n",
"\n",
"Welcome! In this task you will take a **deployed audio event classifier** and teach it to recognize **13 brand-new sound classes** — *without* destroying what the model already knows.\n",
"## The story\n",
"\n",
"Your company runs a network of low-power acoustic monitoring stations. The production model on these stations is an **Audio Spectrogram Transformer (AST)** that recognizes **16 everyday and wildlife sound classes**: dogs, roosters, thunderstorms, sea waves, even keyboard typing.\n",
"\n",
"Two new customers just signed contracts:\n",
"\n",
"- 🌲 **A national park** wants to detect **illegal logging and poaching activity**: axes, chainsaws, hand saws, generators, vehicle engines, helicopters, gunshots, fireworks, and crackling fires.\n",
"- 🦗 **An entomology institute** runs an acoustic insect survey and needs the model to distinguish **four singing insect species** by their calls: *Pterophylla camellifolia*, *Cicada orni*, *Gryllus campestris*, and *Tettigonia viridissima*.\n",
"\n",
"That is **13 new classes**, and the upgraded model must keep serving the existing customers — so the 16 old classes must keep working too.\n",
"\n",
"## Why can't we just retrain from scratch?\n",
"\n",
"Your base model is built on Audio Spectrogram Transformer (AST). AST starts from large-scale ImageNet + AudioSet pre-training (millions of clips, GPU-weeks). Then the model was trained as a classifier for 16 base classes from `train.classes.csv`. Your budget is a **single GPU for up to 10 mins of training time**. The pre-trained model is a way to get strong audio features — treat it as a precious, irreplaceable artifact and build on top of it. Retraining the model from scratch on all data samples is too expensive.\n",
"\n",
"## The rules\n",
"\n",
"1. ✅ You **must start from the provided checkpoint** (`model/`) and reuse its encoder weights. You may add parameters (extra classifier rows, adapters, …) and fine-tune any subset of weights\n",
"2. ✅ Your final model must classify **all 29 classes** (16 old + 13 new) in a single forward pass\n",
"3. ❌ No training from scratch, and no other pre-trained audio models\n",
"4. ⏱️ Keep it lightweight: everything should run on a single GPU ~ 10 mins of training time\n",
"\n",
"Your submission is scored as a **50/50 weighted average of accuracy on old classes and accuracy on new classes** (details in Section 4) — forgetting the old classes is exactly as costly as failing to learn the new ones."
],
"metadata": {
"id": "koRGdrUfcV6V"
}
},
{
"cell_type": "markdown",
"source": [
"# First things first: Set up Google Drive"
],
"metadata": {
"id": "WGX4yY3saawH"
}
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cuFh08ajXN50",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "5e8df7a1-8e2e-4b3d-b8de-74b5ee863f3a"
},
"outputs": [],
"source": [
"!pip -q install gdown\n",
"import gdown, random, os\n",
"\n",
"# dataset.zip mirrors in your IOAI-2026/AudioClassifier/data folder. Each file ID has its\n",
"# own Google Drive download quota, so we try them in random order to survive heavy load.\n",
"MIRRORS = [\n",
" \"12XaRWYDsHq3eBwrgZ0QnEOffflS_dlff\", # dataset.zip\n",
" \"1iUYDtKxXM1GSG5VNJ3r9847hqhWEiQRq\", # dataset_m2.zip\n",
" \"112F9IFfn3_UtOPwSM1cGbuAL7Ci2aBP_\", # dataset_m3.zip\n",
"]\n",
"random.shuffle(MIRRORS)\n",
"\n",
"ZIP = \"dataset.zip\"\n",
"if not (os.path.exists(ZIP) and os.path.getsize(ZIP) > 10**9):\n",
" for fid in MIRRORS:\n",
" try:\n",
" gdown.download(id=fid, output=ZIP, quiet=False)\n",
" except Exception as e:\n",
" print(\"mirror failed:\", fid, \"->\", e)\n",
" if os.path.exists(ZIP) and os.path.getsize(ZIP) > 10**9:\n",
" break\n",
" if os.path.exists(ZIP):\n",
" os.remove(ZIP)\n",
" else:\n",
" raise RuntimeError(\"All dataset mirrors are rate-limited right now. \"\n",
" \"Wait ~30 min and re-run.\")\n",
"\n",
"!unzip -q -o dataset.zip -d /content/dataset"
]
},
{
"cell_type": "code",
"source": [
"from pathlib import Path\n",
"\n",
"LOCAL_DATA_DIR = Path(\"/content/dataset\")\n",
"\n",
"if not LOCAL_DATA_DIR.exists():\n",
" raise FileNotFoundError(\n",
" \"Dataset not found. Please run the dataset download/unzip cell first.\"\n",
" )\n",
"\n",
"print(\"Dataset found:\")\n",
"for i in LOCAL_DATA_DIR.iterdir():\n",
" print(i)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "AGkL7pGLYQ16",
"outputId": "1f3ddec4-c70c-4d73-e867-8a5f60b57408"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Dataset found:\n",
"/content/dataset/train.csv\n",
"/content/dataset/model\n",
"/content/dataset/audio\n",
"/content/dataset/__MACOSX\n",
"/content/dataset/fine_tune.csv\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"# 0. Setup\n",
"\n",
"What you have inside the ```/content/audioclassifier_data```:\n",
"\n",
"| Artifact | Description |\n",
"|---|---|\n",
"| `model/` | Pre-trained AST checkpoint (16-class classifier) |\n",
"| `train.csv` | The retained subset of the *old* data — 16 classes, `train`/`val` splits |\n",
"| `fine_tune.csv` | The *new* data — 13 classes, `train`/`val` splits |\n",
"| `audio/` | All audio clips (5 s, mono, 16 kHz `.wav`) |\n"
],
"metadata": {
"id": "STIBLQsAcEel"
}
},
{
"cell_type": "code",
"source": [
"import json\n",
"import os\n",
"import warnings\n",
"from pathlib import Path\n",
"\n",
"import librosa\n",
"import librosa.display\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"import pandas as pd\n",
"import torch\n",
"from IPython.display import Audio, HTML, display\n",
"from sklearn.manifold import TSNE\n",
"from sklearn.metrics import ConfusionMatrixDisplay, accuracy_score, confusion_matrix\n",
"from torch.utils.data import DataLoader, Dataset\n",
"from transformers import ASTFeatureExtractor, ASTForAudioClassification\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"os.environ.setdefault(\"PYTORCH_ENABLE_MPS_FALLBACK\", \"1\")\n",
"\n",
"OLD_CSV = LOCAL_DATA_DIR / \"train.csv\"\n",
"NEW_CSV = LOCAL_DATA_DIR / \"fine_tune.csv\"\n",
"CHECKPOINT = LOCAL_DATA_DIR / \"model\"\n",
"SR = 16_000\n",
"BATCH_SIZE = 8\n",
"DEVICE = \"cuda\" if torch.cuda.is_available() else (\"mps\" if torch.backends.mps.is_available() else \"cpu\")\n",
"\n",
"config = json.loads((CHECKPOINT / \"config.json\").read_text())\n",
"old_id2label = {int(k): v for k, v in config[\"id2label\"].items()}\n",
"NUM_OLD = len(old_id2label)\n",
"print(f\"device = {DEVICE} | checkpoint knows {NUM_OLD} classes\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "wnzsBQQ_bzZ9",
"outputId": "7d8d41a2-07eb-43f2-f4bc-536d12f80907"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"device = cpu | checkpoint knows 16 classes\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"old_df = pd.read_csv(OLD_CSV)\n",
"\n",
"new_df = pd.read_csv(NEW_CSV)\n",
"new_df[\"target\"] = new_df[\"target\"]\n",
"new_id2label = dict(new_df[[\"target\", \"category\"]].drop_duplicates().values)\n",
"new_id2label = {int(k): v for k, v in sorted(new_id2label.items())}\n",
"\n",
"id2label = {**old_id2label, **new_id2label} # all 29 classes\n",
"label2id = {v: k for k, v in id2label.items()}\n",
"NUM_TOTAL = len(id2label)\n",
"print(f\"total classes after expansion: {NUM_TOTAL}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "WsWMGUcgdudu",
"outputId": "03eb1d89-eb0d-4939-ba3d-57582fe47e90"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"total classes after expansion: 29\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## 1. Meet the data\n",
"\n",
"### The old world: 16 base classes\n",
"\n",
"These are the classes the deployed model already recognizes. `train.csv` is the small retained subset — note how few training clips per class are left.\n"
],
"metadata": {
"id": "8nXz3V6yeINQ"
}
},
{
"cell_type": "code",
"source": [
"old_summary = (old_df.groupby([\"target\", \"category\", \"split\"]).size()\n",
" .unstack(fill_value=0)[[\"train\", \"val\"]])\n",
"print(f\"old-data clips: {len(old_df)}\")\n",
"old_summary"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/",
"height": 600
},
"id": "X4qUN6eZeUN0",
"outputId": "21e9afe7-ed82-4587-8a17-1cc6be7e0489"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"old-data clips: 491\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"split train val\n",
"target category \n",
"0 Dog 12 8\n",
"1 Rooster 12 8\n",
"2 Pig 12 8\n",
"3 Cow 22 8\n",
"4 Frog 35 23\n",
"5 Cat 12 8\n",
"6 Hen 12 8\n",
"7 Sheep 3 8\n",
"8 Crow 12 8\n",
"9 Mouse Click 22 8\n",
"10 Keyboard Typing 3 8\n",
"11 Thunderstorm 62 23\n",
"12 Sea Waves 12 8\n",
"13 Bird Chirping 35 23\n",
"14 Wolf Howl 23 15\n",
"15 Rain 7 23"
],
"text/html": [
"\n",
"
| \n", " | split | \n", "train | \n", "val | \n", "
|---|---|---|---|
| target | \n", "category | \n", "\n", " | \n", " |
| 0 | \n", "Dog | \n", "12 | \n", "8 | \n", "
| 1 | \n", "Rooster | \n", "12 | \n", "8 | \n", "
| 2 | \n", "Pig | \n", "12 | \n", "8 | \n", "
| 3 | \n", "Cow | \n", "22 | \n", "8 | \n", "
| 4 | \n", "Frog | \n", "35 | \n", "23 | \n", "
| 5 | \n", "Cat | \n", "12 | \n", "8 | \n", "
| 6 | \n", "Hen | \n", "12 | \n", "8 | \n", "
| 7 | \n", "Sheep | \n", "3 | \n", "8 | \n", "
| 8 | \n", "Crow | \n", "12 | \n", "8 | \n", "
| 9 | \n", "Mouse Click | \n", "22 | \n", "8 | \n", "
| 10 | \n", "Keyboard Typing | \n", "3 | \n", "8 | \n", "
| 11 | \n", "Thunderstorm | \n", "62 | \n", "23 | \n", "
| 12 | \n", "Sea Waves | \n", "12 | \n", "8 | \n", "
| 13 | \n", "Bird Chirping | \n", "35 | \n", "23 | \n", "
| 14 | \n", "Wolf Howl | \n", "23 | \n", "15 | \n", "
| 15 | \n", "Rain | \n", "7 | \n", "23 | \n", "