{ "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/Restroom/Restroom.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Restroom Icon Matching\n", "\n", "## 1. Problem Description\n", "\n", "This task focuses on training a model to learn the relationship between **male and female restroom icons from the same restroom**. Based on labeled training data, you are required to train a matching model that, given a query image, finds its **cross-gender counterpart** (e.g., match a male icon in its cropped image to its female counterpart in its original image), under the constraint that both icons come from the **same restroom**.\n", "\n", "For example, for a query image (i.e., a male icon in cropped image) shown below in Fig1, its corresponding counterpart is shown in Fig2 (i.e., a female icon in original image which is from the same restroom).\n", "\n", "| | |\n", "| ------------------------------------------------------------ | ------------------------------------------------------------ |\n", "\n", "\n", "\n", "## 2. Dataset\n", "\n", "**(1) Training Set:** \n", "\n", "Used for model training. Directory structure:\n", "\n", "```bash\n", "train/\n", "├── crop/ # Cropped icons\n", "│ ├── female/ 1.png, 2.png, ...\n", "│ └── male/\n", "└── orig/ # Original icons\n", " ├── female/\n", " └── male/\n", "```\n", "\n", "Each subfolder contains icons named from `1.png` to `82.png`, where the number indicates the restroom ID. For each restroom, there are four images (note that four images from the same restroom will share one same unique id across all four subfolders):\n", "\n", "- `crop/female/i.png` → Cropped female icon \n", "- `crop/male/i.png`  → Cropped male icon \n", "- `orig/female/i.png` → Original female icon \n", "- `orig/male/i.png`  → Original male icon \n", "\n", "**(2) Validation Set and Test Set:** \n", "\n", "Either the validation set (test_a) or the test set (test_b) contains two subfolders:\n", "\n", "```bash\n", "test_a/ (or test_b/)\n", "├── query/ # Cropped icons to be matched\n", "└── gallery/ # Candidate original icons\n", "```\n", "\n", "- `query/`: **cropped** icons that need to be matched. \n", "- `gallery/`: pool of **original** icons to match from. \n", "- Note that:\n", " - Unlike the training split, the filenames in `query/` and `gallery/` are independently numbered and shuffled, which means that matching cannot rely on the ids\n", " - For each cropped icon in `query/` there are exactly two originals in `gallery/` (one male, one female from the same restroom), which means $\\text{len}(\\text{gallery})=2 * \\text{len}(\\text{query})$\n", "- All images are in `.png` format. \n", "- The validation set has $10$ images in its `query/` folder, and the test set has $30$ images in its `query/` folder.\n", "\n", "## 3. Task\n", "\n", "For each image in the `query/` folder, predict the image in `gallery/` that:\n", "- Is of the **opposite gender**, and\n", "- Comes from the **same restroom**\n", "\n", "This matching should be accomplished **using your trained model**. \n", "\n", "## 4. Submission Requirements\n", "\n", "You must submit a notebook named `submission.ipynb`, which should include:\n", "\n", "- Model training process (using `train/` data) \n", "- Matching process for both test sets (`test_a/` and `test_b/`) \n", "- The notebook must output two `.npy` files:\n", "```bash\n", "submission_a.npy # Matching results for validation set (test_a).\n", "submission_b.npy # Matching results for test set (test_b).\n", "```\n", "\n", "Each npz file is a one-dimensional array with a size equal to the number of queries, and each value in the array corresponds to the image ID in the gallery.\n", "\n", "For example, one valid `submission_a.npy` may looks like this:\n", "\n", "\n", "You can also find an example output format in [baseline.ipynb](https://ioai.bohrium.com/notebooks/81153159178).\n", "\n", "## 5. Score\n", "\n", "- If the submission finishes within the time limit, the score is calculated as: \n", " $$\n", " \\text{Score} = \\frac{\\text{Number of correct matches}}{\\text{Total queries}}\n", " $$\n", " \n", " which will be a float number between $0.0$ and $1.0$ (inclusive).\n", " \n", "- Submissions that exceed the time limit will receive a score of **0**.\n", "\n", "## 6. Baseline and 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.90$ in Leaderboard B, this score is used for score unification.\n", "- The baseline score by the Scientific Committee for this task is $0.77$ in Leaderboard B, this score is used for score unification.\n" ] }, { "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": { "id": "I5GTjH_JDD6-" }, "outputs": [], "source": [ "def sort_paths_by_number(path_list):\n", " \"\"\"\n", " Sort based on the numerical values of the filenames in the path,\n", " assuming all filenames can be converted to integers.\n", " \"\"\"\n", " def get_file_number(path):\n", " file_name = os.path.splitext(os.path.basename(path))[0]\n", " return int(file_name)\n", "\n", " path_list.sort(key=get_file_number)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GaCBe4plvK-e", "outputId": "b3e76723-7f79-45d7-878b-5619d684e25d", "papermill": { "duration": 6.61984, "end_time": "2022-02-04T11:33:28.148721", "exception": false, "start_time": "2022-02-04T11:33:21.528881", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "# import clip-vit model\n", "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "absolute_model_path = \"/bohr/clip-lnw6/v2/ViT-B-32.pt\" \n", "# The clip-model is deployed automatically in the testing machine. You cannot mounted other pretrained models.\n", "# You notebook can access the above model even if you do not mount it along with notebook.\n", "\n", "# TRAIN_PATH = /bohr/train-s5kb/v1/train\n", "# The training set is deployed automatically in the testing machine. \n", "# Your notebook can access the TRAIN_PATH even if you do not mount it along with notebook.\n", "\n", "\n", "# import the weights\n", "model, preprocess = clip.load(absolute_model_path, device=DEVICE)\n", "model.eval() # evaluation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Eq7CnxKBvK-e", "papermill": { "duration": 0.034656, "end_time": "2022-02-04T11:33:28.209027", "exception": false, "start_time": "2022-02-04T11:33:28.174371", "status": "completed" }, "tags": [] }, "outputs": [], "source": [ "def infer(img_paths):\n", " \"\"\"\n", " Compute L2‑normalized feature embeddings for a list of image file paths using the CLIP visual encoder.\n", " \"\"\"\n", " # print(len(img_paths)) # for debug\n", " embeddings = []\n", " for path in tqdm(img_paths):\n", " img = Image.open(path)\n", " x = preprocess(img)\n", " x = x.type(torch.float16).unsqueeze(0).to(DEVICE)\n", "\n", " with torch.no_grad():\n", " emb = model.visual.forward(x)\n", "\n", " embeddings.append(emb)\n", "\n", " embeddings = torch.cat(embeddings)\n", " embeddings = F.normalize(embeddings, p=2, dim=1)\n", "\n", " return embeddings" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gPOB1nCkEUoJ" }, "outputs": [], "source": [ "def match_images(BASE_DATA_DIR, result_path):\n", " \"\"\"\n", " For each query image in BASE_DATA_DIR/query, find its best matching image\n", " in BASE_DATA_DIR/gallery by computing cosine similarity of CLIP embeddings,\n", " then save 1‑based match indices to result_path as a .npy file.\n", " \"\"\"\n", " QUERY_DIR = BASE_DATA_DIR / \"query\"\n", " NON_QUERY_DIR = BASE_DATA_DIR / \"gallery\"\n", "\n", " query_image_paths = list(QUERY_DIR.glob(\"*.png\"))\n", " non_query_image_paths = list(NON_QUERY_DIR.glob(\"*.png\"))\n", "\n", " query_image_paths_str = [str(p) for p in query_image_paths]\n", " non_query_image_paths_str = [str(p) for p in non_query_image_paths]\n", "\n", " sort_paths_by_number(query_image_paths_str)\n", " sort_paths_by_number(non_query_image_paths_str)\n", "\n", " # print(query_image_paths_str) # for debug\n", "\n", " query_embeddings = infer(query_image_paths_str)\n", " non_query_embeddings = infer(non_query_image_paths_str)\n", " distances = torch.mm(query_embeddings, non_query_embeddings.t())\n", " distances = (distances + 1.) / 2.\n", "\n", " topk_dists, topk_idxs = torch.topk(distances, 11, dim=1) # distances has shape (num_queries, num_non_queries)\n", "\n", " topk_dists, topk_idxs = topk_dists.cpu(), topk_idxs.cpu()\n", "\n", " matches_dists, matches_idxs = topk_dists[:, 1], topk_idxs[:, 1]\n", " matches_dists = matches_dists.cpu().numpy()\n", " matches_idxs = matches_idxs.cpu().numpy()\n", "\n", " for i in range(len(matches_idxs)):\n", " matches_idxs[i]+=1\n", "\n", " # print(matches_idxs) # for debug\n", " np.save(result_path, matches_idxs) # save as .npy file" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "RUtraYPDEz30", "outputId": "e0b44045-e6bf-47c3-e89c-e050760c8e50" }, "outputs": [], "source": [ "\"\"\"the generated submission should be two .npy files\"\"\"\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", "match_images(Path(DATA_PATH + \"test_a\"),\"submission_a.npy\")\n", "match_images(Path(DATA_PATH + \"test_b\"),\"submission_b.npy\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import zipfile\n", "\n", "files_to_zip = ['./submission_a.npy', './submission_b.npy']\n", "zip_filename = 'submission.zip'\n", "\n", "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n", " for file in files_to_zip:\n", " zipf.write(file, os.path.basename(file))\n", "\n", "print(f'{zip_filename} is created succefully!')" ] } ], "metadata": { "accelerator": "GPU", "colab": { "gpuType": "L4", "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 }