{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"IOAI\n", "\n", "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n", "\n", "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Chicken_Counting/Solution/Chicken_Counting_Solution.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Chicken Counting: Reference Solution" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 5616, "status": "ok", "timestamp": 1753592556976, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "t-7tiKDEs5N7" }, "outputs": [], "source": [ "import os\n", "import torch\n", "import torch.nn as nn\n", "import torch.nn.functional as F\n", "import torch.optim as optim\n", "from torch.utils.data import Dataset, DataLoader\n", "from datasets import load_from_disk\n", "import logging\n", "from torchvision import transforms\n", "from tqdm import tqdm\n", "import numpy as np\n", "import math\n", "from PIL import Image\n", "import zipfile\n", "from typing import Optional\n", "import random\n", "\n", "np.random.seed(42)\n", "random.seed(42)\n", "torch.manual_seed(42) \n", "torch.cuda.manual_seed(42) \n", "torch.cuda.manual_seed_all(42)\n", "\n", "TRAIN_PATH = \"/bohr/train-adnz/v1/\"\n", "TRAINING_SET = TRAIN_PATH + \"train\"\n", "BASE_MODEL_PATH = TRAIN_PATH + \"base.pth\"\n", "DTYPE = torch.float32\n", "DEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n", "scale = 300.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logging Utilities" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 28, "status": "ok", "timestamp": 1753592562308, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "SMii-32Qs5N9" }, "outputs": [], "source": [ "def logging_level(level='info'):\n", " str_format = '%(asctime)s - %(levelname)s: %(message)s'\n", " if level == 'debug':\n", " logging.basicConfig(level=logging.DEBUG, format=str_format, datefmt='%Y-%m-%d %H:%M:%S')\n", " elif level == 'info':\n", " logging.basicConfig(level=logging.INFO, format=str_format, datefmt='%Y-%m-%d %H:%M:%S')\n", " return logging\n", "\n", "\n", "class BatchLossLogger:\n", " def __init__(self, log_interval=100):\n", " self.losses = []\n", " self.batch_number = 0\n", " self.log_interval = log_interval\n", "\n", " def log(self, loss):\n", " self.losses.append(loss)\n", " self.batch_number += 1\n", " if self.batch_number % self.log_interval == 0:\n", " logging.info(f'Batch No. {self.batch_number:7d} - loss: {loss:.6f}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Traininng Your Model\n", "### Model Definition\n", "Pretrained weights of the FeatureExtraction model is provided, along with a function to load them. And a completed UNet structure is applied." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 113, "status": "ok", "timestamp": 1753592562424, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "VWPcNgjUvXq5" }, "outputs": [], "source": [ "class DoubleConv(nn.Module):\n", " \"\"\"(convolution => [BN] => ReLU) * 2\"\"\"\n", "\n", " def __init__(self, in_channels, out_channels, mid_channels=None):\n", " super().__init__()\n", " if not mid_channels:\n", " mid_channels = out_channels\n", " self.double_conv = nn.Sequential(\n", " nn.Conv2d(in_channels, mid_channels, kernel_size=3, padding=1, bias=False),\n", " nn.BatchNorm2d(mid_channels),\n", " nn.ReLU(inplace=True),\n", " nn.Conv2d(mid_channels, out_channels, kernel_size=3, padding=1, bias=False),\n", " nn.BatchNorm2d(out_channels),\n", " nn.ReLU(inplace=True)\n", " )\n", "\n", " def forward(self, x):\n", " return self.double_conv(x)\n", "\n", "\n", "class Down(nn.Module):\n", " \"\"\"Downscaling with maxpool then double conv\"\"\"\n", "\n", " def __init__(self, in_channels, out_channels):\n", " super().__init__()\n", " self.maxpool_conv = nn.Sequential(\n", " nn.MaxPool2d(2),\n", " DoubleConv(in_channels, out_channels)\n", " )\n", "\n", " def forward(self, x):\n", " return self.maxpool_conv(x)\n", "\n", "\n", "class Up(nn.Module):\n", " \"\"\"Upscaling then double conv\"\"\"\n", "\n", " def __init__(self, in_channels, out_channels, bilinear=True):\n", " super().__init__()\n", "\n", " # if bilinear, use the normal convolutions to reduce the number of channels\n", " if bilinear:\n", " self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)\n", " self.conv = DoubleConv(in_channels, out_channels, in_channels // 2)\n", " else:\n", " self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)\n", " self.conv = DoubleConv(in_channels, out_channels)\n", "\n", " def forward(self, x1, x2):\n", " x1 = self.up(x1)\n", " # input is CHW\n", " diffY = x2.size()[2] - x1.size()[2]\n", " diffX = x2.size()[3] - x1.size()[3]\n", "\n", " x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,\n", " diffY // 2, diffY - diffY // 2])\n", " # if you have padding issues, see\n", " # https://github.com/HaiyongJiang/U-Net-Pytorch-Unstructured-Buggy/commit/0e854509c2cea854e247a9c615f175f76fbb2e3a\n", " # https://github.com/xiaopeng-liao/Pytorch-UNet/commit/8ebac70e633bac59fc22bb5195e513d5832fb3bd\n", " x = torch.cat([x2, x1], dim=1)\n", " return self.conv(x)\n", "\n", "\n", "class OutConv(nn.Module):\n", " def __init__(self, in_channels, out_channels):\n", " super(OutConv, self).__init__()\n", " self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n", "\n", " def forward(self, x):\n", " return self.conv(x)\n", "\n", "class UNet(nn.Module):\n", " def __init__(self, n_channels, n_classes, bilinear=False):\n", " super(UNet, self).__init__()\n", " self.n_channels = n_channels\n", " self.n_classes = n_classes\n", " self.bilinear = bilinear\n", "\n", " self.inc = (DoubleConv(n_channels, 64))\n", " self.down1 = (Down(64, 128))\n", " self.down2 = (Down(128, 256))\n", " self.down3 = (Down(256, 512))\n", " factor = 2 if bilinear else 1\n", " self.down4 = (Down(512, 1024 // factor))\n", " self.up1 = (Up(1024, 512 // factor, bilinear))\n", " self.up2 = (Up(512, 256 // factor, bilinear))\n", " # self.up2 = (Up(512, 64, bilinear))\n", " self.up3 = (Up(256, 128 // factor, bilinear))\n", " self.up4 = (Up(128, 64, bilinear))\n", " self.outc = (OutConv(64, n_classes))\n", "\n", " def forward(self, x):\n", " x1 = self.inc(x)\n", " x2 = self.down1(x1)\n", " x3 = self.down2(x2)\n", " x4 = self.down3(x3)\n", " x5 = self.down4(x4)\n", " x = self.up1(x5, x4)\n", " x = self.up2(x, x3)\n", " x = self.up3(x, x2)\n", " x = self.up4(x, x1)\n", " logits = self.outc(x)\n", " logits = F.relu(logits)\n", " return logits" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 13, "status": "ok", "timestamp": 1753592562452, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "5glRHs1Fs5N_" }, "outputs": [], "source": [ "class FeatureExtraction(nn.Module):\n", " def __init__(self, in_channels=3):\n", " super(FeatureExtraction, self).__init__()\n", " self.conv1 = nn.Conv2d(in_channels, 64, kernel_size=3, padding=2, dilation=2)\n", " self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=2, dilation=2)\n", " self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n", "\n", " self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=2, dilation=2)\n", " self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding=2, dilation=2)\n", " self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n", "\n", "\n", " def forward(self, x):\n", " x = F.relu(self.conv1(x))\n", " x = F.relu(self.conv2(x))\n", " x = self.pool2(x)\n", " x = F.relu(self.conv3(x))\n", " x = F.relu(self.conv4(x))\n", " x = self.pool4(x)\n", "\n", " return x\n", "\n", " def load_pretrained_weights_partial(self, weights_path, num_layers=4):\n", " save_model = torch.load(weights_path)\n", " partial_state_dict = {}\n", " expected_layers = [\n", " 'feature_extraction.conv1.weight', 'feature_extraction.conv1.bias',\n", " 'feature_extraction.conv2.weight', 'feature_extraction.conv2.bias',\n", " 'feature_extraction.conv3.weight', 'feature_extraction.conv3.bias',\n", " 'feature_extraction.conv4.weight', 'feature_extraction.conv4.bias',\n", " ]\n", " state_dict = {k.split('.', 1)[-1]: v for k, v in save_model.items() if k in expected_layers[:2 * num_layers]}\n", " model_dict = self.state_dict()\n", "\n", " for k in state_dict:\n", " if k in model_dict:\n", " partial_state_dict[k] = state_dict[k]\n", " print(k)\n", "\n", " self.load_state_dict(partial_state_dict)\n", "\n", "\n", "class ChickenCounting(nn.Module):\n", " def __init__(self):\n", " super(ChickenCounting, self).__init__()\n", " self.feature_extraction = FeatureExtraction()\n", " self.unet = UNet(n_channels=128, n_classes=1)\n", "\n", "\n", " def forward(self, x):\n", " x = self.feature_extraction(x)\n", " x = self.unet(x)\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading the Dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 14, "status": "ok", "timestamp": 1753592562479, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "u-Pb0-1Ps5OA" }, "outputs": [], "source": [ "train_dataset = load_from_disk(TRAINING_SET)\n", "\n", "image_transform = transforms.Compose([\n", " transforms.ToTensor(),\n", "])\n", "\n", "def collate_fn(batch, scale = scale):\n", " return {\n", " \"image\": torch.stack([image_transform(item[\"image\"]) for item in batch]),\n", " \"density\": torch.stack([torch.tensor(item[\"density\"], dtype=DTYPE).unsqueeze(0) * scale for item in batch])\n", " }\n", "\n", "train_loader = DataLoader(train_dataset, batch_size=1, shuffle=True, collate_fn=collate_fn)\n", "val_loader = DataLoader(train_dataset, batch_size=1, shuffle=False, collate_fn=collate_fn)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Training" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 35, "status": "ok", "timestamp": 1753592562517, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "RN2VW6yTs5OB" }, "outputs": [], "source": [ "def train_chickenfcn(model, train_loader, val_loader, optimizer, scheduler, num_epochs, device, save_path):\n", " model.train()\n", " criterion_mse = torch.nn.MSELoss(reduction='sum').to(device)\n", " criterion_mae = torch.nn.L1Loss(reduction='sum').to(device)\n", " best_loss = float('inf')\n", " print(train_loader.__len__())\n", "\n", " for epoch in range(num_epochs):\n", " train_loss_mse = 0.0\n", " train_loss_mae = 0.0\n", "\n", " train_loader_tqdm = tqdm(train_loader, desc=f'Epoch {epoch + 1}/{num_epochs}', leave=False)\n", "\n", " for i, data in enumerate(train_loader_tqdm, 0):\n", " inputs, targets = data[\"image\"], data[\"density\"]\n", " inputs = inputs.to(device).float()\n", " targets = targets.to(device).float()\n", " # print(targets.shape)\n", " # t = np.sum((targets[0] / scale).cpu().numpy().squeeze())\n", " # print(t)\n", "\n", " optimizer.zero_grad()\n", "\n", " outputs = model(inputs)\n", "\n", " loss_mse = criterion_mse(outputs, targets)\n", " loss_mae = criterion_mae(outputs, targets)\n", " loss_mae.backward()\n", "\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0)\n", "\n", " optimizer.step()\n", " train_loss_mse += loss_mse.item()\n", " train_loss_mae += loss_mae.item()\n", "\n", " train_loader_tqdm.set_postfix({'Train MSE Loss': loss_mse.item(), 'Train MAE Loss': loss_mae.item()})\n", "\n", " train_loss_mse /= (len(train_loader))\n", " train_loss_mae /= (len(train_loader))\n", " logging.info(\n", " f'Epoch [{epoch + 1}/{num_epochs}], Train MSE loss: {train_loss_mse:.8f}, MAE loss: {train_loss_mae:.8f}')\n", "\n", " scheduler.step()\n", "\n", " # Validation\n", " model.eval()\n", " val_loss_mse = 0.0\n", " val_loss_mae = 0.0\n", "\n", " val_loader_tqdm = tqdm(val_loader, desc=f'Validation Epoch {epoch + 1}/{num_epochs}', leave=False)\n", "\n", " with torch.no_grad():\n", " for i, data in enumerate(val_loader_tqdm, 0):\n", " inputs, targets = data[\"image\"], data[\"density\"]\n", " inputs = inputs.to(device).float()\n", " targets = targets.to(device).float()\n", "\n", " outputs = model(inputs)\n", " mse_loss = criterion_mse(outputs, targets)\n", " mae_loss = criterion_mae(outputs, targets)\n", " val_loss_mse += mse_loss.item()\n", " val_loss_mae += mae_loss.item()\n", "\n", " val_loader_tqdm.set_postfix(\n", " {'Validation MSE Loss': mse_loss.item(), 'Validation MAE Loss': mae_loss.item()})\n", "\n", " val_loss_mse /= (len(val_loader))\n", " val_loss_mae /= (len(val_loader))\n", " logging.info(\n", " f'Epoch [{epoch + 1}/{num_epochs}], Validation MSE Loss: {val_loss_mse:.8f}, MAE Loss: {val_loss_mae:.8f}')\n", "\n", " # Save Model\n", " if val_loss_mae < best_loss:\n", " best_loss = val_loss_mae\n", " torch.save(model.state_dict(), save_path)\n", "\n", " print('Finished Training ChickenFCN')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 917027, "status": "ok", "timestamp": 1753593479556, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "oAoNLtC5s5OC", "outputId": "f700e0dc-5a4c-4f5f-bdc9-2aa074bc3d60" }, "outputs": [], "source": [ "logging = logging_level('info')\n", "logging.debug('use debug level logging setting')\n", "\n", "################################################################################\n", "# Experiment Settings\n", "################################################################################\n", "learning_rate = 1e-4\n", "lr_decay = 1e-5\n", "weight_decay = 0.0001\n", "save_path = \"model.pth\"\n", "\n", "epochs = 30\n", "\n", "################################################################################\n", "# Dataset paths\n", "################################################################################\n", "\n", "model = ChickenCounting().to(DEVICE)\n", "model.feature_extraction.load_pretrained_weights_partial(BASE_MODEL_PATH)\n", "print('load model success')\n", "\n", "optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)\n", "# optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=momentum, weight_decay=weight_decay)\n", "scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=1 - lr_decay)\n", "\n", "logging.info('Begin training single view model...')\n", "train_chickenfcn(model, train_loader, val_loader, optimizer, scheduler, epochs, DEVICE, save_path=save_path)\n", "logging.info('Finished training single view model.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Evaluate Model" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "executionInfo": { "elapsed": 3, "status": "ok", "timestamp": 1753593479563, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "_PuMTMDKs5OE" }, "outputs": [], "source": [ "def evaluate(model, val_loader, device, scale): # Function used for final scoring.\n", " model.eval() # Set the model to evaluation mode\n", "\n", " # Initialize metrics\n", " mse = 0.0\n", " mae = 0.0\n", " predict_num = 0.0\n", " true_num = 0.0\n", " rate = 0.0\n", "\n", " with torch.no_grad(): # Disable gradient calculation for inference\n", " for i, data in enumerate(val_loader, 0):\n", " inputs, targets = data[\"image\"], data[\"density\"]\n", " inputs = inputs.to(device).float() # Move inputs to device and convert to float\n", " targets = targets.to(device).float() # Move targets to device and convert to float\n", "\n", " # Get the model predictions\n", " outputs = model(inputs) / scale # Adjusting for the scaling factor\n", "\n", " # Convert tensors to numpy for visualization and metrics calculation\n", " inputs_np = inputs.cpu().numpy() # Convert inputs to numpy\n", " targets_np = targets.cpu().numpy() # Convert targets to numpy\n", " outputs_np = outputs.cpu().numpy() # Convert outputs to numpy\n", " # imshow_res(inputs_np, targets_np, outputs_np, scale) # Uncomment to visualize results\n", "\n", " # Calculate true and predicted sums for comparison\n", " t = np.sum((targets[0] / scale).cpu().numpy().squeeze()) # Ground truth sum\n", " g = np.sum(outputs.cpu().numpy().squeeze()) # Predicted sum\n", " print(f'NO.{i} true_sum={t}, get_sum={g}, abs={abs(t - g)}, rate={abs(1 - g / t)}')\n", "\n", " # Update metrics\n", " predict_num += g\n", " true_num += t\n", " rate += abs(1 - g / t)\n", " mae += abs(t - g)\n", " mse += abs(t - g) * abs(t - g)\n", "\n", " # Calculate average metrics across all batches\n", " mae /= len(val_loader)\n", " mse /= len(val_loader)\n", " predict_num /= len(val_loader)\n", " true_num /= len(val_loader)\n", " rate /= len(val_loader)\n", "\n", " # Log the results\n", " logging.info(\n", " f'test ---- Score: {math.exp(-rate):.3f}, MSE: {mse:.4f}, MAE: {mae:.4f}, Chicken_avg: {predict_num:.4f}')\n", " return math.exp(-rate)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 12124, "status": "ok", "timestamp": 1753593491690, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "0yFgonMZs5OF", "outputId": "f4a0fe9d-d185-4133-8f8e-4bc2e2c8fa77" }, "outputs": [], "source": [ "model.load_state_dict(torch.load(save_path, map_location=DEVICE))\n", "model.to(DEVICE)\n", "evaluate(model, val_loader, DEVICE, scale)" ] }, { "cell_type": "markdown", "metadata": { "id": "xVQtmZ55s5OG" }, "source": [ "## Submission\n", "Please read through the following code carefully. Make sure to following the file naming conventions." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "executionInfo": { "elapsed": 22942, "status": "ok", "timestamp": 1753593514634, "user": { "displayName": "陈红涛", "userId": "16480124546172497377" }, "user_tz": -480 }, "id": "siCztiUEs5OI", "outputId": "79ea01ce-a3c9-45fb-a511-01815386db75" }, "outputs": [], "source": [ "test_path = os.environ.get(\"DATA_PATH\", \"datasets\")\n", "\n", "def collate_fn(batch): # The test datasets will not provide target densities\n", " return torch.stack([image_transform(item[\"image\"]) for item in batch])\n", "\n", "test_dataset = load_from_disk(os.path.join(test_path, \"test_a\"))\n", "test_loader = DataLoader(test_dataset, batch_size=16, shuffle=False, collate_fn=collate_fn)\n", "\n", "predictions = []\n", "model.eval()\n", "with torch.no_grad():\n", " for batch in tqdm(test_loader):\n", " outputs = model(batch.to(DEVICE)) / scale\n", " predictions.append(outputs.cpu().numpy())\n", "\n", "pred_a = np.concatenate(predictions, axis=0)\n", "\n", "del test_dataset\n", "del test_loader\n", "del predictions\n", "\n", "test_dataset = load_from_disk(os.path.join(test_path, \"test_b\"))\n", "test_loader = DataLoader(test_dataset, batch_size=16, shuffle=False, collate_fn=collate_fn)\n", "\n", "predictions = []\n", "with torch.no_grad():\n", " for batch in tqdm(test_loader):\n", " outputs = model(batch.to(DEVICE)) / scale\n", " predictions.append(outputs.cpu().numpy())\n", "\n", "pred_b = np.concatenate(predictions, axis=0)\n", "\n", "np.savez('submission.npz', pred_a=pred_a, pred_b=pred_b) # save your submissions in an npz file with the keys `pred_a` and `pred_b`" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "T4", "provenance": [] }, "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 }