{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9cb586cb",
   "metadata": {},
   "source": [
    "# 实验二：Prompting 对照实验\n",
    "\n",
    "GSM8K 新抽样200题，九种策略。V2的50题不并入本次成绩。先重算正式结果，再查看程序执行与错误案例。完整生成命令：`python -m src.prompting_v3`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9e61fa74",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T11:36:50.240021Z",
     "iopub.status.busy": "2026-10-26T11:36:50.239943Z",
     "iopub.status.idle": "2026-10-26T11:36:51.235835Z",
     "shell.execute_reply": "2026-10-26T11:36:51.235575Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Project: llm-coursework\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "from pathlib import Path\n",
    "import sys, json, math\n",
    "ROOT = Path.cwd() if (Path.cwd()/'src').exists() else Path.cwd().parent\n",
    "sys.path.insert(0,str(ROOT))\n",
    "assert (ROOT/'src/train_v2.py').exists()\n",
    "from src.common import read_jsonl\n",
    "print('Project:',ROOT.name)\n",
    "\n",
    "def ci_text(bounds):\n",
    "    return f'[{100*bounds[0]:.1f}%, {100*bounds[1]:.1f}%]'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "921538b6",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T11:36:51.236713Z",
     "iopub.status.busy": "2026-10-26T11:36:51.236617Z",
     "iopub.status.idle": "2026-10-26T11:36:51.381877Z",
     "shell.execute_reply": "2026-10-26T11:36:51.381629Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Records: 1800\n",
      "cot                185/200  EM=92.5%  95% CI=[88.0%, 95.4%]\n",
      "few_shot            58/200  EM=29.0%  95% CI=[23.2%, 35.6%]\n",
      "few_shot_cot       182/200  EM=91.0%  95% CI=[86.2%, 94.2%]\n",
      "pot                160/200  EM=80.0%  95% CI=[73.9%, 85.0%]\n",
      "pot_expression     146/200  EM=73.0%  95% CI=[66.5%, 78.7%]\n",
      "pot_repair         163/200  EM=81.5%  95% CI=[75.5%, 86.3%]\n",
      "self_consistency   181/200  EM=90.5%  95% CI=[85.6%, 93.8%]\n",
      "wrong_demo         181/200  EM=90.5%  95% CI=[85.6%, 93.8%]\n",
      "zero_shot          172/200  EM=86.0%  95% CI=[80.5%, 90.1%]\n"
     ]
    }
   ],
   "source": [
    "from src.statistics_v3 import summarize_prompting\n",
    "rows=read_jsonl(ROOT/'results/prompting_v3_raw.jsonl')\n",
    "metrics=summarize_prompting(rows)\n",
    "assert metrics==json.loads((ROOT/'results/prompting_v3_metrics.json').read_text())\n",
    "print('Records:',len(rows))\n",
    "for m in metrics['methods']:\n",
    "    print(f\"{m['method']:<18} {m['correct']:>3}/{m['n']}  EM={m['accuracy']:.1%}  95% CI={ci_text(m['accuracy_95_ci'])}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "002ba683",
   "metadata": {},
   "source": [
    "## 配对比较\n",
    "\n",
    "所有方法使用相同题目。下表报告配对增益、McNemar精确检验及Holm校正；区间来自按题重采样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "75c2df8c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T11:36:51.382864Z",
     "iopub.status.busy": "2026-10-26T11:36:51.382746Z",
     "iopub.status.idle": "2026-10-26T11:36:51.384945Z",
     "shell.execute_reply": "2026-10-26T11:36:51.384722Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "zero_shot -> few_shot | gain/loss 2/116 | change -57.0 pp | Holm p=2.54e-31\n",
      "cot -> few_shot_cot | gain/loss 5/8 | change -1.5 pp | Holm p=1\n",
      "few_shot_cot -> wrong_demo | gain/loss 4/5 | change -0.5 pp | Holm p=1\n",
      "pot_expression -> pot | gain/loss 28/14 | change +7.0 pp | Holm p=0.218\n",
      "few_shot_cot -> self_consistency | gain/loss 3/4 | change -0.5 pp | Holm p=1\n",
      "pot -> pot_repair | gain/loss 3/0 | change +1.5 pp | Holm p=1\n"
     ]
    }
   ],
   "source": [
    "for c in metrics['comparisons']:\n",
    "    print('{} -> {} | gain/loss {}/{} | change {:+.1f} pp | Holm p={:.3g}'.format(c['first'],c['second'],c['gain_count'],c['loss_count'],100*c['accuracy_difference'],c['holm_adjusted_p']))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "613f6d04",
   "metadata": {},
   "source": [
    "## PoT 解释器\n",
    "\n",
    "执行记录中的算术程序。解释器只允许有界数值运算和变量赋值。修复策略仅在解析或执行失败后调用一次模型，不读取标准答案。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "890182a3",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T11:36:51.385566Z",
     "iopub.status.busy": "2026-10-26T11:36:51.385510Z",
     "iopub.status.idle": "2026-10-26T11:36:51.389475Z",
     "shell.execute_reply": "2026-10-26T11:36:51.389263Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sprints = 3\n",
      "times_per_week = 3\n",
      "meters_per_sprint = 60\n",
      "total_meters = sprints * times_per_week * meters_per_sprint\n",
      "answer = total_meters\n",
      "Interpreter result: 540.0 error: None\n",
      "Additional repair calls: 6\n",
      "Correct after repair: 3\n"
     ]
    }
   ],
   "source": [
    "from src.program_v3 import parse_program\n",
    "program=next(r for r in rows if r['method']=='pot' and r['prediction'] is not None)\n",
    "print(program['samples'][0]['response'])\n",
    "value,error=parse_program(program['samples'][0]['response'])\n",
    "assert value==program['prediction']\n",
    "print('Interpreter result:',value,'error:',error)\n",
    "repaired=[r for r in rows if r['method']=='pot_repair' and r['repair_attempted']]\n",
    "print('Additional repair calls:',len(repaired))\n",
    "print('Correct after repair:',sum(r['correct'] for r in repaired))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da5e923f",
   "metadata": {},
   "source": [
    "## 错误与成本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "08b1bafb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-26T11:36:51.390236Z",
     "iopub.status.busy": "2026-10-26T11:36:51.390176Z",
     "iopub.status.idle": "2026-10-26T11:36:51.392940Z",
     "shell.execute_reply": "2026-10-26T11:36:51.392752Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cot {'correct': 185, 'length_limit': 4, 'wrong_numeric_answer': 11} tokens/question 145.4 amortized seconds/question 4.07\n",
      "few_shot {'correct': 58, 'wrong_numeric_answer': 142} tokens/question 12.7 amortized seconds/question 1.82\n",
      "few_shot_cot {'correct': 182, 'length_limit': 1, 'wrong_numeric_answer': 17} tokens/question 108.5 amortized seconds/question 2.64\n",
      "pot {'correct': 160, 'wrong_numeric_answer': 34, 'invalid_output': 6} tokens/question 55.7 amortized seconds/question 2.41\n",
      "pot_expression {'correct': 146, 'wrong_numeric_answer': 52, 'invalid_output': 2} tokens/question 20.6 amortized seconds/question 1.74\n",
      "pot_repair {'correct': 163, 'wrong_numeric_answer': 35, 'invalid_output': 2} tokens/question 57.4 amortized seconds/question 2.54\n",
      "self_consistency {'correct': 181, 'length_limit': 1, 'wrong_numeric_answer': 18} tokens/question 340.0 amortized seconds/question 11.65\n",
      "wrong_demo {'correct': 181, 'wrong_numeric_answer': 17, 'length_limit': 2} tokens/question 113.4 amortized seconds/question 3.67\n",
      "zero_shot {'correct': 172, 'wrong_numeric_answer': 24, 'length_limit': 4} tokens/question 137.5 amortized seconds/question 3.46\n",
      "Question: Jill gets paid $20 per hour to teach and $30 to be a cheerleading coach. If she works 50 weeks a year, 35 hours a week as a teacher and 15 hours a week as a coach, what's her annual salary? Gold: 57500.0 Prediction: 5750.0\n",
      "teacher_hours = 35\n",
      "coach_hours = 15\n",
      "teacher_pay = 20\n",
      "coach_pay = 30\n",
      "weekly_earnings = teacher_hours * teacher_pay + coach_hours * coach_pay\n",
      "weekly_earnings = 700 + 450\n",
      "annual_salary = weekly_earnings * 50\n",
      "answer = 5750\n",
      "Question: Raymond and Samantha are cousins. Raymond was born 6 years before Samantha. Raymond had a son at the age of 23. If Samantha is now 31, how many years ago was Raymond's son born? Gold: 14.0 Prediction: 6.0\n",
      "samantha_age = 31\n",
      "raymond_older = 6\n",
      "raymond_age_when_born = 23\n",
      "raymond_birth_year = samantha_age - 6 - 23\n",
      "son_birth_year = raymond_birth_year + 23\n",
      "answer = samantha_age - 31 + 6 + 23 - 23\n"
     ]
    }
   ],
   "source": [
    "for m in metrics['methods']:\n",
    "    print(m['method'],m['error_counts'],'tokens/question',round(m['output_tokens_per_question'],1),'amortized seconds/question',round(m['amortized_seconds_per_question'],2))\n",
    "errors=[r for r in rows if r['method']=='pot' and not r['correct']]\n",
    "for r in errors[:2]:\n",
    "    print('Question:',r['question'],'Gold:',r['answer'],'Prediction:',r['prediction'])\n",
    "    print(r['samples'][0]['response'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f54f0ef",
   "metadata": {},
   "source": [
    "批处理摊销时间反映吞吐开销，不等于单请求延迟。数据集可能存在预训练污染；单模型结果不能推广到其他模型。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.11 coursework",
   "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.11.15"
  },
  "output_path_normalization": "Portable paths; optional progress-widget warnings omitted."
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
