{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Page 8: Best-of-N\n",
    "\n",
    "Qwen2.5-3B-Instruct writes 16 chains on each of 100 MATH-500 problems, a trained verifier scores every chain, and the chain it scores highest is kept.\n",
    "\n",
    "Built for a Colab A100."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mount Google Drive for Saving Results\n",
    "\n",
    "Run this cell to connect your Google Drive. Everything is saved to a folder named `Page8_Best_of_N` in your Drive. Outside Colab it goes to a local folder of the same name.\n",
    "\n",
    "Progress is saved as it goes, so a run that disconnects picks up where it stopped when the cells are run again. For a fresh run, empty the folder first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "try:\n",
    "    from google.colab import drive\n",
    "    drive.mount('/content/drive')\n",
    "    SAVE_DIR = '/content/drive/MyDrive/Page8_Best_of_N'\n",
    "except ImportError:\n",
    "    SAVE_DIR = 'Page8_Best_of_N'\n",
    "\n",
    "os.makedirs(SAVE_DIR, exist_ok=True)\n",
    "print(f\"Saving to {SAVE_DIR}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Install Dependencies, Imports and Configurations\n",
    "\n",
    "First, we install the required libraries, import the packages, and set the run's parameters: the model that writes the chains, the trained verifier that scores them, and the sampling settings."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "#@title Installation and Setup\n",
    "!pip install -q datasets transformers accelerate math-verify\n",
    "\n",
    "import copy\n",
    "import gc\n",
    "import json\n",
    "import math\n",
    "import os\n",
    "import random\n",
    "import time\n",
    "from collections import Counter\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import torch\n",
    "from datasets import load_dataset\n",
    "from huggingface_hub import snapshot_download\n",
    "from math_verify import parse, verify\n",
    "from tqdm.auto import tqdm\n",
    "from transformers import AutoModelForCausalLM, AutoTokenizer, Qwen2Config, Qwen2Model\n",
    "\n",
    "WRITER = \"Qwen/Qwen2.5-3B-Instruct\"                     # writes the 16 chains\n",
    "VERIFIER = \"Skywork/Skywork-o1-Open-PRM-Qwen-2.5-1.5B\"  # the trained verifier\n",
    "\n",
    "N_CHAINS = 16\n",
    "TEMPERATURE = 0.9\n",
    "TOP_P = 0.95\n",
    "MAX_NEW_TOKENS = 2048\n",
    "\n",
    "BATCH_SIZE = 128            # sequences per generate call; lower it if memory runs out\n",
    "TOKENS_PER_BATCH = 32_768   # padded tokens per scoring pass\n",
    "N_PROBLEMS = 100            # drawn from the 500, in proportion to their levels\n",
    "\n",
    "SEED = 42\n",
    "DEVICE = \"cuda\"\n",
    "random.seed(SEED)\n",
    "torch.manual_seed(SEED)\n",
    "\n",
    "\n",
    "def short(name):\n",
    "    return name.split(\"/\")[-1]\n",
    "\n",
    "\n",
    "def free_gpu():\n",
    "    gc.collect()\n",
    "    torch.cuda.empty_cache()\n",
    "\n",
    "\n",
    "def saved(name):\n",
    "    return os.path.join(SAVE_DIR, name)\n",
    "\n",
    "\n",
    "def save_json(path, obj):\n",
    "    with open(path + \".tmp\", \"w\") as f:\n",
    "        json.dump(obj, f)\n",
    "    os.replace(path + \".tmp\", path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2: Load the MATH-500 Dataset\n",
    "\n",
    "We pull `HuggingFaceH4/MATH-500` and draw 100 of its problems at random, the same share from each level as in the full 500. The seed and the draw are the frequency-voting notebook's, so these are the same 100 problems."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(\"Loading MATH-500 dataset...\")\n",
    "dataset = load_dataset(\"HuggingFaceH4/MATH-500\", split=\"test\")\n",
    "\n",
    "# The same share of each level as the 500, drawn at random within each level, kept in\n",
    "# dataset order.\n",
    "by_level = {}\n",
    "for k, row in enumerate(dataset):\n",
    "    by_level.setdefault(row[\"level\"], []).append(k)\n",
    "draw = random.Random(SEED)\n",
    "quota = {lv: round(len(ks) * N_PROBLEMS / len(dataset)) for lv, ks in by_level.items()}\n",
    "quota[max(quota, key=lambda lv: len(by_level[lv]))] += N_PROBLEMS - sum(quota.values())\n",
    "picked = sorted(k for lv, ks in by_level.items() for k in draw.sample(ks, quota[lv]))\n",
    "problems = [dataset[k] for k in picked]\n",
    "\n",
    "full = Counter(row[\"level\"] for row in dataset)\n",
    "levels = Counter(p[\"level\"] for p in problems)\n",
    "print(f\"{len(problems)} of {len(dataset)} problems, by level: \"\n",
    "      + \", \".join(f\"{lv}: {levels[lv]} of {full[lv]}\" for lv in sorted(levels)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Step 3: Define the Prompt, Answer Extraction and Grading\n\nEvery model solves with the same chain-of-thought prompt and writes its final answer inside `\\boxed{}`. The answer is the contents of the last box. Two answers are the same answer when they match as text or when `math_verify` finds them mathematically equal (`\\frac{1}{2}` and `0.5`). The same test grades a chain against the reference answer and groups the 16 chains' answers for the vote."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "SYSTEM_PROMPT = \"You are a helpful assistant. Solve the math problem step-by-step, explaining your reasoning. Put your final answer inside \\\\boxed{answer}.\"\n",
    "\n",
    "\n",
    "def build_prompt(tok, problem):\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
    "        {\"role\": \"user\", \"content\": problem},\n",
    "    ]\n",
    "    return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)\n",
    "\n",
    "\n",
    "def extract_answer(text):\n",
    "    \"\"\"The contents of the last \\\\boxed{...}, with nested braces matched. None if there is no box.\"\"\"\n",
    "    start = text.rfind(\"\\\\boxed{\")\n",
    "    if start == -1:\n",
    "        return None\n",
    "    i = start + len(\"\\\\boxed{\")\n",
    "    depth = 1\n",
    "    for j in range(i, len(text)):\n",
    "        if text[j] == \"{\":\n",
    "            depth += 1\n",
    "        elif text[j] == \"}\":\n",
    "            depth -= 1\n",
    "            if depth == 0:\n",
    "                return text[i:j].strip() or None\n",
    "    return None\n",
    "\n",
    "\n",
    "_parsed, _same = {}, {}\n",
    "\n",
    "\n",
    "def parsed(answer):\n",
    "    if answer not in _parsed:\n",
    "        _parsed[answer] = parse(f\"${answer}$\")\n",
    "    return _parsed[answer]\n",
    "\n",
    "\n",
    "def same_answer(a, b):\n",
    "    if a is None or b is None:\n",
    "        return False\n",
    "    if a.replace(\" \", \"\") == b.replace(\" \", \"\"):\n",
    "        return True\n",
    "    if (a, b) not in _same:\n",
    "        try:\n",
    "            _same[(a, b)] = bool(verify(parsed(a), parsed(b)))\n",
    "        except Exception:\n",
    "            _same[(a, b)] = False\n",
    "    return _same[(a, b)]\n",
    "\n",
    "\n",
    "def grade(texts, gold):\n",
    "    \"\"\"One row per chain: its text, its answer, and whether the answer is right.\"\"\"\n",
    "    rows = []\n",
    "    for text in texts:\n",
    "        answer = extract_answer(text)\n",
    "        rows.append({\"text\": text, \"answer\": answer, \"correct\": same_answer(gold, answer)})\n",
    "    return rows\n",
    "\n",
    "\n",
    "print(same_answer(\"\\\\frac{1}{2}\", \"0.5\"), same_answer(\"\\\\dfrac{14}{3}\", \"\\\\frac{14}{3}\"), same_answer(\"3\", \"4\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Step 4: Generate Chains\n\nOne helper writes every chain on this page. Greedy (T = 0) when `temperature` is 0, otherwise sampled at `temperature` with `top_p`. The repetition penalty and top-k that ship in Qwen's generation config are switched off, so the settings above are the only ones in play."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def load_generator(name):\n",
    "    tok = AutoTokenizer.from_pretrained(name)\n",
    "    tok.padding_side = \"left\"\n",
    "    model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.bfloat16, device_map=DEVICE).eval()\n",
    "    return model, tok\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def generate_chains(model, tok, problems, n=1, temperature=0.0, checkpoint=None):\n",
    "    \"\"\"n chains per problem, returned as one list of n texts per problem.\"\"\"\n",
    "    config = copy.deepcopy(model.generation_config)\n",
    "    config.update(\n",
    "        max_new_tokens=MAX_NEW_TOKENS,\n",
    "        num_return_sequences=n,\n",
    "        do_sample=temperature > 0,\n",
    "        temperature=temperature if temperature > 0 else None,\n",
    "        top_p=TOP_P if temperature > 0 else None,\n",
    "        top_k=None,\n",
    "        repetition_penalty=1.0,\n",
    "        pad_token_id=tok.pad_token_id,\n",
    "    )\n",
    "    per_call = max(1, BATCH_SIZE // n)\n",
    "    chains = []\n",
    "    if checkpoint and os.path.exists(checkpoint):\n",
    "        with open(checkpoint) as f:\n",
    "            chains = json.load(f)\n",
    "        print(f\"    Resuming at {len(chains)}/{len(problems)} problems.\")\n",
    "    for i in range(len(chains), len(problems), per_call):\n",
    "        batch = problems[i : i + per_call]\n",
    "        prompts = [build_prompt(tok, p[\"problem\"]) for p in batch]\n",
    "        inputs = tok(prompts, return_tensors=\"pt\", padding=True, add_special_tokens=False).to(DEVICE)\n",
    "        outputs = model.generate(**inputs, generation_config=config)\n",
    "        texts = tok.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)\n",
    "        chains += [texts[k * n : (k + 1) * n] for k in range(len(batch))]\n",
    "        if checkpoint:\n",
    "            save_json(checkpoint, chains)\n",
    "        print(f\"    Progress: {len(chains)}/{len(problems)} problems.\")\n",
    "    return chains"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 5: One Greedy Chain from the 3B\n",
    "\n",
    "Qwen2.5-3B-Instruct writes one greedy chain per problem. This is the one-chain baseline every rule below is compared with."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f\"Solving with {WRITER}, one greedy chain per problem\")\n",
    "start = time.time()\n",
    "model, tok = load_generator(WRITER)\n",
    "texts = generate_chains(model, tok, problems, checkpoint=saved(f\"page8_greedy_texts_n{len(problems)}.json\"))\n",
    "greedy = [grade(t, p[\"answer\"])[0] for t, p in zip(texts, problems)]\n",
    "del model, tok\n",
    "free_gpu()\n",
    "ONE_CHAIN = np.array([row[\"correct\"] for row in greedy])\n",
    "print(f\"  solved {ONE_CHAIN.mean():.1%} in {time.time() - start:.0f}s\")\n",
    "\n",
    "save_json(saved(f\"page8_greedy_n{len(problems)}.json\"), greedy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 6: The 3B Writes 16 Chains per Problem\n",
    "\n",
    "Qwen2.5-3B-Instruct solves the 100 problems again, this time writing 16 chains per problem at T = 0.9 with the same prompt and the same 2,048-token cap. These 1,600 chains are the pile every rule below chooses from."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "print(f\"Writing {N_CHAINS} chains per problem with {WRITER} at T = {TEMPERATURE}\")\n",
    "start = time.time()\n",
    "torch.manual_seed(SEED)\n",
    "model, tok = load_generator(WRITER)\n",
    "texts = generate_chains(model, tok, problems, n=N_CHAINS, temperature=TEMPERATURE,\n",
    "                        checkpoint=saved(f\"page8_chain_texts_T{TEMPERATURE}_n{len(problems)}.json\"))\n",
    "chains = [grade(t, p[\"answer\"]) for t, p in zip(texts, problems)]\n",
    "del model, tok\n",
    "free_gpu()\n",
    "print(f\"Done in {time.time() - start:.0f}s\")\n",
    "\n",
    "save_json(saved(f\"page8_chains_T{TEMPERATURE}_n{len(problems)}.json\"), chains)\n",
    "\n",
    "C = np.array([[c[\"correct\"] for c in row] for row in chains])   # (problems, chains): is each chain right?\n",
    "print(f\"one sampled chain is right {C.mean():.1%} of the time\")\n",
    "print(f\"a right answer is among the 16 chains on {C.any(axis=1).mean():.1%} of problems\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Step 7: Majority Vote\n\nFor each problem, the 16 final answers are grouped by equivalence and the most common group is kept. A chain with no boxed answer does not vote, and a tie for most common counts as wrong."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "def group_answers(answers):\n    \"\"\"The distinct answers, and for each chain the index of its group (None if it gave no answer).\"\"\"\n    reps, labels = [], []\n    for answer in answers:\n        if answer is None:\n            labels.append(None)\n            continue\n        for k, rep in enumerate(reps):\n            if same_answer(rep, answer):\n                labels.append(k)\n                break\n        else:\n            reps.append(answer)\n            labels.append(len(reps) - 1)\n    return reps, labels\n\n\ndef vote_winner(labels):\n    \"\"\"The group with the most chains, or None when there is a tie or no answer at all.\"\"\"\n    ranked = Counter(l for l in labels if l is not None).most_common(2)\n    if not ranked or (len(ranked) == 2 and ranked[0][1] == ranked[1][1]):\n        return None\n    return ranked[0][0]\n\n\ngroups = []\nfor row, p in zip(chains, problems):\n    reps, labels = group_answers([c[\"answer\"] for c in row])\n    groups.append({\"reps\": reps, \"labels\": labels,\n                   \"rep_correct\": [same_answer(p[\"answer\"], r) for r in reps]})\n\nwinners = [vote_winner(g[\"labels\"]) for g in groups]\nVOTE = np.array([w is not None and g[\"rep_correct\"][w] for w, g in zip(winners, groups)])\nCEILING = C.any(axis=1)\n\nprint(f\"majority vote solves {VOTE.mean():.1%}\")\nprint(f\"ties: {sum(w is None for w in winners)} problems\")\nprint(f\"ceiling (a right answer is among the chains): {CEILING.mean():.1%}\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 8: The Verifier Scores Every Chain\n",
    "\n",
    "The verifier never sees the reference answer and scores one chain at a time. It reads the question and the chain in Skywork's own format (each line of the chain closed by a newline token) and scores the chain's last token. Skywork's checkpoint is a stock Qwen2 body plus a one-output value head, so the body loads into transformers' own `Qwen2Model` and the head is applied here; none of the checkpoint's custom code runs."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "def length_batches(lengths):\n",
    "    \"\"\"Indices grouped longest first, each group under TOKENS_PER_BATCH padded tokens.\"\"\"\n",
    "    order = sorted(range(len(lengths)), key=lambda i: -lengths[i])\n",
    "    batch = []\n",
    "    for i in order:\n",
    "        if batch and lengths[batch[0]] * (len(batch) + 1) > TOKENS_PER_BATCH:\n",
    "            yield batch\n",
    "            batch = []\n",
    "        batch.append(i)\n",
    "    if batch:\n",
    "        yield batch\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def score_last_token(body, pad_id, sequences, read):\n",
    "    \"\"\"Runs each token sequence through `body` and applies `read` to the hidden state at its last token.\"\"\"\n",
    "    scores = np.empty(len(sequences), dtype=np.float32)\n",
    "    batches = list(length_batches([len(s) for s in sequences]))\n",
    "    for batch in tqdm(batches, desc=\"  scoring\"):\n",
    "        width = len(sequences[batch[0]])\n",
    "        input_ids = torch.full((len(batch), width), pad_id)\n",
    "        mask = torch.zeros((len(batch), width), dtype=torch.long)\n",
    "        for row, i in enumerate(batch):\n",
    "            seq = sequences[i]\n",
    "            input_ids[row, width - len(seq):] = torch.tensor(seq)\n",
    "            mask[row, width - len(seq):] = 1\n",
    "        positions = (mask.cumsum(-1) - 1).clamp(min=0)\n",
    "        hidden = body(input_ids=input_ids.to(DEVICE), attention_mask=mask.to(DEVICE),\n",
    "                      position_ids=positions.to(DEVICE), use_cache=False).last_hidden_state[:, -1]\n",
    "        scores[batch] = read(hidden).float().cpu().numpy()\n",
    "    return scores\n",
    "\n",
    "\n",
    "def load_reward_model(name):\n",
    "    \"\"\"The Qwen2 body in transformers' own implementation, plus the checkpoint's value head.\"\"\"\n",
    "    path = snapshot_download(name)\n",
    "    state = torch.load(f\"{path}/pytorch_model.bin\", map_location=\"cpu\", weights_only=True, mmap=True)\n",
    "    config = Qwen2Config.from_pretrained(path)\n",
    "    config._attn_implementation = \"sdpa\"\n",
    "    torch.set_default_dtype(torch.bfloat16)\n",
    "    with torch.device(DEVICE):\n",
    "        body = Qwen2Model(config)\n",
    "    torch.set_default_dtype(torch.float32)\n",
    "    body.load_state_dict({k[len(\"model.\"):]: v for k, v in state.items() if k.startswith(\"model.\")})\n",
    "    w = state[\"v_head.summary.weight\"].to(DEVICE, torch.float32).flatten()\n",
    "    b = state[\"v_head.summary.bias\"].to(DEVICE, torch.float32)\n",
    "    tok = AutoTokenizer.from_pretrained(path)\n",
    "    return body.eval(), w, b, tok\n",
    "\n",
    "\n",
    "def reward_sequence(tok, question, solution):\n",
    "    \"\"\"Skywork's format: the question on its own line, then every line of the chain closed by a newline token.\"\"\"\n",
    "    newline = tok.encode(\"\\n\", add_special_tokens=False)[-1]\n",
    "    ids = tok.encode(tok.bos_token + question + \"\\n\", add_special_tokens=False)\n",
    "    for step in solution.split(\"\\n\"):\n",
    "        ids += (tok.encode(step, add_special_tokens=False) if step else []) + [newline]\n",
    "    return ids\n",
    "\n",
    "\n",
    "pairs = [(p[\"problem\"], c[\"text\"]) for p, row in zip(problems, chains) for c in row]\n",
    "SCORES = {}\n",
    "\n",
    "\n",
    "def scores_file(name):\n",
    "    return saved(f\"page8_scores_{short(name)}_T{TEMPERATURE}_n{len(problems)}.npy\")\n",
    "\n",
    "\n",
    "def load_scores(name):\n",
    "    \"\"\"A judge already scored by this run, loaded from Drive. False if it still has to run.\"\"\"\n",
    "    if not os.path.exists(scores_file(name)):\n",
    "        return False\n",
    "    SCORES[short(name)] = np.load(scores_file(name))\n",
    "    print(f\"\\n{name}: already scored, loaded\")\n",
    "    return True\n",
    "\n",
    "\n",
    "def save_scores(name):\n",
    "    tmp = scores_file(name) + \".tmp.npy\"\n",
    "    np.save(tmp, SCORES[short(name)])\n",
    "    os.replace(tmp, scores_file(name))\n",
    "\n",
    "if not load_scores(VERIFIER):\n",
    "    print(f\"\\nScoring with {VERIFIER}\")\n",
    "    start = time.time()\n",
    "    body, w, b, tok = load_reward_model(VERIFIER)\n",
    "    sequences = [reward_sequence(tok, q, s) for q, s in pairs]\n",
    "    read = lambda hidden: torch.sigmoid(hidden.float() @ w + b)\n",
    "    SCORES[short(VERIFIER)] = score_last_token(body, tok.pad_token_id, sequences, read).reshape(C.shape)\n",
    "    save_scores(VERIFIER)\n",
    "    del body, w, b, tok, read\n",
    "    free_gpu()\n",
    "    print(f\"  done in {time.time() - start:.0f}s\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 9: Best-of-N\n",
    "\n",
    "The verifier's top-scored chain of the 16 is kept, and the problem counts as solved when that chain is right. A chain with no boxed answer cannot be kept."
   ]
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "V = SCORES[short(VERIFIER)]\n",
    "ANSWERED = np.array([[c[\"answer\"] is not None for c in row] for row in chains])\n",
    "KEPT = C[np.arange(len(C)), np.where(ANSWERED, V, -np.inf).argmax(axis=1)]\n",
    "\n",
    "print(f\"3B, one greedy chain: {100 * ONE_CHAIN.mean():.1f}%\")\n",
    "print(f\"majority vote over 16: {100 * VOTE.mean():.1f}%\")\n",
    "print(f\"Best-of-16: {100 * KEPT.mean():.1f}%\")\n",
    "print(f\"ceiling: {100 * CEILING.mean():.1f}%\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 10: Every Problem as One Dot\n",
    "\n",
    "Each problem stacks over how many of its 16 chains are right. The marker says what Best-of-N got."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "GREEN, BLUE, ORANGE, GRAY = \"#1baf7a\", \"#2a78d6\", \"#eb6834\", \"#8a8578\"\n",
    "INK = \"#3d3a33\"\n",
    "plt.rcParams.update({\"axes.spines.top\": False, \"axes.spines.right\": False})\n",
    "\n",
    "OUTCOMES = [\n",
    "    (\"kept chain right\", GREEN, \"o\"),\n",
    "    (\"kept chain wrong, a right one was written\", BLUE, \"D\"),\n",
    "    (\"no right chain written\", GRAY, \"o\"),\n",
    "]\n",
    "outcome = np.where(KEPT, 0, np.where(CEILING, 1, 2))\n",
    "right = C.sum(axis=1)\n",
    "\n",
    "height = np.zeros(len(C), dtype=int)\n",
    "for k in range(N_CHAINS + 1):\n",
    "    here = np.flatnonzero(right == k)\n",
    "    height[here[np.argsort(outcome[here], kind=\"stable\")]] = np.arange(len(here))\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(10, 4.5))\n",
    "for which, (label, color, marker) in enumerate(OUTCOMES):\n",
    "    mask = outcome == which\n",
    "    ax.scatter(right[mask], height[mask], s=70, c=color, marker=marker, edgecolors=\"white\", linewidths=1, label=label)\n",
    "ax.set_xticks(range(N_CHAINS + 1))\n",
    "ax.set_yticks([])\n",
    "ax.spines[\"left\"].set_visible(False)\n",
    "ax.set_xlabel(f\"chains right, of {N_CHAINS}\")\n",
    "ax.legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.18), ncols=3, frameon=False)\n",
    "ax.set_title(f\"{len(C)} problems, one dot each\", loc=\"left\")\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 11: One Chain, Majority Vote, Best-of-N\n",
    "\n",
    "The three methods on the same chains. The dashed line is the share of problems where at least one chain was right, the most any way of choosing could reach."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "METHODS = [\n",
    "    (\"one chain of thought\", ONE_CHAIN, GRAY),\n",
    "    (f\"majority vote over {N_CHAINS}\", VOTE, ORANGE),\n",
    "    (f\"Best-of-{N_CHAINS}\", KEPT, GREEN),\n",
    "]\n",
    "values = [100 * solved.mean() for _, solved, _ in METHODS]\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(10, 3.2))\n",
    "ax.barh(range(len(METHODS)), values, height=0.5, color=[color for _, _, color in METHODS])\n",
    "for i, v in enumerate(values):\n",
    "    ax.text(102, i, f\"{v:.1f}%\", va=\"center\", color=INK)\n",
    "ax.axvline(100 * CEILING.mean(), color=INK, linestyle=\"--\", linewidth=1.2,\n",
    "           label=f\"at least one chain was correct ({100 * CEILING.mean():.1f}%)\")\n",
    "ax.set_yticks(range(len(METHODS)), [name for name, _, _ in METHODS])\n",
    "ax.invert_yaxis()\n",
    "ax.set_xlim(0, 100)\n",
    "ax.set_xlabel(f\"share of {len(C)} problems solved (%)\")\n",
    "ax.grid(axis=\"x\", color=\"#e6e3dc\", linewidth=1)\n",
    "ax.set_axisbelow(True)\n",
    "ax.legend(loc=\"upper center\", bbox_to_anchor=(0.5, -0.3), frameon=False)\n",
    "plt.tight_layout()\n",
    "plt.show()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 12: Export for the Page\n",
    "\n",
    "`page-08-pile.json` is written to the Drive folder: every problem's 16 chains in the verifier's order, the three methods, the verifier's misses, and one miss drawn at random from those the vote also got wrong. Copy it to `web/data/`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mcnemar(a, b):\n",
    "    \"\"\"Exact two-sided test over the problems where a and b disagree.\"\"\"\n",
    "    x, y = int((a & ~b).sum()), int((b & ~a).sum())\n",
    "    n = x + y\n",
    "    if n == 0:\n",
    "        return x, y, 1.0\n",
    "    return x, y, min(1.0, 2 * sum(math.comb(n, i) for i in range(max(x, y), n + 1)) / 2 ** n)\n",
    "\n",
    "\n",
    "def verifier_order(k):\n",
    "    \"\"\"Problem k's chains, highest score first; a tie goes to the earlier chain, and a chain with no answer comes last.\"\"\"\n",
    "    return sorted(range(N_CHAINS), key=lambda i: (not ANSWERED[k, i], -float(V[k, i]), i))\n",
    "\n",
    "\n",
    "pile_rows = []\n",
    "for k, (p, w) in enumerate(zip(problems, winners)):\n",
    "    pile_rows.append({\n",
    "        \"id\": p[\"unique_id\"],\n",
    "        \"level\": int(p[\"level\"]),\n",
    "        \"n_correct\": int(C[k].sum()),\n",
    "        \"vote\": \"wrong\" if not groups[k][\"reps\"] else \"tie\" if w is None else \"right\" if VOTE[k] else \"wrong\",\n",
    "        \"greedy\": bool(ONE_CHAIN[k]),\n",
    "        \"chains\": [{\"i\": i, \"c\": bool(C[k, i]), \"s\": round(float(V[k, i]), 4) if ANSWERED[k, i] else None} for i in verifier_order(k)],\n",
    "    })\n",
    "pile_rows.sort(key=lambda r: (-r[\"n_correct\"], r[\"id\"]))\n",
    "\n",
    "misses = [k for k in range(len(problems)) if CEILING[k] and not KEPT[k]]\n",
    "pool = [k for k in misses if not VOTE[k]]\n",
    "assert pool, \"no verifier miss the vote also got wrong\"\n",
    "k = int(np.random.default_rng(SEED).choice(pool))\n",
    "ranked = [i for i in verifier_order(k) if ANSWERED[k, i]]\n",
    "top_right = next(i for i in ranked if C[k, i])\n",
    "shown = ranked[:4] if top_right in ranked[:3] else ranked[:3] + [top_right]  # the top three and the best right one\n",
    "\n",
    "best_only, vote_only, p_best_vote = mcnemar(KEPT, VOTE)\n",
    "best_vs_one, one_vs_best, p_best_one = mcnemar(KEPT, ONE_CHAIN)\n",
    "vote_vs_one, one_vs_vote, p_vote_one = mcnemar(VOTE, ONE_CHAIN)\n",
    "\n",
    "pile = {\n",
    "    \"source\": {\"stand_in\": False, \"notebook\": \"8_Best_of_N.ipynb\"},\n",
    "    \"writer\": WRITER,\n",
    "    \"verifier\": VERIFIER,\n",
    "    \"benchmark\": \"MATH-500\",\n",
    "    \"levels\": sorted({r[\"level\"] for r in pile_rows}),\n",
    "    \"temperature\": TEMPERATURE,\n",
    "    \"n_chains\": N_CHAINS,\n",
    "    \"bars\": {\n",
    "        \"one_chain\": float(ONE_CHAIN.mean()),\n",
    "        \"chain_average\": float(C.mean()),\n",
    "        \"vote\": float(VOTE.mean()),\n",
    "        \"best_of_n\": float(KEPT.mean()),\n",
    "        \"ceiling\": float(CEILING.mean()),\n",
    "        \"best_vs_vote\": {\"best_only\": best_only, \"vote_only\": vote_only, \"p\": p_best_vote},\n",
    "        \"best_vs_one\": {\"best_only\": best_vs_one, \"one_only\": one_vs_best, \"p\": p_best_one},\n",
    "        \"vote_vs_one\": {\"vote_only\": vote_vs_one, \"one_only\": one_vs_vote, \"p\": p_vote_one},\n",
    "    },\n",
    "    \"misses\": {\"n\": len(misses), \"of\": int(CEILING.sum()), \"ids\": [problems[m][\"unique_id\"] for m in misses]},\n",
    "    \"specimen\": {\n",
    "        \"id\": problems[k][\"unique_id\"],\n",
    "        \"question\": problems[k][\"problem\"],\n",
    "        \"answer\": problems[k][\"answer\"],\n",
    "        \"vote\": \"tie\" if winners[k] is None else \"wrong\",\n",
    "        \"vote_answer\": None if winners[k] is None else groups[k][\"reps\"][winners[k]],\n",
    "        \"n_correct\": int(C[k].sum()),\n",
    "        \"right_rank\": ranked.index(top_right) + 1,\n",
    "        \"cards\": [{\"i\": i, \"c\": bool(C[k, i]), \"s\": round(float(V[k, i]), 4), \"r\": round(100 * float(V[k, i])),\n",
    "                   \"a\": chains[k][i][\"answer\"], \"trace\": chains[k][i][\"text\"]} for i in shown],\n",
    "    },\n",
    "    \"rows\": pile_rows,\n",
    "}\n",
    "with open(saved(\"page-08-pile.json\"), \"w\") as f:\n",
    "    json.dump(pile, f, ensure_ascii=False, separators=(\",\", \":\"))\n",
    "print(f\"page-08-pile.json: {os.path.getsize(saved('page-08-pile.json')) / 1e3:.0f} kB\")\n",
    "print(f\"one chain {ONE_CHAIN.mean():.1%}, vote {VOTE.mean():.1%}, Best-of-16 {KEPT.mean():.1%}, ceiling {CEILING.mean():.1%}\")\n",
    "print(f\"verifier misses: {len(misses)} of {int(CEILING.sum())}; Best-of-16 alone {best_only}, vote alone {vote_only}, p = {p_best_vote:.3f}\")\n"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "A100",
   "machine_shape": "hm",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
