{ "cells": [ { "cell_type": "markdown", "id": "097ce009-a7a8-45c7-90f4-dd6f8bbb8228", "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/Concepts/Concepts.ipynb)" ] }, { "cell_type": "markdown", "id": "3ddf717a-91f1-4237-8fb2-5d94371f2e4a", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# Concepts\n", "\n", "## **1. Problem Description**\n", "\n", "**Concepts** is a word-guessing game where players communicate ideas through visual icons. There are two roles: the **Clue-Giver** and the **Guesser**. A shared set of visual icons, each with a known description, is available to both players. Here are some sample icons:\n", "\n", "\n", "\n", "The Clue-Giver first selects a **secret**, which is a word or phrase, and then provides a **hint** about it by pointing to an **ordered sequence** of icons from the shared set — speaking or writing is not allowed.\n", "\n", "The order of the icons in the hint is meaningful:\n", "\n", "- The **first icon** typically represents the core idea of the secret.\n", "- The **subsequent icons** provide supporting context that helps clarify or elaborate on the main concept.\n", "\n", "### Example 1\n", "\n", "The following hint might be interpreted as *a place where a job that fights fire takes place* — in other words, a **fire station**:\n", "\n", "\n", "\n", "If the icon order is reversed, it could instead suggest *a job that fights fire in a house* — pointing to a **firefighter**:\n", "\n", "\n", "\n", "### Example 2\n", "\n", "Icons can take on different meanings depending on their context. For example, the heart icon can appear in the following hint, which suggests *a tool used by doctors to listen to the heart* — a **stethoscope**:\n", "\n", "\n", "\n", "The same heart icon might instead appear in a hint that implies *a fictional character that is both dead and alive* — pointing to a **zombie**:\n", "\n", "\n", "\n", "At Home-Stage, contestants had developed an AI program that predicts outcomes based on a sequence of hints. It's fun. However, your friend has now challenged you: \n", "*\"Guessing is easy, but can you make an AI system that can give a good clue as well?\"*\n", "\n", "In fact, they further challenged you to see if you can make an AI system that can provide a good clue so that another AI system can guess your keyword!\n", "\n", "To make the challenge more interesting, we now play the typical Concept game. To recall, our previous Concept game was simplified so that a clue could only consist of a single sequence of markers.\n", "\n", "Now, you may provide up to **4 sequences of markers**!\n", "\n", "With this, we can express complex ideas better. Considering the following that utilizes 3 sequences of markers to explain a **samurai**:\n", "\n", "\n", "\n", "But wait, there's more. To make the challenge even more interesting, the game will now include some keywords that are not typically present in a Concept game, such as \"International Olympiad.\"\n", "\n", "Are you up to the challenge?\n", "\n", "\n", "\n", "**New AI-Powered Format:**\n", "We've replaced the human guesser with an **AI Guesser**. To streamline game play:\n", "\n", "1. The target word (*label*) will always be selected from a predefined set (`options`).\n", "2. Hints must be an **ordered sequence of markers** chosen exclusively from a fixed set of **118 candidate markers**.\n", "\n", "**Terminologies**\n", "\n", "To ensure clarity and consistency, we are standardizing key terms across all materials.\n", "\n", "- **label**: The target answer (or \"secret\") to be identified.\n", "- **options**: The predefined candidate set from which all valid *labels* are selected.\n", "- **marker**: An icon representing a concept, accompanied by its text description.\n", "- **hints**: An **ordered sequence** of *markers* provided to the AI guesser to help identify the *label*.\n", "\n", "Your task is to provide **hints** for each *label* to help the **AI guesser** identify it. For example, when the target label is `\"microphone\"`, your program may generate four hint sequences like:\n", "\n", "1. **Hint 1**: \n", " `[\"Object-Box\", \"Electronic-Computing\", \"Mouth-Taste\", \"Ear-Sound-Hearing\", \"Tool-Construction\"]`\n", "2. **Hint 2**: \n", " `[\"Music-Song\", \"Television-Program-Show\", \"Work-Occupation\", \"Use - Action-Do - Verbe-Button\"]`\n", "3. **Hint 3**: \n", " `[\"Black\", \"Metal\", \"Plastic-Rubber\", \"Cylinder\", \"Circle-Ring\"]`\n", "4. **Hint 4**: \n", " `[\"Arm-Hand-Finger\", \"Happy-Positive\", \"Expression - Quote-Talking-Words\", \"Life-Heart-Love\"]`\n", "\n", "**Note**: The above example is for illustrative purposes only. The program should generate lists of IDs but not strings; please refer to both `3. Task` and the [baseline.ipynb](https://ioai.bohrium.com/notebooks/26681337682).\n", "\n", "## **2. Dataset**\n", "\n", "The structure of the provided dataset is as follows:\n", "\n", "```\n", "datasets/\n", "├── train/\n", "│ └── A huggingface dataset\n", "└── hint_descriptions/\n", " └── A huggingface dataset\n", "\n", "\n", "os.environ.get(\"DATA_PATH\")/\n", "└── test/\n", " ├── test_a/\n", " │ └── A huggingface dataset\n", " └── test_b/\n", " └── A huggingface dataset\n", "```\n", "\n", "1. Training set: files in this folder are used for model training. It contains:\n", " - `train/`: A huggingface dataset with a single split `'train'`, with 30 examples, each containing:\n", " - `label`: string - the target keyword/answer\n", " - `options`: sequence of strings - list of 100 possible choices\n", " - `hint_descriptions/`: A huggingface dataset with a single split `'train'`, with 118 markers and their descriptions:\n", " - `ID`: int64 - unique identifier for each marker\n", " - `Description`: string - textual description of what the marker represents\n", " - `image`: Image - visual representation of the marker\n", "\n", "2. Test sets: Located at `os.environ.get(\"DATA_PATH\")/test/`. These will be inaccessible during development and will only be available in the evaluation environment:\n", " - `test_a/`: A huggingface dataset with a single split `'test'` containing 150 examples for leaderboard A evaluation\n", " - `test_b/`: A huggingface dataset with a single split `'test'` containing 150 examples for final scoring\n", " Both test datasets contain the same structure as the training set (`label` and `options` fields).\n", "\n", "## **3. Task**\n", "\n", "Your task is to provide **hint** for each *label* to help the **AI guesser** identify it. You are required to develop a program that takes two inputs:\n", "\n", "1. A string `label` (your secret *label*)\n", "2. The `options` list (100 candidate choices for the guesser)\n", "\n", "The `label` is guaranteed to be one of the `options`.\n", "\n", "Additionally, the program will utilize the predefined `candidate markers`.\n", "\n", "\n", "\n", "\n", "This program should return a list of lists of integers for each `label`, representing the hints(i.e. the sequences of markers). Specifically:\n", "\n", "- The returned list must contain **no more than 4** sequences.\n", "- Each sequence can contain **up to 8 integers**.\n", "- Each integer represents the ID of a marker in the clue.\n", "\n", "Your hints will then be given to a black-box AI guesser. You will score a point if the black-box AI guesser can correctly guess your secret keyword based on your hints.\n", "\n", "## **4. Submission**\n", "\n", "Submit a notebook that generates `submission.zip`, which includes `clues_a.jsonl` and `clues_b.jsonl`, the clues for testset a and b, respectively, in `json` format. Refer to the baseline notebook for how to generate these files and the specific structure of the `jsonl` files. Please make sure to follow the naming and structuring conventions.\n", "\n", "Contestants may submit model files. **If submitting model files, contestants must create a corresponding dataset on the Bohrium platform.** Only **one** dataset **can** be submitted for this task, and its size **must not** exceed 2GB. Preloaded datasets and models will be automatically mounted on the test machine, **eliminating the need for manual mounting during submission.**\n", "\n", "Additionally, contestants are permitted to use larger external models to assist in developing their submission.\n", "\n", "## **5. Score**\n", "\n", "Your clue is evaluated using two metrics:\n", "\n", "### Hits@10\n", "\n", "= 1 if the secret word is in the top 10 guesses from the AI, else 0.\n", "\n", "### NDCG@10 (Normalized Discounted Cumulative Gain) \n", "Rewards the correct guess more if it appears higher in the list.\n", "\n", "If the secret word is at rank *i* (1-based):\n", "\n", "$$\n", "\\text{NDCG@10} = \\frac{1}{\\log_2(i + 1)}\n", "$$\n", "\n", "**Examples:**\n", "- Rank 1 → 1.00 \n", "- Rank 2 → ~0.63 \n", "- Rank 4 → ~0.43 \n", "- Rank 10 → ~0.29\n", "\n", "### Final Score\n", "\n", "Your final score will be a combination of both, specifically, it will be 0.9 Hits@10 + 0.1 NDCG@10.\n", "\n", "The scoring means that you'll get a significant point as long as the guesser can guess the secret keyword correctly, but more point is given if the guesser can predict the secret keyword earlier.\n", "\n", "\n", "## **6. Baseline & Available Tools**\n", "\n", "- Below you can find the baseline solution.\n", "- The training set and pretrained models are in `training_set` folder.\n", "- The highest score by the Scientific Committee for this task is 0.54, this score is used for score unification.\n", "- The baseline score by the Scientific Committee for this task is 0.20, this score is used for score unification.\n", "\n", "\n", "### AI-Guesser API\n", "\n", "You can assess the AI-guesser for you to play around with. See the following code on how to access the guesser. It is recommended to implement exponential retry logic as network failures might occur. \n", "\n", "```python\n", "guesser_response = httpx.post(f\"{API_URL}/guess\", json={\n", " \"clues\": clues,\n", " \"options\": options\n", " }, headers={\n", " \"Authorization\": f\"Bearer {SCORER_API_KEY}\"\n", " }, timeout=60).json()\n", "```\n", "\n", "**Important**: The AI-Guesser API will not be available on the inference machines. In other words, do **NOT** call the api in your submission notebooks. This is only for you to validate/train your model locally. You may attach your model weights, training data, etc. via a Bohrium dataset. Refer to the Requirements section.\n", "\n", "### Environment\n", "\n", "We installed `vllm`, `sglang` and `unsloth` in environment for LLM inference and fine tuning. \n", "Additionally, we provide access to the following huggingface models via a `training_set`:\n", "\n", "#### Embedding Models\n", "```\n", "sentence-transformers/all-MiniLM-L6-v2\n", "sentence-transformers/all-MiniLM-L12-v2\n", "sentence-transformers/all-mpnet-base-v2\n", "sentence-transformers/paraphrase-mpnet-base-v2\n", "sentence-transformers/paraphrase-MiniLM-L6-v2\n", "intfloat/e5-small\n", "intfloat/e5-base\n", "intfloat/e5-large\n", "intfloat/e5-small-v2\n", "intfloat/e5-base-v2\n", "intfloat/e5-large-v2\n", "intfloat/multilingual-e5-small\n", "intfloat/multilingual-e5-base\n", "Alibaba-NLP/gte-modernbert-base\n", "Snowflake/snowflake-arctic-embed-xs\n", "Snowflake/snowflake-arctic-embed-s\n", "Snowflake/snowflake-arctic-embed-m\n", "Snowflake/snowflake-arctic-embed-m-long\n", "Snowflake/snowflake-arctic-embed-l\n", "BAAI/bge-large-en\n", "BAAI/bge-base-en\n", "BAAI/bge-small-en\n", "BAAI/bge-large-en-v1.5\n", "BAAI/bge-base-en-v1.5\n", "BAAI/bge-small-en-v1.5\n", "WhereIsAI/UAE-Large-V1\n", "mixedbread-ai/mxbai-embed-large-v1\n", "```\n", "\n", "#### Small LLMs\n", "\n", "```\n", "Qwen/Qwen3-0.6B\n", "Qwen/Qwen2.5-0.5B\n", "Qwen/Qwen2.5-0.5B-Instruct\n", "unsloth/Qwen3-0.6B\n", "facebook/opt-350m\n", "facebook/opt-125m\n", "```\n", "\n", "\n", "## **7. Requirements**\n", "\n", "### Overall Requirements\n", "\n", "- Maximum submission limit: **15 times**. Only successful submissions (i.e., those receive a score on Leaderboard A) will be counted toward the submission limit.\n", "- Testing environment restrictions: The test machine will run your Notebook within **10 minutes**. If the execution time exceeds **10 minutes**, the system will forcibly terminate and return a feedback of “Timeout” or “Failed”.\n", "- Data and model submission: In this task, contestants should submit a Notebook and have the option to submit 1 attached dataset generated by themselves. The dataset must not exceed `2GB` in total size. You are warned that attaching a very large dataset might prolong the testing process, as the dataset needs to be mounted to the inference machine. While this process does not count towards the execution time limit, it will take longer for you to be able to see and select your submissions.\n", "- Network: For the on-site stage, the test machine cannot connect to the internet. In other words, downloading commands such as 'pip' and 'conda' or trying to call APIs will not work. Specific to this problem, the testing machines cannot access the guessor API nor the LLM proxy.\n", "\n", "### API Access Limitations\n", "\n", "Your token will grant you 12,500 `POST` requests to `/guess` endpoint of the AI-guesser API. \n", "\n", "- If successful, this will return a dictionary in the form `{'guesses': ['firefighter', 'fire inspector', 'fire marshal', 'fire warden', 'fire safety officer', 'smokejumper', 'pyrotechnician', 'firewatcher', 'chef', 'cook'], 'message': 'Generated 10 guesses'}`. \n", "\n", "- If unsuccessful, this will either raise an `HTTPStatusError` and return `{'detail': 'error message'}`, or return `{'guesses': [], 'message': 'unable to generate guesses'}`. \n", "- Usually, the former is because you have exceeded the 12,500 limit of your token, or you tried to make more than 1000 requests within 1 minute, and the latter is because your clues exceeded 4 sequences or exceeded 8 markers in 1 sequence. \n", "- Refer to the error message for details.\n", "- There might be 1-2 failures in 1000 requests, 'retry' mechanism is provided in [baseline.ipynb](https://ioai.bohrium.com/notebooks/26681337682).\n", "\n", "\n" ] }, { "cell_type": "markdown", "id": "fc6bbc24", "metadata": {}, "source": [ "### Imports" ] }, { "cell_type": "code", "execution_count": null, "id": "26a701aa", "metadata": {}, "outputs": [], "source": [ "import vllm\n", "from vllm import LLM, SamplingParams\n", "from vllm.sampling_params import GuidedDecodingParams\n", "from pydantic import BaseModel" ] }, { "cell_type": "code", "execution_count": null, "id": "ab3b9844-a68b-437d-9a29-4c24f2827878", "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": "markdown", "id": "ce0b4e27-a439-4608-b71c-e393157c2e5a", "metadata": {}, "source": [ "**Note on Output Determinism**\n", "\n", "In the above code block, we fix the random seed to ensure that results are reproducible when running the baseline model alone. This is a common practice to eliminate output variance caused by stochastic operations.\n", "However, in this specific task, your model is required to interact dynamically with an AI guesser. The guesser is powered by a large language model, which may produce different responses to the same input due to inherent randomness in its decoding process. Therefore, even when given the same set of hints, the guesser’s answers may vary across runs.\n", "As a result, you may observe fluctuations in the reported scores across multiple identical submissions. This is expected behavior and does not indicate a bug in the evaluation system." ] }, { "cell_type": "markdown", "id": "f46cc2bf", "metadata": {}, "source": [ "### Accessing AI-Guesser\n", "\n", "You can asses the AI-guesser for you to play around with, through the API_URL server. See the following code on how to access the guesser.\n", "\n", "Your token will grant you $12,500$ `POST` requests to `/guess`. You will also be limited to $1000$ calls per minute.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a021e386", "metadata": {}, "outputs": [], "source": [ "API_URL = \"https://concepts-judge-server-production-1188.up.railway.app\"\n", "# This url will not be accessible on the inference/testing machines. Do not try to call the api in your submitted code.\n", "# The testing machine will use a secret url to do call API for evalutaion.\n", "# SCORER_API_KEY = \"sk-ioai-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\" # If you want to use API, use the api key provided to you.\n", "# If you do not know how to use it. Just use the model we provide to you." ] }, { "cell_type": "code", "execution_count": null, "id": "20ffe741", "metadata": {}, "outputs": [], "source": [ "import math, random\n", "import httpx\n", "from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type, retry_if_exception\n", "\n", "class GameClient:\n", " def ndcg_at_10(self, predictions, correct_answer):\n", " if correct_answer not in predictions:\n", " return 0.0\n", " try:\n", " rank = predictions[:10].index(correct_answer) + 1\n", " except ValueError:\n", " return 0.0\n", "\n", " return 1 / math.log2(rank + 1)\n", "\n", " def hits_at_10(self, predictions, correct_answer):\n", " return 1.0 if correct_answer in predictions[:10] else 0.0\n", "\n", " def __init__(self):\n", " self._random_options = ['gym', 'dinosaur', 'camel', 'desk', 'chicken', 'suitcase', 'thief', 'penguin', 'bat', 'painter', 'yogurt', 'chocolate', 'football', 'wallet', 'magician', 'shoes', 'bank', 'church', 'chewing gum', 'fashion', 'chainsaw', 'escalator', 'scarf', 'lawyer', 'eagle', 'credit card', 'garden hose', 'glider', 'crosswalk', 'subway', 'fireworks', 'marshmallow', 'cookies', 'curtains', 'dining room', 'cars', 'wedding', 'guitar', 'coffee', 'mouse', 'meat', 'scale', 'train tracks', 'zebra', 'fairy', 'quit', 'museum', 'kangaroo', 'surfboard', 'cheese', 'nightmare', 'jellyfish', 'koala', 'strawberry', 'tiger', 'mailbox', 'kettle', 'potato', 'janitor', 'lighthouse', 'crocodile', 'charger', 'doctor', 'peacock', 'peanut', 'popcorn', 't-shirt', 'fertilizer', 'keyboard', 'umbrella', 'pool', 'watercolor', 'mango', 'xylophone', 'bathroom', 'ice cube', 'giraffe', 'garage', 'cabin', 'plankton', 'pig', 'vulture', 'frame', 'polar bear', 'microscope', 'snake', 'skeleton', 'rocket', 'backpack', 'jacket', 'bedroom', 'castle', 'horse', 'dragonfly', 'hotel', 'cyclist', 'mask', 'restaurant', 'toothpaste', 'angel', 'whistle', 'wrestling', 'eclipse', 'hermit crabs', 'horn', 'boxers', 'volcano', 'fire station', 'toothbrush', 'egg', 'straw', 'rice', 'diamond', 'vitamins', 'tricycle', 'bottle-opener', 'panther', 'ice skates', 'theater', 'gas mask', 'game console', 'path', 'scorpion', 'snowboard', 'crab', 'pie', 'octopus', 'mustache', 'pepper grinder', 'swings', 'palm tree', 'well', 'sewing machine', 'key', 'station', 'mosque', 'chameleon', 'cherry', 'parrot', 'leggings', 'radio', 'brick', 'sunflower', 'hammer', 'carrot', 'radar', 'kite', 'bathtub', 'rhinoceros', 'spoon', 'orchestra', 'gravity', 'flute', 'lipstick', 'school', 'meteorite', 'politician', 'ladder', 'lawnmower', 'computer', 'wheel', 'airport', 'firefighter', 'porch', 'police station', 'queen', 'mayonnaise', 'alumunium foil', 'lion', 'helmet', 'teacher', 'tea', 'fan', 'piano', 'snail', 'farmer', 'harbor', 'nurse', 'sunglasses', 'bee', 'postal worker', 'market', 'plank', 'steering wheel', 'squirrel', 'netting', 'dragon', 'cafeteria', 'millennium', 'spinach', 'fork', 'cabbage', 'ping-pong', 'lock', 'submarine', 'dictionary', 'vaccine', 'soda', 'skirt', 'toaster', 'shorts', 'circus', 'flowerpot', 'lobster', 'rainbow', 'cockroach', 'frog', 'basket ball', 'chilli pepper', 'pajamas', 'crossword', 'light bulb', 'drill', 'beaver', 'daisy', 'river', 'yo-yo', 'harmonica', 'soap', 'igloo', 'sausage', 'deer', 'sailboat', 'fish', 'mosquito', 'can', 'rat', 'frying pan', 'barcode', 'sunscreen', 'ferret', 'whale', 'duck', 'shirt', 'vacuum', 'detective', 'perfume', 'seal', 'raincoat', 'alien', 'bull', 'nest', 'butterfly', 'eraser', 'hedgehog', 'panda', 'refrigerator', 'monocle', 'window', 'kitchen', 'mole', 'speaker', 'waiter', 'salad', 'dolphin', 'storm', 'drums', 'spiderweb', 'bicycle', 'monkey', 'flamingo', 'prison', 'bowling', 'pencil sharpner', 'photo', 'printer', 'robe', 'seahorse', 'doorbell', 'gloves', 'alcohol', 'diving suit', 'shotgun', 'hairbrush', 'cactus', 'ambulance', 'hula hoop', 'snowman', 'mountain', 'unicorn', 'suit', 'cake', 'cow', 'sled', 'boar', 'barbecue', 'trash can', 'slingshot', 'banana', 'dam', 'hat', 'milk', 'shell', 'broom', 'fisherman', 'bucket', 'bell', 'tracktor', 'fly', 'spider', 'carpet', 'coconut tree', 'movie theater', 'socks', 'soldier', 'watering can', 'accountant', 'microphone', 'toothpick', 'wolf', 'trumpet', 'apple', 'library', 'cork', 'zipper', 'pan', 'doghouse', 'dynamite', 'swan', 'grasshopper', 'beach', 'starfish', 'police officer', 'board game', 'magnet', 'cucumber', 'fire extinguisher', 'sundial', 'mechanic', 'lighter', 'shovel', 'shark', 'notebook', 'ostrich', 'bodyguard', 'binoculars', 'parachute', 'drone', 'kiwi', 'ghost', 'baker', 'robot', 'postcard', 'horseshoe', 'karaoke', 'billiards', 'palace', 'hospital', 'compass', 'truck', 'holiday', 'lake', 'cave', 'space station', 'mushroom', 'magnifying glass', 'fox', 'bread', 'rose', 'windmill', 'pirate', 'earring', 'hunter', 'princess', 'calculator', 'clown', 'watch', 'pilot', 'mustard', 'swordfish', 'darts', 'microwave oven', 'plumber', 'sword']\n", "\n", " @retry(\n", " stop=stop_after_attempt(3),\n", " wait=wait_exponential(multiplier=1, min=4, max=10),\n", " retry=retry_if_exception_type((httpx.TimeoutException, httpx.ConnectError, httpx.RequestError)) |\n", " retry_if_exception(lambda e: isinstance(e, httpx.HTTPStatusError) and e.response.is_server_error) # Retry on connection errors or server side errors.\n", " )\n", " def _make_api_call(self, clues, options):\n", " response = httpx.post(f\"{API_URL}/guess\", json={\n", " \"clues\": clues,\n", " \"options\": options\n", " }, headers={\n", " \"Authorization\": f\"Bearer {SCORER_API_KEY}\"\n", " }, timeout=60)\n", " \n", " response.raise_for_status()\n", " \n", " guesser_response = response.json()\n", " \n", " if \"guesses\" not in guesser_response:\n", " raise ValueError(f\"Unable to generate guesses: {guesser_response}\")\n", " if not isinstance(guesser_response[\"guesses\"], list):\n", " raise ValueError(f\"Guesses is not a list: {guesser_response}\")\n", " \n", " return guesser_response\n", "\n", " def simulate_game(self, clues, expected_answer, distractors = []):\n", " expected_answer = expected_answer.lower()\n", " if expected_answer in distractors:\n", " options = []\n", " else:\n", " options = [expected_answer]\n", " if len(distractors) > 0:\n", " options.extend([d.lower() for d in distractors])\n", " options = options[:100]\n", "\n", " # fill in options until the size is 100 with random options\n", " # set seed based on the expected_answers\n", " if len(options) < 100:\n", " random.seed(expected_answer)\n", " options.extend(random.choices(self._random_options, k=100-len(options)))\n", " # then shuffle\n", " random.shuffle(options)\n", "\n", " try:\n", " guesser_response = self._make_api_call(clues, options)\n", " predictions = [p.lower() for p in guesser_response[\"guesses\"]]\n", " return {\n", " \"predictions\": predictions,\n", " \"hit@10\": self.hits_at_10(predictions, expected_answer),\n", " \"NDCG@10\": self.ndcg_at_10(predictions, expected_answer)\n", " }\n", " \n", " except Exception as e:\n", "\n", " if isinstance(e, httpx.HTTPStatusError):\n", " print(f\"HTTP Status Error {e.response.status_code}: {e.response.text}\")\n", " try:\n", " error_detail = e.response.json().get(\"detail\", \"Unknown error\")\n", " print(f\"Error details: {error_detail}\")\n", " except:\n", " print(f\"Could not parse error response {e.response.text}\")\n", " \n", " elif isinstance(e, ValueError):\n", " print(f\"Value error: {e}\")\n", "\n", " elif isinstance(e, httpx.TimeoutException):\n", " print(\"request timed out after retries\")\n", "\n", " elif isinstance(e, httpx.ConnectError):\n", " print(f\"Could not connect to {API_URL} after retries\")\n", "\n", " elif isinstance(e, httpx.RequestError):\n", " print(f\"Request error after retries: {e}\")\n", "\n", " else:\n", " print(f\"Unknown error: {e}\")\n", "\n", " return {\n", " \"predictions\": [],\n", " \"hit@10\": 0.0,\n", " \"NDCG@10\": 0.0\n", " }" ] }, { "cell_type": "code", "execution_count": null, "id": "a7929fa5", "metadata": {}, "outputs": [], "source": [ "game_client = GameClient()\n", "\n", "# the clue for samurai\n", "clue = [[4, 35],\n", " [16, 116, 85, 106],\n", " [43, 102]]\n", "\n", "'''\n", "# You can refer to the following code for calling the judge api. Don't forget to comment out this part before submission, otherwise your notebook will not run.\n", "# you can call simulate game, given your clues and the expected answer.\n", "# the game client will randomly generate 100 options.\n", "# The answer will be automatically added as one of the options.\n", "# note that capitalization does not matter, the client will treat all texts as lowercase.\n", "prediction = game_client.simulate_game(clue, \"Samurai\")\n", "\n", "# it will print the prediction, as well as the score of the prediction (more later)\n", "print(prediction)\n", "\n", "# you might also want to put your own distractors, which will be added into the set of options.\n", "# It will randomly fill in the rest of options until it has 100 options\n", "prediction = game_client.simulate_game(clue, \"Samurai\",\n", " distractors=['cat', 'dog', 'castle', 'blacksmith', 'martial artist', 'hunter',\n", " 'warrior', 'knight', 'viking', 'janissary', 'chevalier', 'imperial guard', 'swordsman', 'gladiator', 'marksman', 'police officer'])\n", "print(prediction)\n", "'''" ] }, { "cell_type": "markdown", "id": "17c8559a-540a-4a10-80dd-bf2a452bc098", "metadata": {}, "source": [ "### Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "8730c968", "metadata": {}, "outputs": [], "source": [ "from datasets import load_from_disk\n", "TRAIN_PATH = \"./training_set/\" \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", "DESCRIPTIONS = TRAIN_PATH + \"hint_descriptions\"\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", "\n", "hint_descriptions = load_from_disk(DESCRIPTIONS)['train']\n", "hint_descriptions = {\n", " x['ID']: {'description': x['Description'], 'icons': x['image']}\n", " for x in hint_descriptions\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "f1804b3b", "metadata": {}, "outputs": [], "source": [ "valid_hints = [x['description'] for x in hint_descriptions.values()]\n", "hint_to_id = {\n", " x['description']: xid\n", " for xid, x in hint_descriptions.items()\n", "}\n", "\n", "print(valid_hints)\n", "print(hint_to_id)" ] }, { "cell_type": "code", "execution_count": null, "id": "118f6ada", "metadata": {}, "outputs": [], "source": [ "TRAINING_SET = TRAIN_PATH + \"train\"\n", "dev = load_from_disk(TRAINING_SET)['train']\n", "print(dev)\n", "print(dev[0])" ] }, { "cell_type": "code", "execution_count": null, "id": "50a07d22", "metadata": {}, "outputs": [], "source": [ "from typing import Literal, List, Optional\n", "ValidHint = Literal[*valid_hints]\n", "\n", "class Hints(BaseModel):\n", " hints_1: List[ValidHint]\n", " hints_2: List[ValidHint]\n", " hints_3: List[ValidHint]\n", " hints_4: List[ValidHint]\n", "\n", " def to_result(self):\n", " hints = [self.hints_1, self.hints_2, self.hints_3, self.hints_4]\n", " result = []\n", " for hintlist in hints:\n", " cur_hintlist = [hint_to_id[hint] for hint in hintlist[:8]]\n", " result.append(cur_hintlist)\n", " return result\n", "\n", "class ClueGiver:\n", " def __init__(self):\n", " self.llm = LLM(\"/bohr/models-b08n/v1/models/facebook/opt-125m\")\n", " # The models in select_hf_models are deployed automatically in the testing machine. \n", " # You notebook can access the select_hf_models even if you do not mount it along with notebook.\n", " json_schema = Hints.model_json_schema()\n", " self.sampling_params = SamplingParams(\n", " guided_decoding=GuidedDecodingParams(\n", " json=json_schema,\n", " ),\n", " max_tokens=5096,\n", " frequency_penalty=0.5,\n", " presence_penalty=0.8\n", " )\n", "\n", " def construct_clues(self, answers: List[str], options: List[List[str]]):\n", " prompts = []\n", " for answer, options in zip(answers, options):\n", " prompt = (\n", " f\"Your valid list of clues are: {valid_hints}. \"\n", " \"Your job is a clue giver. You will help the guesser pick the correct answer from a range of options.\"\n", " \"You must output at least 1 hint and at most 8 hints for each sequence. \"\n", " \"Please output a json object with the key 'hints_1', 'hints_2', 'hints_3', and 'hints_4', and the value being a list of hints. \"\n", " \"Example: {\"\n", " \"'hints_1': [\\\"Work\\\\nOccupation\\\", \\\"Idea\\\\nIntelligence\\\\nConcept\\\"], \"\n", " \"'hints_2': [\\\"Fauna\\\\nAnimal\\\", \\\"Flora\\\\nPlant\\\\nNature\\\"], \"\n", " \"'hints_3': [\\\"Object\\\\nBox\\\", \\\"Art\\\\nSculpture - Painting\\\\nDrawing - Cartoon\\\"], \"\n", " \"'hints_4': [\\\"Work\\\\nOccupation\\\", \\\"Idea\\\\nIntelligence\\\\nConcept\\\"]\"\n", " \"}\"\n", " f\"The options the guesser has to choose from are: {options}.\"\n", " f\"Please construct sequences of hints that are most relevant to the answer {answer}. \"\n", " )\n", " prompts.append(prompt)\n", " # batch mode: pass a list of prompts\n", " hints_batch = self.llm.generate(prompts=prompts, sampling_params=self.sampling_params)\n", " results = []\n", " for i, hints in enumerate(hints_batch):\n", " # print(hints.outputs)\n", " # print(f\"len of token ids: {len(hints.outputs[0].token_ids)}\")\n", " txt = hints.outputs[0].text\n", " # print(txt)\n", " try:\n", " hints_obj = Hints.model_validate_json(txt)\n", " results.append(hints_obj.to_result())\n", " except Exception as e:\n", " print(f\"Error parsing hints for answer {answers[i]}: {e}\")\n", " results.append([[1,2,3,4]])\n", " return results" ] }, { "cell_type": "code", "execution_count": null, "id": "c21319c5", "metadata": {}, "outputs": [], "source": [ "clue_giver = ClueGiver()" ] }, { "cell_type": "code", "execution_count": null, "id": "01a07b30", "metadata": {}, "outputs": [], "source": [ "res_clues = clue_giver.construct_clues([x['label'] for x in dev], [x['options'] for x in dev])" ] }, { "cell_type": "code", "execution_count": null, "id": "bf138945", "metadata": {}, "outputs": [], "source": [ "'''\n", "# You may use the following code to evaluate your model. Don't forget to comment out this section before submission, as the inference machine will not have access to the judge api.\n", "from tqdm import tqdm\n", "from concurrent.futures import ThreadPoolExecutor, as_completed\n", "\n", "def simulate_one(i_data):\n", " i, data = i_data\n", " clues = res_clues[i]\n", " prediction = game_client.simulate_game(clues, data['label'])\n", " return prediction\n", "\n", "predictions = []\n", "with ThreadPoolExecutor() as executor:\n", " futures = [executor.submit(simulate_one, (i, data)) for i, data in enumerate(dev)]\n", " for f in tqdm(as_completed(futures), total=len(futures)):\n", " predictions.append(f.result())\n", "\n", "print(\"Final Score: \")\n", "print(sum([p['hit@10'] for p in predictions]) * 0.9 + sum([p['NDCG@10'] for p in predictions]) * 0.1)\n", "'''" ] }, { "cell_type": "markdown", "id": "a516aaa2-0153-4e7d-bb31-b802fe702c00", "metadata": {}, "source": [ "### Clean Gpu Cache" ] }, { "cell_type": "code", "execution_count": null, "id": "a33b2a1e", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "del clue_giver\n", "\n", "torch.cuda.empty_cache()" ] }, { "cell_type": "markdown", "id": "dda5169b", "metadata": {}, "source": [ "### Submission\n", "\n", "You do not have to submit your training notebook (you can if you would like to). For resource-efficiency and reliability reasons, we encourage you to upload your trained model weights (if you have one) attached to your submission notebook, instead of submitting your entire training process. For help with submitting model weight files, refer to section 5 in the Bohrium Guide. Your submission notebook only has to include the test inference section below.\n", "\n", "You need to save your answers to testset A and testset B in separate `jsonl` files, `clues_a.jsonl` and `clues_b.jsonl`, as shown below. `clues_a` and `clues_b` should be lists of clues (each clue being a list of lists of integers). You need to zip the files together into `submission.zip`. The file names are important. You must follow the naming conventions otherwise the evaluation script will not be able to find your answers." ] }, { "cell_type": "code", "execution_count": null, "id": "3582fdfe", "metadata": {}, "outputs": [], "source": [ "clue_giver = ClueGiver() # Initialize your model. You can load model weights here." ] }, { "cell_type": "code", "execution_count": null, "id": "e35c1193", "metadata": {}, "outputs": [], "source": [ "import os\n", "if os.environ.get('DATA_PATH'):\n", " TEST_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n", "else:\n", " TEST_PATH = \"/bohr/test-66r2/v1/\" # Fallback for local testing\n", "\n", "testset_a = load_from_disk(os.path.join(TEST_PATH, \"test/test_a\"))[\"test\"]\n", "testset_b = load_from_disk(os.path.join(TEST_PATH, \"test/test_b\"))[\"test\"]\n", "clues_a = clue_giver.construct_clues([x['label'] for x in testset_a], [x['options'] for x in testset_a])\n", "clues_b = clue_giver.construct_clues([x['label'] for x in testset_b], [x['options'] for x in testset_b])" ] }, { "cell_type": "code", "execution_count": null, "id": "4ef60d7a", "metadata": {}, "outputs": [], "source": [ "import zipfile\n", "import json\n", "\n", "def write_clues(clues: List[List[List[int]]], path: str):\n", " with open(path, 'w') as f:\n", " for c in clues:\n", " f.write(json.dumps(c) + '\\n')\n", "\n", "write_clues(clues_a, \"clues_a.jsonl\")\n", "write_clues(clues_b, \"clues_b.jsonl\")\n", "\n", "with zipfile.ZipFile('submission.zip', 'w') as zipf:\n", " zipf.write('clues_a.jsonl')\n", " zipf.write('clues_b.jsonl')" ] }, { "cell_type": "code", "execution_count": null, "id": "515d63b6-19d5-425f-85d6-d6ea9471047f", "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "del clue_giver\n", "torch.cuda.empty_cache()" ] } ], "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": 5 }