{ "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/Chicken_Counting.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Chicken Counting\n", "\n", "## **1. Problem Description**\n", "\n", "As the leader of an AI research team collaborating with Silkie chicken farmers, you are tasked with solving a critical challenge in traditional free-range farming. Accurate counting of livestock is crucial for both farmers and insurance companies, as factors like disease outbreaks and predator invasions can significantly impact the survival rate of these chickens in a short time. While insurance coverage helps mitigate farming risks, the claims process requires precise counting of livestock losses. Your farmers have approached your team for help in developing more accurate, automated counting systems. The challenge before your research team is to develop an optimized Silkie chicken counting model using density estimation techniques that can provide reliable counts to support both farm management and insurance processes.\n", "\n", "Your team has access to a pretrained feature extractor for Silkie chicken images, but you'll need to design and train the density estimation decoder to create a complete counting solution. Your task is to build upon this foundation by developing an effective decoder architecture and training strategy to achieve accurate chicken counts that farmers and insurance companies can rely on.\n", "\n", "The below figure shows an image in the dataset, as well as the corresponding true density distribution and a predicted density distribution generated by the baseline model. The total density (sum of densities across all areas) is labeled.\n", "\n", "\n", "\n", "## **2. Dataset**\n", "\n", "The structure of the provided Silkie chicken image dataset is as follows:\n", "\n", "```\n", "datasets/\n", "├── train/\n", "│ └── A dataset with features:\n", "│ ├── `image`: `PIL.Image` with RGB channels (3x720x1280)\n", "│ └── `density`: a 2D array of shape 180x320\n", "└── base.pth (Pretrained Model)\n", "\n", "\n", "os.environ.get(\"DATA_PATH\")/\n", "├── test_a/\n", "│ └── A dataset with features:\n", "│ └── `image`: `PIL.Image` with RGB channels (3x720x1280)\n", "└── test_b/\n", " └── A dataset with features:\n", " └── `image`: `PIL.Image` with RGB channels (3x720x1280)\n", "```\n", "\n", "(1) Training set location: `datasets`, files in this folder are used for model fine-tuning. It contains a train folder, which stores a dataset with 100 images and their corresponding density maps.\n", "\n", "(2) Validation set (test_a) and Test set (test_b): These will be used to evaluate scores on Leaderboard A and Leaderboard B, respectively. They will be inaccessible to contestants. Only the score achieved on test set B will be used for final scoring. \n", "\n", "(3) Datasets size:\n", "\n", "- Training set: 100 images.\n", "- Validation set: 100 images.\n", "- Test set: 100 images.\n", "\n", "(4) Validation set (test_a) and Test set (test_b) are not visible.\n", "\n", "(5) Due to limits of computing resources, training density maps are reshaped to $1\\times 180 \\times 320$. **NOTE** the output density map can be viewed as a 2D real number matrix with shape $180\\times 320$, the sum of all matrix values is the count of chickens.\n", "\n", "## **3. Task**\n", "\n", "Your task is to train your own model using the training data to predict density maps, thereby serving the purpose of chicken counting.\n", "\n", "You may extend and optimize the given pretrained model to improve its count prediction accuracy. The pretrained model `base.pth` only contains the weights of the first four layers of the model (the feature extraction model), and the function `load_pretrained_weights_partial` in the baseline code can be used to load these partial weights into your model. You may construct a density decoder `DensityDecoder` and combine it with the pretrained feature extraction module to form a complete data prediction model.\n", "\n", "```\n", "class DensityDecoder(nn.Module):\n", " def __init__(self):\n", " #################################################\n", " # Your code here\n", " #################################################\n", "\n", " def forward(self, x):\n", " #################################################\n", " # Your code here\n", " #################################################\n", " return x\n", "```\n", "\n", "You can also build your own model without the pretrained model we provided.\n", "\n", "This task is the continuation of Satellite Weather Forecasting. A kind remind is the UNET is easily to full GPU memory without any feature engineering. Then, the GPU memory error message will be reported. \n", "\n", "Please follow these rules to achieve a score normally:\n", "\n", "(1) Your model must output the predicted density map.\n", "\n", "(2) Due to limits of computing resources, your output density map should be reshaped to $180 \\times 320$. This is also the shape of target density maps provided in the train dataset.\n", "\n", "## 4. Submission\n", "\n", "Please submit a **submission.ipynb** that includes the following components:\n", "\n", "(1)**Training Code** \n", "\n", "- Include the full training pipeline.\n", "\n", "(2)**Evaluation Code**\n", "- Evaluate your model on the validation set and test set. \n", "\n", "- The output should be saved as **`submission.npz`**. This must be a valid `npz` file containing two arrays `pred_a` and `pred_b`, each with shape `100x1x180x320` (The evaluation script will also accept predictions in the shape of `100x180x320`, if you decide to squeeze the channel dimension).\n", "\n", " **Any result that does not meet the specified size will be considered invalid, resulting in an assessment score of zero.**\n", " \n", "- Each element of the density map should be **no less than zero**, otherwise will result in an assessment score of zero.\n", "\n", "## **5. Scoring**\n", "\n", "You will be scored based on the mean relative error of your model. Relative error is defined by:\n", "\n", "$$\n", "\\text{Relative Error} = \\frac{|y_i - \\hat{y}_i|}{|y_i|}\n", "$$\n", "\n", "where $y_i$ is the true total density for the $i$-th sample, and $\\hat{y}_i$ is the predicted total density for the $i$-th sample.\n", "\n", "Your final score before normalization will be calculated based on your mean relative error, as follows:\n", "\n", "$$\n", "\\text{Score} = \\exp(-\\frac{1}{n} \\sum_{i=1}^{n} \\frac{|y_i - \\hat{y}_i|}{y_i})\n", "$$\n", "\n", "## **6. Baseline & Training Set**\n", "\n", "- Below you can find the baseline solution.\n", "- The dataset is in `training_set` folder.\n", "- The highest score by the Scientific Committee for this task is 0.89, this score is used for score unification.\n", "- The baseline score by the Scientific Committee for this task is 0.71, this score is used for score unification." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Imports" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "import numpy as np\n", "import torch\n", "\n", "seed = 42\n", "\n", "random.seed(seed) # Python built-in random\n", "np.random.seed(seed) # NumPy\n", "torch.manual_seed(seed) # PyTorch (CPU)\n", "torch.cuda.manual_seed(seed) # PyTorch (single GPU)\n", "torch.cuda.manual_seed_all(seed) # PyTorch (all GPUs)\n", "\n", "# Ensures deterministic behavior\n", "torch.backends.cudnn.deterministic = True\n", "torch.backends.cudnn.benchmark = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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 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", "\n", "#Contestants should mount \"counting_problem_train(v1)\" datasets while creating the node.\n", "TRAIN_PATH = \"/bohr/train-adnz/v1/\" #Address of the training set and base.pth\n", "# The training set is deployed automatically in the testing machine. \n", "# You notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n", "TRAINING_SET = TRAIN_PATH + \"train\" #Address of the traninig set \n", "BASE_MODEL_PATH = TRAIN_PATH + \"base.pth\"#Address of the .pth file\n", "DTYPE = torch.float32\n", "DEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n", "scale = 100.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Logging Utilities" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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": [ "### Training Your Model\n", "#### Model Definition\n", "Pretrained weights of the `FeatureExtraction` model is provided in `base.pth` in the training set, along with a function to load them.\n", "`ChickenCounting` is the completed model." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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", " 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 DensityDecoder(nn.Module): # Define your decoder model here.\n", " def __init__(self):\n", " super(DensityDecoder, self).__init__()\n", " self.conv5 = nn.Conv2d(in_channels=128, out_channels=1, kernel_size=3, padding=2, dilation=2)\n", "\n", " def forward(self, x):\n", " x = F.relu(self.conv5(x))\n", " return x\n", "\n", "\n", "class ChickenCounting(nn.Module):\n", " def __init__(self):\n", " super(ChickenCounting, self).__init__()\n", " self.feature_extraction = FeatureExtraction()\n", " self.feature_decoder = DensityDecoder()\n", "\n", " def forward(self, x):\n", " x = self.feature_extraction(x)\n", " x = self.feature_decoder(x)\n", " return x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reading the Dataset\n", "Read the train dataset" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "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]) # Multiply by scale for faster training\n", " }\n", "\n", "train_loader = DataLoader(train_dataset, batch_size=8, 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": [ "### Run Training" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Definition of the training process\n", "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": {}, "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 = 20\n", "\n", "# Training\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", "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\n", "This section validates the model on the train set, which helps contestants understand whether the model is usable and calculate the score on the train set." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Definition of the evaluation function\n", "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": {}, "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": {}, "source": [ "### Submission\n", "This part is to generate the result files for testing and scoring.\n", "Contestants couldn't access the validation set(test_a) and the test set(test_b) locally.\n", "Please read through the following code carefully. Make sure to following the file naming conventions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#DATA_PATH is the secret environment variable to point the address of the validation set and test set on the testing machine. \n", "#Contestants cannot access this address locally.\n", "if os.environ.get('DATA_PATH'): \n", " DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n", "else:\n", " DATA_PATH = \"\" # Fallback for local testing\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(DATA_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(DATA_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 `submission.npz` file with the keys `pred_a` and `pred_b`" ] } ], "metadata": { "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 }