{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Page 9 (dev): Best-of-N with a Process Reward Model\n",
    "\n",
    "Dev only. `Qwen2.5-Math-PRM-7B` scores every step of every chain in the temperature sweep, and Best-of-N keeps the chain it scores highest. This notebook generates nothing: it reads the sweep's `chains_T*_L2048.json` files.\n",
    "\n",
    "Built for a Colab A100."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mount Google Drive for Saving Results\n",
    "Run this cell to connect your Google Drive. Everything is saved to a folder named `Page9_PRM_Dev` in your Drive. Outside Colab it goes to a local folder of the same name."
   ]
  },
  {
   "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/Page9_PRM_Dev'\n",
    "    COLAB = True\n",
    "except ImportError:\n",
    "    SAVE_DIR = 'Page9_PRM_Dev'\n",
    "    COLAB = False\n",
    "\n",
    "os.makedirs(SAVE_DIR, exist_ok=True)\n",
    "os.chdir(SAVE_DIR)\n",
    "print(f\"Working directory: {os.getcwd()}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 1: Install Dependencies, Imports and Configurations\n",
    "\n",
    "Every number the run uses is set here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "#@title Installation and Setup\n!pip install -q datasets transformers accelerate math_verify safetensors\n\nimport json\nimport math\nimport re\nimport time\nfrom collections import defaultdict\nfrom functools import cache\nfrom itertools import combinations\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom datasets import load_dataset\nfrom huggingface_hub import snapshot_download\nfrom math_verify import parse, verify\nfrom matplotlib.ticker import PercentFormatter\nfrom safetensors import safe_open\nfrom tqdm.auto import tqdm\nfrom transformers import AutoTokenizer, Qwen2Model\n\nPRM_MODEL = \"Qwen/Qwen2.5-Math-PRM-7B\"\nSTEP_SEP = \"<extra_0>\"   # the token the PRM scores at, one per step\nSYSTEM = \"Please reason step by step, and put your final answer within \\\\boxed{}.\"\n\nTEMPERATURES = [round(0.1 * i, 1) for i in range(12)]   # 0.0 to 1.1\nCAP = 2048                   # the sweep's tokens per chain\nN_PROBLEMS = 100             # problems every temperature has\nN_CHAINS = 16                # chains per problem\nBEST_OF_SIZES = [1, 2, 4, 8, 16]\nN_DRAWS = 100                # random sets of chains averaged per point\nSEED = 42\n\nTOKENS_PER_BATCH = 32_768    # padded tokens per scoring pass; lower it if memory runs out\nDEVICE = \"cuda\""
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 2: Load the Chains and the Problems\n",
    "\n",
    "Put the 12 `chains_T*_L2048.json` files in the Drive folder, or select them when this cell asks. MATH-500 supplies each problem's text and answer, joined on `unique_id`.\n",
    "\n",
    "T 0.0 and 0.1 hold more problems than the other files. All of their chains are scored, and accuracy uses the 100 problems every temperature has."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "names = {t: f\"chains_T{t:.1f}_L{CAP}.json\" for t in TEMPERATURES}\n",
    "\n",
    "missing = [n for n in names.values() if not os.path.exists(n)]\n",
    "if missing and COLAB:\n",
    "    from google.colab import files\n",
    "    print(f\"Select the {len(missing)} missing files.\")\n",
    "    files.upload()\n",
    "    missing = [n for n in names.values() if not os.path.exists(n)]\n",
    "assert not missing, f\"not in {os.getcwd()}: {missing}\"\n",
    "\n",
    "traces = {}\n",
    "for t, name in names.items():\n",
    "    with open(name) as f:\n",
    "        traces[t] = json.load(f)\n",
    "    assert all(len(r[\"chains\"]) == N_CHAINS for r in traces[t]), f\"{name}: not {N_CHAINS} chains each\"\n",
    "\n",
    "dataset = load_dataset(\"HuggingFaceH4/MATH-500\", split=\"test\")\n",
    "question = {row[\"unique_id\"]: row[\"problem\"] for row in dataset}\n",
    "\n",
    "shared = set.intersection(*[{r[\"unique_id\"] for r in traces[t]} for t in TEMPERATURES])\n",
    "assert len(shared) == N_PROBLEMS, f\"{len(shared)} problems are in every file, not {N_PROBLEMS}\"\n",
    "problems = [row for row in dataset if row[\"unique_id\"] in shared]   # dataset order, as the sweep drew them\n",
    "\n",
    "total = sum(len(r[\"chains\"]) for t in TEMPERATURES for r in traces[t])\n",
    "print(f\"{total:,} chains across {len(TEMPERATURES)} temperatures\")\n",
    "print(f\"{len(problems)} problems shared by every temperature\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 3: Answers and Sets of Chains\n",
    "\n",
    "The grader and the random sets are the sweep's own, so every point here sits on the same chains as its vote.\n",
    "\n",
    "- **Two answers are the same** when `math_verify` says they are equal.\n",
    "- **A chain with no boxed answer** has nothing to submit.\n",
    "- **The sets of N chains** are every combination when there are at most `N_DRAWS`, otherwise `N_DRAWS` random ones, drawn from one generator in the sweep's order."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache\n",
    "def grade(pred, gold):\n",
    "    gt = str(gold).strip()\n",
    "    if pred == \"\":\n",
    "        return False\n",
    "    try:\n",
    "        return bool(verify(parse(f\"${gt}$\"), parse(f\"${pred}$\")))\n",
    "    except Exception:\n",
    "        return pred.replace(\" \", \"\").lower() == gt.replace(\" \", \"\").lower()\n",
    "\n",
    "\n",
    "@cache\n",
    "def same_answer(a, b):\n",
    "    if a.replace(\" \", \"\") == b.replace(\" \", \"\"):\n",
    "        return True\n",
    "    try:\n",
    "        return bool(verify(parse(f\"${a}$\"), parse(f\"${b}$\")))\n",
    "    except Exception:\n",
    "        return False\n",
    "\n",
    "\n",
    "def tally(chains, gold):\n",
    "    # Groups the chains' answers into distinct answers. Returns each chain's group\n",
    "    # (None when it has no answer) and whether each group is the right answer.\n",
    "    groups, labels = [], []\n",
    "    for chain in chains:\n",
    "        answer = chain[\"answer\"]\n",
    "        if answer == \"\":\n",
    "            labels.append(None)\n",
    "            continue\n",
    "        for g, rep in enumerate(groups):\n",
    "            if same_answer(rep, answer):\n",
    "                labels.append(g)\n",
    "                break\n",
    "        else:\n",
    "            groups.append(answer)\n",
    "            labels.append(len(groups) - 1)\n",
    "    return labels, [grade(rep, gold) for rep in groups]\n",
    "\n",
    "\n",
    "def chain_sets(n, rng):\n",
    "    # Which n of the 16 chains compete: every combination when there are at most\n",
    "    # N_DRAWS of them, otherwise N_DRAWS random ones.\n",
    "    if math.comb(N_CHAINS, n) <= N_DRAWS:\n",
    "        return [list(c) for c in combinations(range(N_CHAINS), n)]\n",
    "    return [sorted(rng.choice(N_CHAINS, n, replace=False).tolist()) for _ in range(N_DRAWS)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 4: Load the PRM\n",
    "\n",
    "The checkpoint's bundled modeling code returns finite but wrong scores on current `transformers`, about 0.25 for every step, and raises nothing. So the body loads as transformers' own `Qwen2Model` and the checkpoint's score head is attached by hand: same weights, none of the bundled code.\n",
    "\n",
    "A step is one paragraph, cut at every blank line. A step's score is the probability the PRM gives it of being sound.\n",
    "\n",
    "The model card publishes four step scores for one worked example. This cell reproduces them and stops the run if it cannot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = snapshot_download(PRM_MODEL)\n",
    "tok = AutoTokenizer.from_pretrained(path)\n",
    "body = Qwen2Model.from_pretrained(path, torch_dtype=torch.bfloat16).to(DEVICE).eval()\n",
    "assert next(body.parameters()).dtype == torch.bfloat16\n",
    "\n",
    "with open(f\"{path}/model.safetensors.index.json\") as f:\n",
    "    shard = json.load(f)[\"weight_map\"]\n",
    "head_state = {}\n",
    "for name in (\"0.weight\", \"0.bias\", \"2.weight\", \"2.bias\"):\n",
    "    with safe_open(f\"{path}/{shard['score.' + name]}\", framework=\"pt\") as f:\n",
    "        head_state[name] = f.get_tensor(\"score.\" + name).float()\n",
    "width = body.config.hidden_size\n",
    "head = torch.nn.Sequential(torch.nn.Linear(width, width), torch.nn.ReLU(), torch.nn.Linear(width, 2))\n",
    "head.load_state_dict(head_state)\n",
    "head = head.to(DEVICE).float().eval()\n",
    "\n",
    "SEP_ID = tok.encode(STEP_SEP)[0]\n",
    "PAD_ID = tok.pad_token_id\n",
    "assert SEP_ID != PAD_ID\n",
    "\n",
    "\n",
    "def split_steps(text):\n",
    "    steps = [p.strip() for p in re.split(r\"\\n\\s*\\n\", text) if p.strip()]\n",
    "    return steps or [text.strip() or \"(empty)\"]\n",
    "\n",
    "\n",
    "def sequence(problem, steps):\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": SYSTEM},\n",
    "        {\"role\": \"user\", \"content\": problem},\n",
    "        {\"role\": \"assistant\", \"content\": STEP_SEP.join(steps) + STEP_SEP},\n",
    "    ]\n",
    "    text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)\n",
    "    return tok(text, add_special_tokens=False).input_ids\n",
    "\n",
    "\n",
    "@torch.inference_mode()\n",
    "def prm_batch(sequences):\n",
    "    # One list of step scores per sequence.\n",
    "    longest = max(len(s) for s in sequences)\n",
    "    input_ids = torch.full((len(sequences), longest), PAD_ID)\n",
    "    mask = torch.zeros((len(sequences), longest), dtype=torch.long)\n",
    "    for row, seq in enumerate(sequences):\n",
    "        input_ids[row, : len(seq)] = torch.tensor(seq)\n",
    "        mask[row, : len(seq)] = 1\n",
    "    input_ids, mask = input_ids.to(DEVICE), mask.to(DEVICE)\n",
    "    hidden = body(input_ids=input_ids, attention_mask=mask, use_cache=False).last_hidden_state\n",
    "    at_step = input_ids == SEP_ID\n",
    "    probs = torch.softmax(head(hidden[at_step].float()), dim=-1)[:, 1].cpu()\n",
    "    return [p.tolist() for p in probs.split(at_step.sum(dim=1).tolist())]\n",
    "\n",
    "\n",
    "EXAMPLE_QUERY = \"Sue lives in a fun neighborhood.  One weekend, the neighbors decided to play a prank on Sue.  On Friday morning, the neighbors placed 18 pink plastic flamingos out on Sue's front yard.  On Saturday morning, the neighbors took back one third of the flamingos, painted them white, and put these newly painted white flamingos back out on Sue's front yard.  Then, on Sunday morning, they added another 18 pink plastic flamingos to the collection. At noon on Sunday, how many more pink plastic flamingos were out than white plastic flamingos?\"\n",
    "EXAMPLE_STEPS = [\n",
    "    \"To find out how many more pink plastic flamingos were out than white plastic flamingos at noon on Sunday, we can break down the problem into steps. First, on Friday, the neighbors start with 18 pink plastic flamingos.\",\n",
    "    \"On Saturday, they take back one third of the flamingos. Since there were 18 flamingos, (1/3 \\\\times 18 = 6) flamingos are taken back. So, they have (18 - 6 = 12) flamingos left in their possession. Then, they paint these 6 flamingos white and put them back out on Sue's front yard. Now, Sue has the original 12 pink flamingos plus the 6 new white ones. Thus, by the end of Saturday, Sue has (12 + 6 = 18) pink flamingos and 6 white flamingos.\",\n",
    "    \"On Sunday, the neighbors add another 18 pink plastic flamingos to Sue's front yard. By the end of Sunday morning, Sue has (18 + 18 = 36) pink flamingos and still 6 white flamingos.\",\n",
    "    \"To find the difference, subtract the number of white flamingos from the number of pink flamingos: (36 - 6 = 30). Therefore, at noon on Sunday, there were 30 more pink plastic flamingos out than white plastic flamingos. The answer is (\\\\boxed{30}).\",\n",
    "]\n",
    "PUBLISHED = [1.0, 0.1904, 0.9766, 1.0]\n",
    "\n",
    "got = prm_batch([sequence(EXAMPLE_QUERY, EXAMPLE_STEPS)])[0]\n",
    "print(\"model card:\", PUBLISHED)\n",
    "print(\"this load: \", [round(x, 4) for x in got])\n",
    "assert len(got) == len(PUBLISHED) and all(abs(a - b) < 0.1 for a, b in zip(got, PUBLISHED)), \\\n",
    "    \"The PRM did not reproduce the model card's scores, so every score below would be wrong.\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 5: Score Every Chain\n",
    "\n",
    "Every step of every chain gets a score, and each temperature is saved as `scored_T{temperature}_L2048.json`: the sweep's records, with each chain gaining `steps` and `prm`, one score per step. A chain that is an exact copy of another for the same problem (all of T 0.0) is run once and the score copied.\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, delete the `scored_*` files."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def save_json(path, obj):\n",
    "    with open(path + \".tmp\", \"w\") as f:\n",
    "        json.dump(obj, f)\n",
    "    os.replace(path + \".tmp\", path)\n",
    "\n",
    "\n",
    "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",
    "def score_temperature(t):\n",
    "    final = f\"scored_T{t:.1f}_L{CAP}.json\"\n",
    "    if os.path.exists(final):\n",
    "        with open(final) as f:\n",
    "            traces[t] = json.load(f)\n",
    "        print(f\"T {t:.1f}: already scored\")\n",
    "        return\n",
    "\n",
    "    partial = final + \".partial\"\n",
    "    done = {}\n",
    "    if os.path.exists(partial):\n",
    "        with open(partial) as f:\n",
    "            done = json.load(f)\n",
    "\n",
    "    # One job per distinct chain of a problem, named by where it first appears.\n",
    "    first_seen, jobs = {}, []\n",
    "    for rec in traces[t]:\n",
    "        for i, chain in enumerate(rec[\"chains\"]):\n",
    "            chain[\"steps\"] = split_steps(chain[\"text\"])\n",
    "            where = (rec[\"unique_id\"], chain[\"text\"])\n",
    "            if where not in first_seen:\n",
    "                first_seen[where] = f\"{rec['unique_id']}#{i}\"\n",
    "                jobs.append((first_seen[where], rec[\"unique_id\"], chain[\"steps\"]))\n",
    "\n",
    "    todo = [j for j in jobs if j[0] not in done]\n",
    "    print(f\"T {t:.1f}: {len(jobs):,} distinct chains, {len(todo):,} to score\")\n",
    "    sequences = [sequence(question[uid], steps) for _, uid, steps in todo]\n",
    "\n",
    "    started = saved_at = time.time()\n",
    "    for batch in tqdm(list(length_batches([len(s) for s in sequences])), desc=f\"T {t:.1f}\"):\n",
    "        for i, scores in zip(batch, prm_batch([sequences[i] for i in batch])):\n",
    "            key, _, steps = todo[i]\n",
    "            assert len(scores) == len(steps), f\"{key}: {len(scores)} scores for {len(steps)} steps\"\n",
    "            done[key] = scores\n",
    "        if time.time() - saved_at > 60:\n",
    "            save_json(partial, done)\n",
    "            saved_at = time.time()\n",
    "\n",
    "    for rec in traces[t]:\n",
    "        for chain in rec[\"chains\"]:\n",
    "            chain[\"prm\"] = done[first_seen[(rec[\"unique_id\"], chain[\"text\"])]]\n",
    "    save_json(final, traces[t])\n",
    "    if os.path.exists(partial):\n",
    "        os.remove(partial)\n",
    "    print(f\"T {t:.1f}: saved {final} ({time.time() - started:.0f}s)\")\n",
    "\n",
    "\n",
    "for t in TEMPERATURES:\n",
    "    score_temperature(t)\n",
    "\n",
    "steps_scored = sum(len(c[\"prm\"]) for t in TEMPERATURES for r in traces[t] for c in r[\"chains\"])\n",
    "print(f\"\\n{total:,} chains and {steps_scored:,} steps scored\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 6: Best-of-N Accuracy\n",
    "\n",
    "From a set of N chains, keep the one with the highest score; its answer is the final answer. A problem counts when that answer is right, averaged over the sets.\n",
    "\n",
    "A chain's score is its **weakest step**. The last step's score and the product of all steps are computed beside it, from the same scores.\n",
    "\n",
    "- A chain with no boxed answer cannot be kept. A set with no answer in it is wrong.\n",
    "- A tie goes to the first chain in the set.\n",
    "\n",
    "Saved to `prm_accuracy.csv`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "RULES = {\n",
    "    \"weakest step\": min,\n",
    "    \"last step\": lambda s: s[-1],\n",
    "    \"product of steps\": lambda s: sum(math.log(max(x, 1e-12)) for x in s),   # as a sum of logs\n",
    "}\n",
    "\n",
    "rng = np.random.default_rng(SEED)\n",
    "right_at = defaultdict(list)   # (rule, temperature, N) -> one bool per set\n",
    "\n",
    "for t in tqdm(TEMPERATURES, desc=\"Best-of-N\"):\n",
    "    by_id = {r[\"unique_id\"]: r[\"chains\"] for r in traces[t]}\n",
    "    for p in problems:\n",
    "        chains = by_id[p[\"unique_id\"]]\n",
    "        labels, right = tally(chains, p[\"answer\"])\n",
    "        answered = np.array([l is not None for l in labels])\n",
    "        correct = np.array([l is not None and right[l] for l in labels])\n",
    "        scores = {rule: np.array([f(c[\"prm\"]) for c in chains]) for rule, f in RULES.items()}\n",
    "\n",
    "        for n in BEST_OF_SIZES:\n",
    "            for idx in chain_sets(n, rng):\n",
    "                idx = np.array(idx)\n",
    "                candidates = idx[answered[idx]]\n",
    "                for rule, s in scores.items():\n",
    "                    kept = candidates.size > 0 and correct[candidates[s[candidates].argmax()]]\n",
    "                    right_at[rule, t, n].append(bool(kept))\n",
    "\n",
    "accuracy = pd.DataFrame(\n",
    "    [{\"rule\": rule, \"temperature\": t, \"n_chains\": n, \"accuracy\": float(np.mean(v))}\n",
    "     for (rule, t, n), v in right_at.items()]\n",
    ")\n",
    "accuracy.to_csv(\"prm_accuracy.csv\", index=False)\n",
    "\n",
    "table = accuracy[accuracy.rule == \"weakest step\"].pivot(index=\"temperature\", columns=\"n_chains\", values=\"accuracy\")\n",
    "display(table.round(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 7: Accuracy Against the Number of Chains\n",
    "\n",
    "Best-of-N by weakest step, over 1, 2, 4, 8 and 16 chains, one line per temperature. The 0.0 line is greedy decoding: its 16 chains are identical, so it stays flat."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rcParams.update({\n",
    "    \"figure.facecolor\": \"#fcfcfb\", \"axes.facecolor\": \"#fcfcfb\",\n",
    "    \"axes.spines.top\": False, \"axes.spines.right\": False,\n",
    "    \"axes.edgecolor\": \"#c3c2b7\", \"axes.labelcolor\": \"#52514e\",\n",
    "    \"xtick.color\": \"#52514e\", \"ytick.color\": \"#52514e\",\n",
    "    \"axes.grid\": True, \"grid.color\": \"#e1e0d9\", \"grid.linewidth\": 0.8,\n",
    "    \"axes.axisbelow\": True, \"lines.linewidth\": 2, \"font.size\": 11,\n",
    "})\n",
    "\n",
    "by_n = accuracy[accuracy.rule == \"weakest step\"].pivot(index=\"n_chains\", columns=\"temperature\", values=\"accuracy\")\n",
    "best_t = float(by_n.loc[N_CHAINS].idxmax())   # a tie goes to the lower temperature\n",
    "hot = [t for t in TEMPERATURES if t > 0]\n",
    "shades = plt.cm.Blues(np.linspace(0.35, 1, len(hot)))\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(9, 6))\n",
    "ax.plot(by_n.index, by_n[0.0], color=\"#0b0b0b\", linestyle=\"--\", marker=\"o\", markersize=6, label=\"0.0 (greedy)\")\n",
    "for t, color in zip(hot, shades):\n",
    "    ax.plot(by_n.index, by_n[t], color=color, marker=\"o\", markersize=6,\n",
    "            linewidth=3 if t == best_t else 1.5, label=f\"{t:.1f}\" + (\" (best)\" if t == best_t else \"\"))\n",
    "ax.set_xscale(\"log\", base=2)\n",
    "ax.set_xticks(BEST_OF_SIZES, [str(n) for n in BEST_OF_SIZES])\n",
    "ax.minorticks_off()\n",
    "ax.set_xlabel(\"chains to choose from (N)\")\n",
    "ax.set_ylabel(\"accuracy\")\n",
    "ax.yaxis.set_major_formatter(PercentFormatter(1.0))\n",
    "ax.set_title(\"Best-of-N by the PRM's weakest step, one line per temperature\", loc=\"left\")\n",
    "ax.legend(title=\"temperature\", bbox_to_anchor=(1.02, 1), loc=\"upper left\", frameon=False)\n",
    "plt.savefig(\"fig_prm_accuracy_by_n.png\", dpi=150, bbox_inches=\"tight\")\n",
    "plt.show()\n",
    "\n",
    "print(f\"best temperature at N = {N_CHAINS}: {best_t} ({by_n.loc[N_CHAINS, best_t]:.1%})\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Step 8: Best-of-16 Across Temperatures\n",
    "\n",
    "Best-of-16 accuracy at each temperature, once for each way of turning step scores into one score."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "STYLE = {\"weakest step\": (\"#2a78d6\", \"o\"), \"last step\": (\"#eb6834\", \"s\"), \"product of steps\": (\"#1baf7a\", \"^\")}\n\ntop = accuracy[accuracy.n_chains == N_CHAINS].pivot(index=\"temperature\", columns=\"rule\", values=\"accuracy\")[list(RULES)]\n\nfig, ax = plt.subplots(figsize=(9, 5.5))\nfor rule in RULES:\n    color, marker = STYLE[rule]\n    ax.plot(top.index, top[rule], color=color, marker=marker, markersize=7, label=rule)\n\n# Labels at the right end, nudged apart when the lines finish close together.\ngap = 0.045 * (top.values.max() - top.values.min() + 0.02)\nplaced = []\nfor rule in top.iloc[-1].sort_values().index:\n    y = max(top[rule].iloc[-1], placed[-1] + gap) if placed else top[rule].iloc[-1]\n    placed.append(y)\n    ax.annotate(rule, (top.index[-1], y), xytext=(10, 0), textcoords=\"offset points\", va=\"center\", color=\"#52514e\")\n\nax.set_xticks(top.index, [f\"{t:.1f}\" for t in top.index])\nax.set_xlabel(\"temperature\")\nax.set_ylabel(f\"Best-of-{N_CHAINS} accuracy\")\nax.yaxis.set_major_formatter(PercentFormatter(1.0))\nax.set_title(f\"Best-of-{N_CHAINS} by the PRM, three ways to score a chain\", loc=\"left\")\nax.legend(frameon=False, loc=\"upper center\", bbox_to_anchor=(0.5, -0.13), ncol=3)\nax.margins(x=0.02)\nplt.savefig(\"fig_prm_best_of_16.png\", dpi=150, bbox_inches=\"tight\")\nplt.show()\n\ndisplay(top.round(3))"
  },
  {
   "cell_type": "markdown",
   "source": "### Step 9: What Follows the First Low Step\n\nA chain's break is its first step scored below a cut. The share after it is the chain's text that follows that step, by characters. Right answers are drawn beside wrong ones because a low step on a right chain is a false alarm.\n\nThe cut is a choice: 0.75 is the page's colour cut, with 0.5 and 0.9 beside it in the table. The figure and table use the best temperature from step 7. \"Tokens after it\" applies each chain's share to its token count.\n\nSaved to `prm_breaks.csv` (every chain on the shared problems, every temperature, one row per cut) and `prm_break_summary.csv`.",
   "metadata": {}
  },
  {
   "cell_type": "code",
   "source": "CUTS = [0.5, 0.75, 0.9]\nMAIN_CUT = 0.75\n\nrows = []\nfor t in TEMPERATURES:\n    by_id = {r[\"unique_id\"]: r[\"chains\"] for r in traces[t]}\n    for p in problems:\n        chains = by_id[p[\"unique_id\"]]\n        labels, right = tally(chains, p[\"answer\"])\n        for i, (c, l) in enumerate(zip(chains, labels)):\n            sizes = [len(s) for s in c[\"steps\"]]\n            for cut in CUTS:\n                at = next((k for k, x in enumerate(c[\"prm\"]) if x < cut), None)\n                rows.append({\n                    \"temperature\": t, \"unique_id\": p[\"unique_id\"], \"chain\": i, \"cut\": cut,\n                    \"right_answer\": l is not None and right[l], \"tokens\": c[\"tokens\"], \"n_steps\": len(sizes),\n                    \"first_low_step\": at,\n                    \"share_after\": None if at is None else sum(sizes[at + 1 :]) / sum(sizes),\n                })\nbreaks = pd.DataFrame(rows)\nbreaks.to_csv(\"prm_breaks.csv\", index=False)\n\nhere = breaks[breaks.temperature == best_t]\nGROUPS = {True: (\"right answer\", \"#1baf7a\"), False: (\"wrong or no answer\", \"#2a78d6\")}\n\n\ndef summarise(d):\n    low = d[d.first_low_step.notna()]\n    return {\n        \"chains\": len(d),\n        \"with a low step\": len(low) / len(d),\n        \"median share after it\": low.share_after.median(),\n        \"tokens after it\": (d.share_after.fillna(0) * d.tokens).sum() / d.tokens.sum(),\n    }\n\n\nsummary = pd.DataFrame(\n    [{\"cut\": cut, \"chains are\": GROUPS[is_right][0], **summarise(g)}\n     for (cut, is_right), g in here.groupby([\"cut\", \"right_answer\"])]\n)\nsummary.to_csv(\"prm_break_summary.csv\", index=False)\ndisplay(summary.round(3))\n\nmain = here[here.cut == MAIN_CUT]\nbins = np.linspace(0, 1, 11)\nticks = [\"no low\\nstep\"] + [f\"{a:.0f}–{b:.0f}\" for a, b in zip(bins[:-1] * 100, bins[1:] * 100)]\n\nfig, ax = plt.subplots(figsize=(10, 5.5))\nfor offset, (is_right, (label, color)) in zip((-0.2, 0.2), GROUPS.items()):\n    g = main[main.right_answer == is_right]\n    counts = np.histogram(g.share_after.dropna(), bins=bins)[0]\n    heights = np.concatenate([[g.first_low_step.isna().sum()], counts]) / len(g)\n    ax.bar(np.arange(len(ticks)) + offset, heights, width=0.38, color=color, label=f\"{label} ({len(g):,} chains)\")\nax.set_xticks(np.arange(len(ticks)), ticks)\nax.set_xlabel(\"share of the chain written after its first low step (%)\")\nax.set_ylabel(\"share of chains\")\nax.yaxis.set_major_formatter(PercentFormatter(1.0))\nax.grid(axis=\"x\", visible=False)\nax.set_title(f\"How much of a chain follows its first low step (below {MAIN_CUT}, temperature {best_t})\", loc=\"left\")\nax.legend(frameon=False, loc=\"upper center\")\nplt.savefig(\"fig_prm_first_low_step.png\", dpi=150, bbox_inches=\"tight\")\nplt.show()",
   "metadata": {},
   "execution_count": null,
   "outputs": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "A100",
   "machine_shape": "hm"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}