{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"Open" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# πŸ—„οΈ The Analytical Language of John Wilkins\n", "\n", "> *\"These ambiguities, redundancies, and deficiencies recall those attributed by Dr. Franz Kuhn to a certain Chinese encyclopedia called the *Celestial Emporium of Benevolent Knowledge*. On those remote pages it is written that animals are divided into (a) those that belong to the Emperor, (b) embalmed ones, (c) those that are trained, (d) suckling pigs, (e) mermaids, (f) fabulous ones, (g) stray dogs, (h) those that are included in this classification...\"*\n", ">\n", "> β€” Jorge Luis Borges, *The Analytical Language of John Wilkins*\n", "\n", "## The story\n", "\n", "In the seventeenth century a churchman named John Wilkins set out to build a perfect language β€” one in which the very *spelling* of a word would declare the nature of the thing it named. Each animal would be filed under a rigorous tree of yes-and-no distinctions: beast or fish, winged or finned, tame or wild, until the creature stood alone at the end of a single branch, named by the path that led to it.\n", "\n", "The scheme failed, as all such schemes fail. But somewhere a clerk kept building it anyway. He bound every animal of the world into a great **Cabinet of Distinctions** β€” and then, before the index could be written, he died. The drawers remain. Each holds one creature behind a small brass grille, and the creature will not say its name. It will only answer **yes** or **no** to questions about its own nature.\n", "\n", "The Cabinet has come to you with its labels lost. Two lists survived in the clerk's hand:\n", "\n", "- `animals_pool.txt` β€” every creature filed in the Cabinet (~1,400 entries).\n", "- `questions_pool.txt` β€” every distinction the clerk thought to draw (~500 yes/no questions).\n", "\n", "Open a drawer. Ask your distinctions. Find the path that names the beast." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Your task\n", "\n", "Each hidden creature sits inside a sealed oracle called an **Interactor** β€” a brass grille over a drawer, holding one animal. You cannot see it. You may put to it one of two kinds of question:\n", "\n", "| Call | Returns | What you are asking |\n", "|---|---|---|\n", "| `interactor.ask(question)` | `\"yes\"` or `\"no\"` | A yes/no question about the hidden animal. The question must be a line from `questions_pool.txt`. |\n", "| `interactor.guess(animal)` | `\"correct\"` or `\"wrong\"` | \"Is this the hidden animal?\" `\"correct\"` ends the row. The animal must be a word from `animals_pool.txt`. |\n", "\n", "Each question in the pool refers to the creature generically β€” *\"is it a mammal?\"*, *\"does it live in water?\"*, *\"can it fly?\"* β€” and the oracle answers about whichever animal is hidden in that drawer.\n", "\n", "If you submit a question or animal not in the relevant pool, the oracle refuses without spending its strength: a `ValueError` is raised and your budget is unchanged. Typos cost nothing.\n", "\n", "Each drawer will entertain at most **fifteen questions** before the grille falls shut.\n", "\n", "### Scoring\n", "\n", "For each creature:\n", "\n", "```\n", "score = max(0, (1 if you ever guessed correctly else 0) - 0.02 Γ— queries_used)\n", "```\n", "\n", "- Correct guess on question 1 β†’ 0.98\n", "- Correct guess on question 5 β†’ 0.90\n", "- Correct guess on question 15 β†’ 0.70\n", "- Never correct β†’ 0\n", "\n", "Your score is the mean across all creatures in a test set. Tune on `dev`, then run the final cell to get your **`test1`** score β€” that summary table is what you submit a screenshot of. The organizers keep a second, **hidden** test set for official grading, so a solution that genuinely deduces (rather than overfits `dev`/`test1`) is what scores well." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## The oracle\n", "\n", "In plain language, the oracle inside each Interactor is a local language model β€” by default, `Qwen/Qwen2.5-3B-Instruct`. When you call `ask(question)` it prompts the model with:\n", "\n", "```\n", "You are answering a question about one specific animal.\n", "The animal is: .\n", "Answer with a single word, yes or no.\n", "Question: \n", "```\n", "\n", "at temperature 0, parses the first word of the reply, and returns `\"yes\"` or `\"no\"` to your code.\n", "\n", "The model is deterministic (the same `(animal, question)` pair always gives the same answer) and runs entirely inside the Interactor. You are free to run the same model in your own code to **predict** what it will say without spending the oracle's strength β€” that is a large part of what makes a clever solution. Note the oracle answers from the model's *beliefs* about the animal, which are usually right but not infallible; a good solution is robust to the occasional surprising answer." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 1: Setup\n", "\n", "The dataset and helper code (`interactor.py`, `evaluate.py`, the two pools, the dev/test CSVs) live in the shared **`IOAI-2026/AnimalDeduction/dataset`** Drive folder. The cell below just downloads them into Colab β€” no sign-in, no shortcuts, just run it. Use a **GPU** runtime: *Runtime β†’ Change runtime type β†’ T4* (free tier is enough)." ], "outputs": [], "execution_count": null }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "!pip install -q gdown transformers accelerate\n", "\n", "import os, sys\n", "from pathlib import Path\n", "import gdown\n", "\n", "# Dataset + helper code live in the shared IOAI-2026/AnimalDeduction/dataset folder\n", "# (public link). Download locally and import from there β€” no sign-in needed.\n", "LOCAL_DIR = Path('/content/animaldeduction')\n", "if not LOCAL_DIR.exists() or not any(LOCAL_DIR.iterdir()):\n", " gdown.download_folder(id='1YheHvGfQw5YUa7MjdUF0hQC4sdtLZ5UC',\n", " output=str(LOCAL_DIR), quiet=True, use_cookies=False)\n", "\n", "sys.path.insert(0, str(LOCAL_DIR))\n", "os.chdir(LOCAL_DIR)\n", "print('Working directory:', os.getcwd())\n", "print('Files:', sorted(p.name for p in LOCAL_DIR.iterdir()))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 2: Load data and try the oracle\n", "\n", "The `Interactor` owns the hidden gold animal and runs a local LLM (Qwen 2.5 3B Instruct by default) to answer yes/no questions about it. The first `Interactor(...)` instantiation triggers the LLM download (~6 GB on first run, takes 30-60 s on T4). Every subsequent Interactor reuses the same LLM that's already loaded in memory." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import random\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "\n", "from interactor import Interactor\n", "from evaluate import evaluate, load_pools\n", "\n", "DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'\n", "print('Device:', DEVICE)\n", "\n", "animals_pool, questions_pool = load_pools()\n", "print(f'animals_pool size: {len(animals_pool):>6} (e.g. {animals_pool[:5]})')\n", "print(f'questions_pool size: {len(questions_pool):>6} (e.g. {questions_pool[:3]})')\n", "\n", "# Sanity probe: create one Interactor and ask two questions about an octopus.\n", "probe = Interactor(gold_animal='octopus', animals_pool=animals_pool, questions_pool=questions_pool)\n", "print(\"\\nask('is it a mammal?') ->\", probe.ask('is it a mammal?'))\n", "print(\"ask('does it live in water?') ->\", probe.ask('does it live in water?'))\n", "print('Queries used:', probe.queries_used, '/', probe.budget)\n", "\n", "# The model loads in bfloat16, which a T4 (Turing) cannot accelerate. Convert to\n", "# float16 (T4 has fp16 tensor cores) -> identical answers, several times faster.\n", "import torch\n", "if torch.cuda.is_available() and next(Interactor._model.parameters()).dtype != torch.float16:\n", " Interactor._model = Interactor._model.half()\n", " print('oracle model -> float16 (faster on T4)')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 3: Solution interface\n", "\n", "Your solution is a class with two methods:\n", "\n", "- `__init__(self, animals_pool, questions_pool)` β€” runs once. Load models, precompute tables, etc.\n", "- `solve(self, interactor)` β€” runs once per test row. Use the oracle to identify the hidden animal.\n", "\n", "Inside `solve`, you have:\n", "\n", "```\n", "interactor.ask(question) -> 'yes' or 'no' (question must be in questions_pool)\n", "interactor.guess(animal) -> 'correct' or 'wrong' (animal must be in animals_pool)\n", "interactor.is_done() -> True after a correct guess or budget exhausted\n", "interactor.remaining_budget() -> int\n", "```\n", "\n", "**Scoring per row**: `score = max(0, (1 if you ever guess correctly else 0) - 0.02 * total_queries)`.\n", "\n", "Budget is **15 questions** per row. Information theory: `logβ‚‚(1400) β‰ˆ 10.5 bits`, each yes/no answer is at most 1 bit β€” so ~11 well-chosen questions plus 1 final guess fit the budget, *if* each question splits the remaining candidates in half. Most don't: *\"does it have a backbone?\"* sounds decisive but the model calls a great many creatures vertebrates. A good question splits the *remaining* candidates roughly in half, given everything you have already learned β€” so the right next question depends on the answers so far." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Baseline: random guessing (the floor)\n", "\n", "Ignores `ask()` entirely. Just guesses random animals until the budget runs out. Expected score: ~0 (15 random guesses out of ~1,400 candidates β‰ˆ 1% solve rate). Any reasonable solution needs to beat this by a lot." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "class RandomBaseline:\n", " def __init__(self, animals_pool, questions_pool, seed=0):\n", " self.animals_pool = animals_pool\n", " self.questions_pool = questions_pool\n", " self.rng = random.Random(seed)\n", "\n", " def solve(self, interactor):\n", " guessed = set()\n", " while not interactor.is_done():\n", " cand = self.rng.choice(self.animals_pool)\n", " while cand in guessed:\n", " cand = self.rng.choice(self.animals_pool)\n", " guessed.add(cand)\n", " interactor.guess(cand)\n", "\n", "baseline_results = evaluate(RandomBaseline(animals_pool, questions_pool), 'dev.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reference: a non-adaptive 20-questions sketch\n", "\n", "This reference shows the *shape* of a real solution without giving away the points. In `__init__` it precomputes, with its own copy of the model, the oracle's yes/no answer to a small **fixed** list of broad questions for every animal β€” a bit-vector per animal. In `solve` it asks those same fixed questions, reads off the oracle's bit-vector, and guesses the animals whose precomputed vector is closest.\n", "\n", "It works, but it's deliberately weak: the questions are the **same for every row** (not chosen adaptively to split the *remaining* candidates), and it uses only a handful. Beating it is mostly about (1) precomputing the full `animal Γ— question` table and (2) choosing each next question *greedily* to most evenly split the animals still consistent with the answers so far. That's your job in Step 4.\n", "\n", "> Precomputing even this small table calls the model a few thousand times (~5-15 min on T4). Skip this cell if you just want to get to your own solution β€” it is only a reference." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### πŸ’‘ Speed tip\n", "\n", "Building the animalΓ—question table by calling `interactor.ask()` **one at a time** is slow.\n", "You can make your precompute **much** faster β€” without changing any answers β€” by **batching**\n", "your model calls (many prompts through the model per forward pass). That optimization is up to you." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "# Reference solution (optional, slow to init). Demonstrates precompute + match,\n", "# but uses FIXED, non-adaptive questions -> leaves most of the score on the table.\n", "FIXED_QUESTIONS = [\n", " 'is it a mammal?',\n", " 'is it a bird?',\n", " 'is it a fish?',\n", " 'is it an insect?',\n", " 'does it live in water?',\n", " 'can it fly?',\n", " 'is it a carnivore?',\n", " 'is it bigger than a human?',\n", " 'does it have a backbone?',\n", " 'is it commonly kept as a pet?',\n", " 'does it have legs?',\n", " 'does it lay eggs?',\n", "]\n", "\n", "class FixedQuestionsReference:\n", " def __init__(self, animals_pool, questions_pool, max_animals=None):\n", " self.animals_pool = animals_pool\n", " self.questions_pool = set(questions_pool)\n", " self.fixed = [q for q in FIXED_QUESTIONS if q in self.questions_pool]\n", " from interactor import Interactor\n", " cand = animals_pool if max_animals is None else animals_pool[:max_animals]\n", " self.candidates = cand\n", " print(f' [reference] precomputing {len(cand)} x {len(self.fixed)} answer table...')\n", " self.table = {}\n", " for i, a in enumerate(cand):\n", " sim = Interactor(gold_animal=a, animals_pool=self.animals_pool,\n", " questions_pool=self.questions_pool, budget=10**9)\n", " self.table[a] = tuple(1 if sim.ask(q) == 'yes' else 0 for q in self.fixed)\n", " if (i + 1) % 200 == 0:\n", " print(f' {i+1}/{len(cand)}')\n", " print(' [reference] table ready.')\n", "\n", " def solve(self, interactor):\n", " obs = []\n", " for q in self.fixed:\n", " if interactor.remaining_budget() <= 1:\n", " break\n", " obs.append(1 if interactor.ask(q) == 'yes' else 0)\n", " obs = tuple(obs)\n", " def agree(a):\n", " vec = self.table[a]\n", " return sum(1 for x, y in zip(vec, obs) if x == y)\n", " ranked = sorted(self.candidates, key=agree, reverse=True)\n", " for a in ranked:\n", " if interactor.is_done():\n", " break\n", " interactor.guess(a)\n", "\n", "# Example (commented out by default β€” uncomment to run; slow to init):\n", "# ref = FixedQuestionsReference(animals_pool, questions_pool)\n", "# ref_results = evaluate(ref, 'dev.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 4: Your solution\n", "\n", "Replace the body of `MySolution.solve` (and `__init__` if you precompute anything) with your strategy. Iterate on `dev.csv` until you're happy with the score, then jump to Step 5 to evaluate on test1 + test2.\n", "\n", "**The intended approach:**\n", "1. In `__init__`, precompute once β€” with your own copy of the model β€” the oracle's yes/no answer for every `(animal, question)` pair you care about. This costs no oracle budget.\n", "2. In `solve`, keep a set of candidate animals still consistent with the answers so far. At each step pick the **question whose answer most evenly splits that set** (maximize information gain), ask it, and shrink the set. Guess when one candidate dominates or the budget is nearly gone.\n", "3. Be robust: the oracle occasionally answers in a way your table didn't predict. Don't let one surprising bit eliminate the true animal forever." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "class MySolution:\n", " def __init__(self, animals_pool, questions_pool):\n", " self.animals_pool = animals_pool\n", " self.questions_pool = questions_pool\n", " # TODO: precompute the (animal x question) answer table and anything else.\n", "\n", " def solve(self, interactor):\n", " # TODO: your strategy. Each ask is ~1 bit; log2(1400) ~ 10.5 bits needed.\n", " # Budget is 15. Choose each question to split the remaining candidates.\n", " while not interactor.is_done():\n", " interactor.guess(self.animals_pool[0])\n", "\n", "my_dev = evaluate(MySolution(animals_pool, questions_pool), 'dev.csv')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Step 5: Final scoring\n", "\n", "Once you're happy with your dev score, run this cell. It scores `dev` and `test1` (and `test2` automatically, if that file is present). The **FINAL** line β€” the *n*-weighted mean over the available test split(s) β€” is what you submit a screenshot of.\n", "\n", "> The organizers also score your submitted `MySolution` on a separate **hidden** test set that is not included here. Aim for a strategy that deduces the animal from scratch each row, so it transfers to unseen creatures." ] }, { "cell_type": "code", "metadata": {}, "execution_count": null, "outputs": [], "source": [ "import os\n", "\n", "solution = MySolution(animals_pool, questions_pool)\n", "dev_results = evaluate(solution, 'dev.csv')\n", "test1_results = evaluate(solution, 'test1.csv')\n", "\n", "splits = [('dev', dev_results), ('test1', test1_results)]\n", "# test2 is a held-out set; included automatically only if present in the folder.\n", "if os.path.exists('test2.csv'):\n", " splits.append(('test2', evaluate(solution, 'test2.csv')))\n", "\n", "rows = [{\n", " 'split': name, 'n': r['n'], 'mean_score': r['mean_score'],\n", " 'solved_rate': r['solved_rate'], 'mean_queries': r['mean_queries'],\n", "} for name, r in splits]\n", "\n", "# FINAL = n-weighted mean over every test split available (test1 [+ test2]).\n", "tests = [r for name, r in splits if name.startswith('test')]\n", "n_test = sum(r['n'] for r in tests)\n", "rows.append({\n", " 'split': 'FINAL',\n", " 'n': n_test,\n", " 'mean_score': sum(r['mean_score'] * r['n'] for r in tests) / n_test,\n", " 'solved_rate': sum(r['solved_rate'] * r['n'] for r in tests) / n_test,\n", " 'mean_queries': sum(r['mean_queries'] * r['n'] for r in tests) / n_test,\n", "})\n", "pd.DataFrame(rows)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" }, "accelerator": "GPU", "colab": { "provenance": [] } }, "nbformat": 4, "nbformat_minor": 5 }