{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "exotic-voluntary",
   "metadata": {},
   "source": [
    "## Running the metrics for proof generation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fancy-agreement",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append(\"..\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "burning-patient",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Populating the interactive namespace from numpy and matplotlib\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import transformers\n",
    "import torch\n",
    "import pickle\n",
    "from tqdm.notebook import tqdm\n",
    "import pandas as pd\n",
    "import glob\n",
    "from pprint import pprint\n",
    "import transformers\n",
    "transformers.logging.set_verbosity_error()\n",
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '6'\n",
    "import datasets\n",
    "datasets.logging.set_verbosity(50)\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "%pylab inline"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "scenic-porter",
   "metadata": {},
   "source": [
    "### Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "thermal-society",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds_base = json.load(open(\n",
    "    '../data/latest/proofwiki.json'\n",
    "))\n",
    "ds_generations = json.load(open(\n",
    "    '../data/latest/proofwiki__refs_ground_truth.json'\n",
    "))\n",
    "redirects = json.load(open(\n",
    "    '../data/proofwiki_redirects.json'\n",
    "))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "educated-import",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_type = 'facebook/bart-large'\n",
    "tokenizer = transformers.AutoTokenizer.from_pretrained(model_type)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "respiratory-vault",
   "metadata": {},
   "source": [
    "### Utilities"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "missing-literature",
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_gens(name2gen_files):\n",
    "    name2gens = {}\n",
    "    for name in name2gen_files:\n",
    "        try:\n",
    "            name2gens[name] = json.load(open(name2gen_files[name]))\n",
    "        except:\n",
    "            print(\"skipping %s\" % name)\n",
    "    return name2gens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "industrial-target",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from npgen.evaluation_proofgen import full_generation_metrics\n",
    "def evaluate(name2gens):    \n",
    "    name2metrics_object = {}\n",
    "    df_data = []\n",
    "    for name, gens in tqdm(name2gens.items(), total=len(name2gens)):\n",
    "        metrics, metrics_object = full_generation_metrics(\n",
    "            gens['full_generations'], \n",
    "            ds_base, \n",
    "            ds_generations,\n",
    "            redirects,\n",
    "            tokenizer, \n",
    "            return_metrics_object=True\n",
    "        )\n",
    "        name, run = name.split('___')\n",
    "        for span in name.split('__'):\n",
    "            if '=' in span:\n",
    "                key, value = span.split('=')\n",
    "                metrics[key] = value\n",
    "        metrics['name'] = name\n",
    "        metrics['run'] = run\n",
    "        df_data.append(metrics)\n",
    "        name2metrics_object[name] = metrics_object\n",
    "\n",
    "    df = pd.DataFrame(df_data)\n",
    "    return df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "innovative-lender",
   "metadata": {},
   "outputs": [],
   "source": [
    "from copy import deepcopy\n",
    "\n",
    "default_cols = ['ppl', 'gleu', 'ref_f1', 'kf1', 'f1', 'total_sampled_tokens', 'corpus_ref_halluc']\n",
    "def display(df, cols=default_cols):\n",
    "    df = deepcopy(df)\n",
    "    df['total_sampled_tokens'] /= 100000    \n",
    "    if cols is None:\n",
    "        min_cols = ['corpus_ref_halluc', 'ppl']\n",
    "        df_show = df[['run', 'ppl', 'name', 'f1', 'gleu', 'ref_precision', 'ref_recall', 'ref_f1', 'corpus_ref_halluc']]    \n",
    "    else:\n",
    "        min_cols = [c for c in ['corpus_ref_halluc', 'ppl'] if c in cols]\n",
    "        show_cols = cols\n",
    "        df_show = df[['run', 'name'] + show_cols]   \n",
    "\n",
    "    df_show = df_show.groupby('name').mean().round(4)\n",
    "    df_show = df_show.style.highlight_min(\n",
    "        color = 'lightgreen', axis=0, \n",
    "        subset=min_cols,\n",
    "    )\n",
    "    df_show = df_show.highlight_max(\n",
    "        color = 'lightgreen', axis=0, \n",
    "        subset=list(set(df_show.columns).difference(set(min_cols)))\n",
    "    )\n",
    "    df_show = df_show.format('{:.4f}')\n",
    "\n",
    "    return df_show\n",
    "\n",
    "def std_dev(df, cols=default_cols):\n",
    "    show_cols = ['ppl', 'f1', 'gleu',  'ref_precision', 'ref_recall', 'ref_f1', 'corpus_ref_halluc'] if cols is None else cols\n",
    "    df_show = df[['run', 'name'] + cols]\n",
    "    df_show = df_show.groupby('name').std().round(4)\n",
    "    df_show.fillna('--')\n",
    "    return df_show"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "polyphonic-consortium",
   "metadata": {},
   "source": [
    "### Example (lines 4 from Table 5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "consistent-oliver",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5a349498ad32466fb6281f2af1558c7e",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(FloatProgress(value=0.0, max=1.0), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[nltk_data] Downloading package wordnet to /Users/seanw/nltk_data...\n",
      "[nltk_data]   Package wordnet is already up-to-date!\n",
      "100%|██████████| 100/100 [00:01<00:00, 56.43it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>name</th>\n",
       "      <th>ppl</th>\n",
       "      <th>gleu</th>\n",
       "      <th>ref_f1</th>\n",
       "      <th>corpus_ref_halluc</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>stepwise++</td>\n",
       "      <td>1.05</td>\n",
       "      <td>40.8</td>\n",
       "      <td>94.25</td>\n",
       "      <td>1.05</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "         name   ppl  gleu  ref_f1  corpus_ref_halluc\n",
       "0  stepwise++  1.05  40.8   94.25               1.05"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "name2gen_files = {    \n",
    "    'stepwise++___1': '../eval/gpt3curie:ft_valid_gtrefs__stepwise_beam__temp=0.30_n=10_alpha=0.75__diversity-broad__multitemp-broad__set-vf__reduced_ixs__full_generations__run1.json',\n",
    "}\n",
    "name2gen = load_gens(name2gen_files)\n",
    "df = evaluate(name2gen)\n",
    "df[['name', 'ppl', 'gleu', 'ref_f1', 'corpus_ref_halluc']].sort_values('ref_f1').round(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "revolutionary-timer",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}