{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uRLjFRmzHJXS"
      },
      "source": [
        "# Assignment 4: Post Training!\n",
        "<!-- <p align=\"center\">\n",
        "  <img src=\"https://pixeljoint.com/files/icons/full/charmander_evos.png\" width=\"450\">\n",
        "</p>\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://completecollector.co.uk/hubfs/Screenshot%202024-04-07%20at%2022.53.50.png\" width=\"450\">\n",
        "</p>\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://static0.anpoimages.com/wordpress/wp-content/uploads/2022/11/eeveelutionHero.jpg?w=1600&h=900&fit=crop\" width=\"450\">\n",
        "</p> -->\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://www.esports.net/wp-content/uploads/2023/11/eveelutions.jpg\" width=\"650\">\n",
        "</p>\n",
        "\n",
        "In this assignment you'll learn some of the **motivations and methods behind post-training language models**.\n",
        "\n",
        "The assignment is broken down into **five** parts:\n",
        "\n",
        "  - **1)** Set up a Hugging Face account and experiment with a small pre-trained model. For this assignment, we will be using Llama-3.2-1B.\n",
        "\n",
        "  - **2)** Load and explore the GSM8K dataset.\n",
        "\n",
        "  - **3)** Write an evaluation method to test the performance of your models on the GSM8K dataset.\n",
        "\n",
        "  - **4)** Fine-tune a pretrained model to use Chain of Thought (CoT).\n",
        "\n",
        "  - **5)** Do more RL post-training to further improve model performance.\n",
        "\n",
        "\n",
        "**Please note**:\n",
        "- **Snippets** marked with `TODO STUDENT START/END` are for you to complete.\n",
        "- If you have colab notebook pro, you can try changing the runtime type to A100. If not, use the L4 GPU. With L4, the expected training time for Part 4 (SFT) is < 30 mins and ~ 30m-1hr for Part 5 (RL) to train for 0.1 epoch, which will not give you much performance improvement. We will not grade you based on final accuracy.\n"
      ]
    },
    {
      "metadata": {
        "id": "qWCQmXCLYQNB"
      },
      "cell_type": "markdown",
      "source": [
        "# Part 1: HuggingFace Setup and Base Model Exploration\n",
        "\n",
        "We will be using **meta-llama/Llama-3.2-1B** from HuggingFace. It is a **gated** model: you need to accept Meta's license on the\n",
        "[model page](https://huggingface.co/meta-llama/Llama-3.2-1B) (approval usually takes a few minutes to a few hours, so do this early).\n",
        "\n",
        "1) Create a HuggingFace account with your student email.\n",
        "\n",
        "2) Create a HuggingFace access token with:\n",
        "\n",
        "  -  **Read and write access to contents of all repos under your personal namespace**\n",
        "\n",
        "  -  **IMPORTANT:** Anybody holding this token can read from and write to any model on your\n",
        "     account. Do not share it, and do not leave it in your submission.\n",
        "\n",
        "3) Run the cell below to log in, and type n when asked about git credentials."
      ]
    },
    {
      "metadata": {
        "id": "mBJcOOmIbhVi"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "%pip install huggingface_hub==1.33.0\n",
        "%pip install -U bitsandbytes==0.50.2\n",
        "# Colab's preinstalled torchao is too old for peft (LoRA) and we don't need it. Remove it to avoid an ImportError later.\n",
        "%pip uninstall -y torchao\n",
        "!hf auth login\n",
        "\n",
        "# TODO STUDENT START: Set your HuggingFace username, which will be used for pushing checkpoints\n",
        "HF_USERNAME = \"YOUR_USERNAME\"\n",
        "\n",
        "BASE_MODEL_NAME = \"meta-llama/Llama-3.2-1B\"\n",
        "MODEL_NAME_STRING = \"llama3.2-1B\"\n",
        "\n",
        "# This is where your ckpts will be uploaded to. Change the naming if you want\n",
        "SFT_REPO = f\"{HF_USERNAME}/gsm8ksft-{MODEL_NAME_STRING}-lora\"\n",
        "RL_REPO  = f\"{HF_USERNAME}/gsm8krl-{MODEL_NAME_STRING}-lora\"\n",
        "# TODO STUDENT END"
      ]
    },
    {
      "metadata": {
        "id": "k1E-zPRAJUiB"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "from transformers import AutoModelForCausalLM, AutoTokenizer,StoppingCriteria, StoppingCriteriaList\n",
        "tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)\n",
        "model = AutoModelForCausalLM.from_pretrained(BASE_MODEL_NAME, dtype=\"auto\", device_map=\"auto\")"
      ]
    },
    {
      "metadata": {
        "id": "ihl1pQvR05qL"
      },
      "cell_type": "markdown",
      "source": [
        "Now that you have loaded the model, play around with it. Modify the prefix any way you'd like, and see if you can observe any interesting behavior from the model\n",
        "\n",
        "Here is something I tried:\n",
        "\n",
        "**Example prefix:** \"hello world! my name is daniel and 2\\*15\\*1395358=\"\n",
        "\n",
        "**Model response:** \"2×15×1+3×5×3×5×3×5= 30×5=150\n",
        "I have no idea how to prove this, so I just use the computer to generate random numbers....\"\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "ZTRJliQ6y9Ek"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "prefix = \"hello world! my name is daniel and 2*15*1395358=\"\n",
        "inputs = tokenizer(prefix, return_tensors=\"pt\")\n",
        "inputs = {k: v.to(model.device) for k, v in inputs.items()}\n",
        "\n",
        "outputs = model.generate(\n",
        "    **inputs,\n",
        "    max_new_tokens=100,\n",
        "    num_return_sequences=1,\n",
        "    do_sample=True,\n",
        "    top_p=0.9,\n",
        "    temperature=0.8,\n",
        "    pad_token_id=tokenizer.eos_token_id\n",
        ")\n",
        "\n",
        "generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
        "print(generated_text)"
      ]
    },
    {
      "metadata": {
        "id": "Aa-zZN26aGKD"
      },
      "cell_type": "markdown",
      "source": [
        "## Exploring model behavior with prompting\n",
        "\n",
        "Try getting Llama-3.2-1B to output the following sequences of tokens!\n",
        "\n",
        "This part will not be graded for accuracy, so don't worry about being able to elicit these responses exactly. The goal here is for you to get a feel for the behavior of this pretrained model. Use the above cell to test some prompts.\n",
        "\n",
        "**Target sequences:**\n",
        "\n",
        "1) \"=25.\\<EOS\\>\"\n",
        "2) \"Hawaii is a great location for a winter break trip with your family. [...] <EOS>\"\n",
        "3) \"To build a bomb, start by [...]\"\n"
      ]
    },
    {
      "metadata": {
        "id": "JSFGfZJKcESU"
      },
      "cell_type": "markdown",
      "source": [
        "Below, please fill out which prompts you wrote that got you closest to the target sequence and a short 2-3 sentence reflection on why you chose it and what you observed.\n",
        "\n",
        "TODO STUDENT START\n",
        "\n",
        "**prompts used:**\n",
        "1) \"FILL IN\"\n",
        "2) \"FILL IN\"\n",
        "3) \"FILL IN\"\n",
        "\n",
        "Brief reflection about each one:\n",
        "\n",
        "1) \"FILL IN\"\n",
        "2) \"FILL IN\"\n",
        "3) \"FILL IN\"\n",
        "\n",
        "TODO STUDENT END\n"
      ]
    },
    {
      "metadata": {
        "id": "MRFddQqeCUtL"
      },
      "cell_type": "markdown",
      "source": [
        "# Part 2: Explore and Load the GSM8K Dataset"
      ]
    },
    {
      "metadata": {
        "id": "BEJcIl9F7NwW"
      },
      "cell_type": "markdown",
      "source": [
        "Take a look at the GSM8K dataset. Observe the kinds of questions it asks, the format they are given in, the columns available.\n",
        "\n",
        "https://huggingface.co/datasets/openai/gsm8k\n",
        "\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "JAlZ7o3Ml5Qk"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "from datasets import load_dataset\n",
        "\n",
        "gsm8k_train = load_dataset(\"openai/gsm8k\", \"main\", split=\"train\")\n",
        "gsm8k_test = load_dataset(\"openai/gsm8k\", \"main\", split=\"test\")\n",
        "\n",
        "print(len(gsm8k_train))\n",
        "print(len(gsm8k_test))"
      ]
    },
    {
      "metadata": {
        "id": "K9xfOWt4tFAV"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "prefix = \"Your role as an assistant involves thoroughly exploring questions through a systematic thinking process before providing the final precise and accurate solutions. End your response with \\\"Therefore, the answer is\\\". Now, try to solve the following question:\"\n",
        "problem = \"Problem: If I have 3 apples, and in sum they cost $4.5, how much does it cost to buy 2 apples?\"\n",
        "prompt = prefix + problem\n",
        "\n",
        "inputs = tokenizer(prompt, return_tensors=\"pt\")\n",
        "inputs = {k: v.to(model.device) for k, v in inputs.items()}\n",
        "outputs = model.generate(\n",
        "    **inputs,\n",
        "    max_new_tokens=300,\n",
        "    num_return_sequences=1,\n",
        "    do_sample=True,\n",
        "    top_p=0.8,\n",
        "    temperature=1.0,\n",
        "    pad_token_id=tokenizer.eos_token_id,\n",
        ")\n",
        "\n",
        "generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
        "print(generated_text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JcsS_WE_k0uz"
      },
      "source": [
        "You might have noticed that the GSM8K dataset has a numerical answer following the #### delimeter in the answer body. We will be trying to use this to parse out the ground truth from the dataset and the answers from the model's responses.\n",
        "\n",
        "Fill in the methods below."
      ]
    },
    {
      "metadata": {
        "id": "-G6Puudinkc3"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "def extract_answer_after_hashes(s):\n",
        "    # split on \"####\", strip spaces, take everything after. Returns string\n",
        "    ## Fill in with your code ##\n",
        "    # TODO STUDENT START\n",
        "    ans =\n",
        "    # TODO STUDENT END\n",
        "    return ans\n"
      ]
    },
    {
      "metadata": {
        "id": "lX_7OBgQnvUW"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "def preprocess_gsm8k(example):\n",
        "  # take a single row from gsm8k and return as the following columns: {\"question\", \"response\", \"numeric_response\"}\n",
        "  return {\"question\": example[\"question\"], \"response\": example[\"answer\"], \"numeric_answer\": extract_answer_after_hashes(example[\"answer\"])}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "DT2CYE_Jh68-"
      },
      "outputs": [],
      "source": [
        "# Apply the preprocessing to both splits, so every row has {question, response, numeric_answer}.\n",
        "gsm8k_train = gsm8k_train.map(preprocess_gsm8k, remove_columns=gsm8k_train.column_names)\n",
        "gsm8k_test  = gsm8k_test.map(preprocess_gsm8k,  remove_columns=gsm8k_test.column_names)\n",
        "\n",
        "# Evaluating on the full test set is not cheap: we generate up to 300 tokens per question,\n",
        "# one question at a time within a batch. Use a fixed subset instead -- and use the SAME\n",
        "# subset for every evaluation in this notebook, or the base / SFT / RL numbers you report\n",
        "# will not be comparable to each other.\n",
        "N_EVAL = 200\n",
        "gsm8k_test_sample = gsm8k_test.select(range(N_EVAL))\n",
        "\n",
        "print(gsm8k_train)\n",
        "print(f\"\\nevaluating on {len(gsm8k_test_sample)} of {len(gsm8k_test)} test questions\\n\")\n",
        "print(gsm8k_test_sample[0])"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "72kMv_d5but2"
      },
      "source": [
        "# Part 3: Evaluate Model Performance on GSM8K"
      ]
    },
    {
      "metadata": {
        "id": "-G-zsBqXh68-"
      },
      "cell_type": "markdown",
      "source": [
        "## Evaluation Metric / Verifier"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### First Attempt\n",
        "Parsing out gold answers from the dataset is easy: GSM8K always puts the final number after `####`. However, to evaluate the model, we need to parse a text response and score it against the ground truth answer.\n",
        "\n",
        "Here is the code for extracting and grading prediction that OpenAI first released for GSM8k:"
      ],
      "metadata": {
        "id": "aXM8vWPq0mmt"
      }
    },
    {
      "metadata": {
        "id": "AglgwBQ4h68-"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "import re\n",
        "\n",
        "ANS_RE = re.compile(r\"#### (\\-?[0-9\\.\\,]+)\")\n",
        "INVALID_ANS = \"[invalid]\"\n",
        "\n",
        "\n",
        "def extract_answer(completion):\n",
        "    \"\"\"\n",
        "    Use the provided regex to parse out the answer\n",
        "    If there is an answer, return that answer string\n",
        "    Otherwise, return INVALID_ANS\n",
        "    \"\"\"\n",
        "    match = ANS_RE.search(completion)\n",
        "    if match:\n",
        "        match_str = match.group(1).strip()\n",
        "        match_str = match_str.replace(\",\", \"\")\n",
        "        return match_str\n",
        "    else:\n",
        "        return INVALID_ANS\n",
        "\n",
        "def evaluate_em(gen, ans):\n",
        "    \"\"\"\n",
        "    Extract with the regex above, then compare the two values as strings.\n",
        "    \"\"\"\n",
        "    gold_str = str(ans).strip().replace(\",\", \"\")\n",
        "    prediction = extract_answer(gen)\n",
        "    em_flag = 1 if (prediction != INVALID_ANS and prediction == gold_str) else 0\n",
        "    return em_flag, prediction, ans"
      ]
    },
    {
      "metadata": {
        "id": "4zQpLrBZh68-"
      },
      "cell_type": "markdown",
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Q: What could potentially be wrong with this evaluation metric? Give at least two concrete model outputs where the model's answer is actually correct but this metric scores it as wrong (or the other way around), and briefly explain each failiure mode.\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "TODO STUDENT END"
      ]
    },
    {
      "metadata": {
        "id": "HZQ_xN3Ih68-"
      },
      "cell_type": "markdown",
      "source": [
        "### A More Reliable Verifier\n",
        "\n",
        "Below is the parser we use for the rest of the notebook. Answer the question above before reading the rest."
      ]
    },
    {
      "metadata": {
        "id": "hOxtSB6Eh68-"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "import re\n",
        "from decimal import Decimal, InvalidOperation\n",
        "from fractions import Fraction\n",
        "\n",
        "_NUM_RE = re.compile(r\"[-+]?\\d{1,3}(?:,\\d{3})+(?:\\.\\d+)?|[-+]?\\d+(?:\\.\\d+)?(?:/[1-9]\\d*)?\")\n",
        "_ANS_RE = re.compile(r\"####\\s*(\" + _NUM_RE.pattern + r\")\")\n",
        "\n",
        "_THEREFORE_RE = re.compile(\n",
        "    r\"(?:therefore|so|thus)[,:]?\\s*(?:the\\s+)?answer\\s+is[:\\s]*\\$?\\s*(\" + _NUM_RE.pattern + r\")\",\n",
        "    flags=re.I,\n",
        ")\n",
        "\n",
        "\n",
        "def _to_decimal(s):\n",
        "    \"\"\"Parse into a Decimal; returns None if unparseable.\"\"\"\n",
        "    s = str(s).strip().replace(\",\", \"\")\n",
        "    if \"/\" in s:\n",
        "        try:\n",
        "            f = Fraction(s)\n",
        "            return Decimal(f.numerator) / Decimal(f.denominator)\n",
        "        except Exception:\n",
        "            return None\n",
        "    try:\n",
        "        return Decimal(s)\n",
        "    except InvalidOperation:\n",
        "        return None\n",
        "\n",
        "\n",
        "def normalize_num(s):\n",
        "    return _to_decimal(str(s))\n",
        "\n",
        "\n",
        "def extract_answer(text: str):\n",
        "    \"\"\"Recover the answer from the formats the prompt asks for; returns None if neither is present.\"\"\"\n",
        "    # 1) \"#### <number>\"\n",
        "    hits = list(_ANS_RE.finditer(text))\n",
        "    if hits:\n",
        "        return _to_decimal(hits[-1].group(1))\n",
        "\n",
        "    # 2) \"... the answer is <number>\"\n",
        "    hits = list(_THEREFORE_RE.finditer(text))\n",
        "    if hits:\n",
        "        return _to_decimal(hits[-1].group(1))\n",
        "\n",
        "    return None\n",
        "\n",
        "\n",
        "def evaluate_em(gen, ans):\n",
        "    \"\"\"\n",
        "    Extract with the parser above, then compare the two values as Decimals (not strings),\n",
        "    \"\"\"\n",
        "    pred = extract_answer(gen)\n",
        "    gold = normalize_num(ans)\n",
        "    em_flag = 1 if (pred is not None and gold is not None and pred == gold) else 0\n",
        "    return em_flag, pred, gold\n"
      ]
    },
    {
      "metadata": {
        "id": "0gVeie6Eh68-"
      },
      "cell_type": "markdown",
      "source": [
        "**Why this matters**\n",
        "\n",
        "People like training LLMs on math datasets such as GSM8K, because the answers are \"verifiable\": each question has one correct number. However, the model gives us text, not a number. A task is only as verifiable as its verifier, and we as model developer decide what verifier counts as \"correct\".\n",
        "\n",
        "No matter what tasks you are working on, make sure your metric is actually measuring what you want it to measure."
      ]
    },
    {
      "metadata": {
        "id": "XmVXygdRh68-"
      },
      "cell_type": "markdown",
      "source": [
        "## Prompt Formatting\n",
        "Besides improving the parser, we can also use the prompt to guide the model to generate gradable outputs by prompting it to answer in the format our parser expects.\n",
        "\n",
        "So how should we present each GSM8K question in the input? This is up to you, but three key pieces of information you might start with are:\n",
        "\n",
        "1) role information\n",
        "2) how the question should be attempted\n",
        "3) formatting guidelines\n",
        "\n",
        "Here is a template you might follow:\n",
        "\n",
        "\"Your role... that involves correctly solving math questions in a...  When you are ready to give your solution, format as follows. \\n#### \\<NUMERIC_ANSWER\\>.\\n Now solve the following problem:\\n\".\n",
        "\n",
        "Now define the prefix below."
      ]
    },
    {
      "metadata": {
        "id": "Zho7j5BVw_yd"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "# Change this prompt to your own need\n",
        "PROMPT_GSM8K = (\n",
        "    \"\"\n",
        "    \"When you are ready to give your solution, format as follows. \\n#### <ANSWER>.\\n Now solve the following problem:\\n\"\n",
        ")"
      ]
    },
    {
      "metadata": {
        "id": "4hDZ6Z0n5HjJ"
      },
      "cell_type": "markdown",
      "source": [
        "## Evaluate the Base Model\n",
        "\n",
        "Finally, we will combine the helpers together into our evaluation loop. No coding work is needed here, but take a read to understand how it works."
      ]
    },
    {
      "metadata": {
        "id": "Pk8Fbd6XprW2"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "import torch, torchsummary\n",
        "def evaluate_gsm8k(\n",
        "    model_name,\n",
        "    questions,\n",
        "    gold_answers,\n",
        "    batch_size=4,\n",
        "    max_new_tokens=300, # notice we limit the response to 300 tokens to keep inference cheap\n",
        "    prefix=None,\n",
        "    print_every=20,   # print one detailed sample every N examples\n",
        "):\n",
        "    tok = AutoTokenizer.from_pretrained(model_name, use_fast=True)\n",
        "    tok.padding_side = \"left\"\n",
        "    if tok.pad_token is None:\n",
        "        tok.pad_token = tok.eos_token\n",
        "\n",
        "    mdl = AutoModelForCausalLM.from_pretrained(\n",
        "        model_name, device_map=\"cuda\", torch_dtype=torch.bfloat16\n",
        "    )\n",
        "    mdl.eval()\n",
        "\n",
        "    prefix = prefix\n",
        "\n",
        "    outs = []\n",
        "    records = []\n",
        "    total_early, total_seen = 0, 0\n",
        "    correct_responses = []\n",
        "\n",
        "    with torch.inference_mode():\n",
        "        for i in range(0, len(questions), batch_size):\n",
        "            print(f\"Evaluation progress: {min(i + batch_size, len(questions))} / {len(questions)}\")\n",
        "\n",
        "            batch_q = questions[i:i + batch_size]\n",
        "            prompts = [prefix + q for q in batch_q]\n",
        "\n",
        "            enc = tok(prompts, return_tensors=\"pt\", padding=True, truncation=True)\n",
        "            enc = {k: v.to(mdl.device, non_blocking=True) for k, v in enc.items()}\n",
        "            enc_len = enc[\"input_ids\"].shape[1]\n",
        "\n",
        "            # notice we are doing greedy decoding here. This is typical in an evaluation setting, where we don't want any source of randomness to affect the accuracy.\n",
        "            gen = mdl.generate(\n",
        "                **enc,\n",
        "                max_new_tokens=max_new_tokens,\n",
        "                do_sample=False,\n",
        "                temperature=0.0,\n",
        "                top_p=1.0,\n",
        "                use_cache=True,\n",
        "                pad_token_id=tok.eos_token_id,\n",
        "                eos_token_id=tok.eos_token_id,\n",
        "                return_dict_in_generate=False,\n",
        "                output_scores=False,\n",
        "            )\n",
        "\n",
        "            new_tokens = gen[:, enc_len:]\n",
        "            texts = tok.batch_decode(new_tokens, skip_special_tokens=True)\n",
        "\n",
        "            for j, (q, t, gold) in enumerate(zip(batch_q, texts, gold_answers[i:i + batch_size])):\n",
        "                idx = i + j   # Index of this example across the whole eval set\n",
        "                gen_len = int(new_tokens[j].shape[0])\n",
        "                early = gen_len < max_new_tokens\n",
        "                hit_marker = (\"####\" in t) or (\"<|end_of_solution|>\" in t)\n",
        "\n",
        "                cleaned = t.rstrip()\n",
        "                outs.append(cleaned)\n",
        "\n",
        "                em_flag, pred_num, gold_num = evaluate_em(t, gold)\n",
        "\n",
        "                if em_flag == 1:\n",
        "                    correct_responses.append({\n",
        "                        \"idx\": idx,\n",
        "                        \"question\": q,\n",
        "                        \"generation\": t,\n",
        "                        \"pred\": pred_num,\n",
        "                        \"gold\": gold_num\n",
        "                    })\n",
        "\n",
        "                rec = {\n",
        "                    \"idx\": idx,\n",
        "                    \"question\": q,\n",
        "                    \"generation\": t,     # raw generation (with markers if any)\n",
        "                    \"cleaned\": cleaned,  # truncated at markers\n",
        "                    \"pred_num\": str(pred_num) if pred_num is not None else None,\n",
        "                    \"gold\": gold,\n",
        "                    \"gold_num\": str(gold_num) if gold_num is not None else None,\n",
        "                    \"em\": em_flag,\n",
        "                    \"gen_len\": gen_len,\n",
        "                    \"max_new_tokens\": int(max_new_tokens),\n",
        "                    \"early_stop\": early,\n",
        "                    \"hit_marker\": hit_marker,\n",
        "                }\n",
        "                records.append(rec)\n",
        "\n",
        "                total_seen += 1\n",
        "                total_early += int(early)\n",
        "\n",
        "                if (i + j) % max(1, print_every) == 0:\n",
        "                    print(f\"[{rec['idx']}] early={rec['early_stop']} len={rec['gen_len']} EM={rec['em']}\")\n",
        "                    print(f\"Q: {q}\")\n",
        "                    print(f\"GEN: {t}\")\n",
        "                    print(f\"PRED={rec['pred_num']} | GOLD={rec['gold_num']}\")\n",
        "                    print(\"-\" * 80)\n",
        "\n",
        "            # free per-batch tensors\n",
        "            del gen, new_tokens, texts, enc\n",
        "\n",
        "    # Aggregate stats\n",
        "    early_rate = total_early / max(1, total_seen)\n",
        "    gen_lengths = [r[\"gen_len\"] for r in records]\n",
        "    mean_len = sum(gen_lengths) / max(1, len(gen_lengths))\n",
        "    median_len = sorted(gen_lengths)[len(gen_lengths) // 2] if gen_lengths else 0\n",
        "\n",
        "    accuracy = sum(r[\"em\"] for r in records) / max(1, len(records))\n",
        "\n",
        "    print(\"\\n=== Evaluation summary ===\")\n",
        "    print(f\"Accuracy (EM): {accuracy:.4f}\")\n",
        "    print(f\"Early-stop rate: {early_rate*100:.1f}%\")\n",
        "    print(f\"Gen length: mean={mean_len:.1f}, median={median_len}, cap={max_new_tokens}\")\n",
        "    print(\"==========================\\n\")\n",
        "\n",
        "    if correct_responses:\n",
        "      print(f\"\\n=== Correct predictions ({len(correct_responses)}) ===\")\n",
        "      for s in correct_responses[:10]:\n",
        "          print(f\"[{s['idx']}] PRED={s['pred']} | GOLD={s['gold']}\")\n",
        "          print(\"Q:\", s[\"question\"])\n",
        "          print(\"GEN:\", s[\"generation\"])\n",
        "          print(\"-\" * 80)\n",
        "    return accuracy, outs, records"
      ]
    },
    {
      "metadata": {
        "id": "tAblsqXxp_NN"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "accuracy, outs, records = evaluate_gsm8k(BASE_MODEL_NAME, gsm8k_test_sample[\"question\"], gsm8k_test_sample[\"numeric_answer\"], batch_size=16, prefix=PROMPT_GSM8K)\n",
        "\n",
        "print(f\"Accuracy: {accuracy}\")"
      ]
    },
    {
      "metadata": {
        "id": "AawmMDUzmgWS"
      },
      "cell_type": "markdown",
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Please record your accuracy here:\n",
        "\n",
        "\\<ACCURACY\\>\n",
        "\n",
        "And 5 examples here, ideally a mix of correct and incorrect examples:\n",
        "\n",
        "\\<SAMPLES\\>\n",
        "\n",
        "What do you notice about the behavior of the model when faced these questions?\n",
        "\n",
        "\\<3-5 sentence reflection\\>\n",
        "\n",
        "TODO STUDENT END\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mntxPOIQ04tN"
      },
      "source": [
        "# Part 4: Supervised Fine Tuning"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uzDL1O0dQeY-"
      },
      "source": [
        "Now we will do supervised fine-tuning (SFT) on GSM8K. SFT uses the same next-token loss as pretraining, but on (prompt, response) pairs. Similar to machine translation in Assignment 3, only the response tokens count toward the loss.\n",
        "\n",
        "Q: After SFT, we will conduct on-policy RL training to further improve the model. Why might someone wants to do SFT before on-policy RL?\n",
        "\n",
        "TODO STUDENT START\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "TODO STUDENT END"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jG-d7xNuh_xb"
      },
      "source": [
        "## Preprocessing Dataset for Finetuning\n",
        "Let's first pretokenize all our training data. We will be using the GSM8K dataset to fine tune Llama-3.2-1B.\n",
        "\n",
        "The benefit of doing this is that it avoids re-tokenizing the same text repeatedly during training, which saves time and ensures that all examples share a consistent tokenization scheme. It also lets us inspect and cache tokenized sequences in advance, which is useful for debugging. Most importantly, pretokenization significantly improves efficiency by reducing on-the-fly preprocessing overhead during each training step.\n"
      ]
    },
    {
      "metadata": {
        "id": "puDlVfYTbut3"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "import os\n",
        "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n",
        "\n",
        "tok = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, use_fast=True)\n",
        "tok.padding_side = \"right\"\n",
        "\n",
        "if tok.pad_token is None:\n",
        "    tok.pad_token = tok.eos_token\n",
        "tok.truncation_side = \"left\"\n",
        "\n",
        "MAX_LEN = 400 # I chose this because at ~3 characters a token, this admits a total sequence of 1200 characters.\n",
        "              #The distribution of character lengths for the summed question, answer columns is mostly under 1200 characters.\n",
        "BUDGET = MAX_LEN - 1\n",
        "\n",
        "#TODO STUDENT START: Tokenize the system prompt/prefix PROMPT_GSM8K you defined previously.\n",
        "# Start the sequence with the BOS token (tok.bos_token_id), as the tokenizer does by default (and as evaluate_gsm8k does).\n",
        "SYS_IDS =\n",
        "#TODO STUDENT END\n",
        "\n",
        "def tokenize_batch(batch, include_answer=True):\n",
        "    qs = [q.rstrip() for q in batch[\"question\"]]\n",
        "\n",
        "    #TODO STUDENT START: Tokenize qs without adding special tokens or padding\n",
        "    enc_q =\n",
        "    #TODO STUDENT END\n",
        "    has_response = \"response\" in batch and include_answer\n",
        "\n",
        "    if has_response:\n",
        "        ans = [a.rstrip() for a in batch[\"response\"]]\n",
        "        #TODO STUDENT START: Tokenize ans without adding special tokens or padding\n",
        "        enc_a =\n",
        "        #END TODO#\n",
        "    else:\n",
        "        enc_a = {\"input_ids\": [[] for _ in qs]}\n",
        "\n",
        "    gold_answers = [(n or \"\").rstrip() for n in batch.get(\"numeric_answer\", [\"\"] * len(qs))]\n",
        "    input_ids_list, prompt_len_list, kept_gold = [], [], []\n",
        "\n",
        "    for i, (q_ids, a_ids) in enumerate(zip(enc_q[\"input_ids\"], enc_a[\"input_ids\"])):\n",
        "        #TODO STUDENT START: Define the whole input id sequence (system prompt, input question, and output)\n",
        "        ids =\n",
        "        #TODO STUDENT END\n",
        "        if len(ids) > MAX_LEN:\n",
        "            #TODO STUDENT START: early truncate the answer to keep the entire input id sequence to be within the MAX_LEN budget\n",
        "            ids =\n",
        "            #TODO STUDENT END\n",
        "        input_ids_list.append(ids)\n",
        "        prompt_len_list.append(len(SYS_IDS) + len(q_ids))\n",
        "        kept_gold.append(gold_answers[i])\n",
        "\n",
        "    return {\"input_ids\": input_ids_list, \"prompt_len\": prompt_len_list, \"gold_answer\": kept_gold}\n",
        "\n",
        "\n",
        "train_tok = gsm8k_train.map(\n",
        "    tokenize_batch,\n",
        "    batched=True,\n",
        "    batch_size=1024,\n",
        "    num_proc=2,\n",
        "    remove_columns=gsm8k_train.column_names,\n",
        "    writer_batch_size=1024,\n",
        "    desc=\"Tokenizing train set\",\n",
        "    fn_kwargs={\"include_answer\": True}\n",
        ")\n",
        "\n",
        "val_tok = gsm8k_test.map(\n",
        "    tokenize_batch,\n",
        "    batched=True,\n",
        "    batch_size=1024,\n",
        "    num_proc=2,\n",
        "    remove_columns=gsm8k_test.column_names,\n",
        "    writer_batch_size=1024,\n",
        "    desc=\"Tokenizing val set\",\n",
        "    fn_kwargs={\"include_answer\": True}\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Xt5pE5oO-vHw"
      },
      "source": [
        "Additionally, we do have to make sure Llama-3.2-1B can handle any sequence we're interested in. Let's check the maximum context length for Llama-3.2-1B, and compare against the token lengths in the tokenized examples."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "2r5HZ56h-u40"
      },
      "outputs": [],
      "source": [
        "from transformers import AutoModelForCausalLM\n",
        "mdl = AutoModelForCausalLM.from_pretrained(BASE_MODEL_NAME, device_map=\"auto\", torch_dtype=\"auto\")\n",
        "print(\"max_position_embeddings:\", getattr(mdl.config, \"max_position_embeddings\", None))"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "u7Hf3weF37G9"
      },
      "outputs": [],
      "source": [
        "count = 0\n",
        "total = 0\n",
        "for i in range(0,1000,10):\n",
        "  if (len(train_tok[i]['input_ids']) >= 400):\n",
        "    count+=1\n",
        "  total +=1\n",
        "print(count/total)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KIoaWPnRB1LI"
      },
      "source": [
        "The PromptMaskedCollator is responsible for taking a list of examples (each containing tokenized input IDs, attention masks, and the length of the prompt) and turning them into a single batch tensor that the model can train on. Importantly, the collator is responsible for masking the log probabilities of the prompt tokens. Fill in the masking logic."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "x4lg4bMJ6YWD"
      },
      "outputs": [],
      "source": [
        "class PromptMaskedCollator:\n",
        "    def __init__(self, tokenizer, pad_to_multiple_of=8):\n",
        "        self.tok = tokenizer\n",
        "        self.pad_to_multiple_of = pad_to_multiple_of\n",
        "\n",
        "    def __call__(self, features):\n",
        "        prompt_len = torch.tensor([f[\"prompt_len\"] for f in features], dtype=torch.long)\n",
        "\n",
        "        # only pad input_ids: other columns (e.g. the gold_answer strings) cannot become tensors\n",
        "        feats_wo_plen = [{\"input_ids\": f[\"input_ids\"]} for f in features]\n",
        "\n",
        "        batch = self.tok.pad(\n",
        "            feats_wo_plen,\n",
        "            padding=True,\n",
        "            return_tensors=\"pt\",\n",
        "            pad_to_multiple_of=self.pad_to_multiple_of,\n",
        "        )\n",
        "\n",
        "        input_ids = batch[\"input_ids\"]\n",
        "        attn = batch[\"attention_mask\"]\n",
        "\n",
        "        T = input_ids.size(1)\n",
        "        ar = torch.arange(T, device=input_ids.device).unsqueeze(0)\n",
        "        plen = prompt_len.unsqueeze(1).to(device=input_ids.device)\n",
        "\n",
        "        # TODO STUDENT START:\n",
        "        labels =\n",
        "        labels[] =\n",
        "        labels[] =\n",
        "        # TODO STUDENT END\n",
        "        batch[\"labels\"] = labels\n",
        "        return batch\n",
        "\n",
        "\n",
        "collator = PromptMaskedCollator(tok)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VsP25SUD64aj"
      },
      "source": [
        "## SFT with LoRA\n",
        "\n",
        "In order to do SFT fast, we will fine tune our model using a method called LoRA, which has been covered in class. Implementing it isn't trivial in raw PyTorch, so instead of we'll be using a library called [peft](https://huggingface.co/docs/peft/en/index).\n",
        "\n",
        "Q: Please read through the documentation of LoraConfig (https://huggingface.co/docs/peft/main/en/package_reference/lora#peft.LoraConfig). For each parameter used in the following block, briefly explain its functionality.\n",
        "\n",
        "TODO STUDENT START\n",
        "\n",
        "A:\n",
        "- r:\n",
        "- lora_alpha:\n",
        "- lora_dropout:\n",
        "- task_type:\n",
        "- target_modules:\n",
        "\n",
        "TODO STUDENT END\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "wQ9DcXVkV1Km"
      },
      "outputs": [],
      "source": [
        "import torch\n",
        "from transformers import (\n",
        "    AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, BitsAndBytesConfig\n",
        ")\n",
        "from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n",
        "\n",
        "model = AutoModelForCausalLM.from_pretrained(\n",
        "    BASE_MODEL_NAME,\n",
        "    device_map=\"auto\",\n",
        "    torch_dtype=torch.float16,\n",
        "    attn_implementation=\"sdpa\",\n",
        ")\n",
        "\n",
        "model.config.use_cache = False\n",
        "lora_config = LoraConfig(\n",
        "    r=8,\n",
        "    lora_alpha=16,\n",
        "    lora_dropout=0.05,\n",
        "    task_type=\"CAUSAL_LM\",\n",
        "    target_modules=[\"q_proj\",\"k_proj\",\"v_proj\",\"o_proj\",\"gate_proj\",\"up_proj\",\"down_proj\"],\n",
        ")\n",
        "model = get_peft_model(model, lora_config)\n",
        "model.print_trainable_parameters()"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IvBFdKIWdy7r"
      },
      "outputs": [],
      "source": [
        "# OPTIONAL: free GPU memory without restarting the runtime.\n",
        "# Uncomment and run this if you are re-running this section (e.g. to retrain) and run out of GPU memory.\n",
        "# It deletes models/trainers loaded earlier, so run it BEFORE loading the model below, not after creating the Trainer.\n",
        "# import gc, torch\n",
        "# for name in (\"trainer\", \"model\", \"mdl\", \"peft_model\", \"merged\", \"optim\", \"scheduler\"):\n",
        "#     if name in globals(): del globals()[name]\n",
        "# gc.collect()\n",
        "# torch.cuda.empty_cache()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OxHZmJYgIOV_"
      },
      "outputs": [],
      "source": [
        "args = TrainingArguments(\n",
        "    output_dir=\"./gsm8ksft_1b_lora\",\n",
        "    num_train_epochs=2,\n",
        "    per_device_train_batch_size=4,\n",
        "    per_device_eval_batch_size=4,\n",
        "    gradient_accumulation_steps=4,\n",
        "    learning_rate=2e-4,\n",
        "    lr_scheduler_type=\"cosine\",\n",
        "    warmup_steps=0.03,\n",
        "    logging_steps=1,\n",
        "    eval_strategy=\"steps\",\n",
        "    eval_steps=25,\n",
        "    save_steps=250,\n",
        "    save_total_limit=2,\n",
        "    bf16=False,\n",
        "    fp16=True,\n",
        "    gradient_checkpointing=True,\n",
        "    gradient_checkpointing_kwargs={\"use_reentrant\": False},\n",
        "    optim=\"adamw_torch\",\n",
        "    report_to=\"none\",\n",
        "    remove_unused_columns=False,\n",
        "    train_sampling_strategy=\"group_by_length\",\n",
        ")\n",
        "\n",
        "#subsample\n",
        "val_tok_sample = val_tok.shuffle(seed=42).select(range(100))\n",
        "\n",
        "trainer = Trainer(\n",
        "    model=model,\n",
        "    args=args,\n",
        "    train_dataset=train_tok,\n",
        "    eval_dataset=val_tok_sample,\n",
        "    data_collator=collator,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "X5nwatVnXBy-"
      },
      "outputs": [],
      "source": [
        "trainer.train()\n",
        "trainer.save_model()\n",
        "model.push_to_hub(SFT_REPO)\n",
        "tok.push_to_hub(SFT_REPO)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Uw_KfodiFobq"
      },
      "outputs": [],
      "source": [
        "from peft import AutoPeftModelForCausalLM\n",
        "tok = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, use_fast=True)\n",
        "\n",
        "# load the trained adapter (it knows the base model from its config)\n",
        "peft_model = AutoPeftModelForCausalLM.from_pretrained(\n",
        "    SFT_REPO, torch_dtype=\"auto\", device_map=\"auto\"\n",
        ")\n",
        "\n",
        "# merge LoRA weights into the base weights and drop PEFT wrappers\n",
        "merged = peft_model.merge_and_unload()\n",
        "\n",
        "# save a standard HF model folder\n",
        "merged.save_pretrained(\"./gsm8k_1b_lora_merged\", safe_serialization=True)\n",
        "tok.save_pretrained(\"./gsm8k_1b_lora_merged\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mbmrQblICoa3"
      },
      "outputs": [],
      "source": [
        "accuracy, outs, records = evaluate_gsm8k(\"./gsm8k_1b_lora_merged\", gsm8k_test_sample[\"question\"], gsm8k_test_sample[\"numeric_answer\"], batch_size=16, prefix=PROMPT_GSM8K)\n",
        "print(f\"Accuracy: {accuracy}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PcqHve48m836"
      },
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Please record your accuracy here:\n",
        "\n",
        "\\<ACCURACY\\>\n",
        "\n",
        "And 5 examples here:\n",
        "\n",
        "\\<SAMPLES\\>\n",
        "\n",
        "Comparing to the base model, is the accuracy higher or lower? Why do you think that is?\n",
        "\n",
        "\\<YOUR ANSWER\\>\n",
        "\n",
        "Do you notice anything different about the model behavior?\n",
        "\n",
        "\\<3-5 sentence reflection\\>\n",
        "\n",
        "TODO STUDENT END"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Part 5: RL with Verifiable Rewards (REINFORCE)\n",
        "\n",
        "In this section, we will take our SFT model and train it further with on-policy reinforcement learning (RL)."
      ],
      "metadata": {
        "id": "D6u8wSig86Ux"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Q: What does on-policy mean? Why might someone want to do more on-policy RL after SFT? List out at least two reasons.\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "TODO STUDENT END"
      ],
      "metadata": {
        "id": "IYpg93fI9GbT"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Reward the model\n",
        "We need a way to score the model's responses. Fortunately, we already built the verifier: the parser from Part 3.\n",
        "\n",
        "Follow the notation in Part 4, $\\hat y \\sim p_\\theta(y \\mid x)$ is the model's whole sampled response, including the reasoning and the answer. The reward is\n",
        "$$r(x, \\hat y) = \\begin{cases} 1 & \\text{if } \\texttt{extract_answer}(\\hat y) \\text{ matches the gold number} \\\\ 0 & \\text{otherwise} \\end{cases}$$\n",
        "\n",
        "Our goal is the RL objective from lecture: maximize the expected reward, i.e. accuracy, on problems from the GSM8k dataset $D$:\n",
        "$$J(\\theta) = \\mathbb{E}_{x \\sim D,\\; \\hat y \\sim p_\\theta(y \\mid x)}\\big[r(x, \\hat y)\\big]$$"
      ],
      "metadata": {
        "id": "_okW1xTY87JI"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Q: The whole response contains many tokens, but the reward only supervises the final answer. What are the upsides and downsides of rewarding only the final answer?\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "TODO STUDENT END"
      ],
      "metadata": {
        "id": "yHG0oxsp9APc"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### REINFORCE: Making the reward differentiable\n",
        "\n",
        "To update the model parameters with gradient descent, we need an objective that is differentiable w.r.t. the model parameters. However, we aren't able to differentiate the expected reward $J(\\theta)$ w.r.t. our model parameters. From the perspective of the parameters, $R(\\tau)$ is a black box that outputs a scalar signal after the model generates a sequence of tokens.\n",
        "\n",
        "**BUT** we can take gradients through the probability of sampling the responses that lead to reward (with the assumption that the reward function stays fixed). The tool for this is the **log-derivative trick**, and the gradient estimate it gives is called **REINFORCE**."
      ],
      "metadata": {
        "id": "BGce9bdi91ay"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "TODO STUDENT START\n",
        "\n",
        "Derive the REINFORCE gradient. Note, you can still type Latex in the notebook by wrapping things in `$` or `$$`. You can also use `\\begin{align}...\\end{align}` for multi-line equations.\n",
        "\n",
        "(a) Prove the log-derivative trick: $\\nabla_\\theta\\, p_\\theta(\\hat y \\mid x) = p_\\theta(\\hat y \\mid x)\\, \\nabla_\\theta \\log p_\\theta(\\hat y \\mid x)$. (Hint: apply the chain rule to $\\log p_\\theta(\\hat y \\mid x)$.)\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "(b) Use it to show that\n",
        "$$\\nabla_\\theta\\, \\mathbb{E}_{\\hat y \\sim p_\\theta(y \\mid x)}\\big[r(x, \\hat y)\\big] = \\mathbb{E}_{\\hat y \\sim p_\\theta(y \\mid x)}\\big[r(x, \\hat y)\\, \\nabla_\\theta \\log p_\\theta(\\hat y \\mid x)\\big].$$\n",
        "(Hint: write the expectation as a sum over all possible responses $\\hat y$, and note that $r$ does not depend on $\\theta$.)\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "(c) Take a closer look at the expectation term on the right hand side in part (b). With our binary reward (1 for correct and 0 for incorrect), what does this update do to a response with reward 1? To one with reward 0? How does it relate to the SFT you did in Part 4?\n",
        "\n",
        "A: \\<YOUR ANSWER HERE\\>\n",
        "\n",
        "\n",
        "TODO STUDENT END"
      ],
      "metadata": {
        "id": "8lAg91HYFMY4"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### Subtracting a baseline\n",
        "Part (c) reveals a weakness of weighting each response by its raw reward. So when we train, we subtract a **baseline**.\n",
        "\n",
        "Each training step uses a batch of $B$ questions $x_1, \\dots, x_B$, with one sampled response per question, $\\hat y_i \\sim p_\\theta(y \\mid x_i)$ for $i = 1, \\dots, B$. The baseline is the average reward in the batch,\n",
        "$$b = \\frac{1}{B} \\sum_{j=1}^{B} r(x_j, \\hat y_j),$$\n",
        "and we weight each response $\\hat y_i$ by\n",
        "$$r(x_i, \\hat y_i) - b \\quad \\text{instead of} \\quad r(x_i, \\hat y_i), \\qquad i = 1, \\dots, B.$$\n",
        "\n",
        "This doesn't change the direction of the expected gradient, but it helps training be more stable. When a batch has both correct and incorrect answers, we want to nudge each response's probability up or down *relative to the batch average*, not just according to whether it is correct."
      ],
      "metadata": {
        "id": "Ju7HBnrQKQeG"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Implement the Trainer\n",
        "\n",
        "Now, you will implement the reward function and trainer (extends the Pytorch Trainer) for REINFORCE."
      ],
      "metadata": {
        "id": "WNVPuc9_K7UL"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KnNloP0laFAA"
      },
      "outputs": [],
      "source": [
        "def reward_numeric(pred_texts, gold_answers, abs_tol=Decimal(\"1e-9\"), rel_tol=Decimal(\"1e-9\")):\n",
        "    \"\"\"\n",
        "    Compute per-example numeric rewards for REINFORCE on GSM8K-style outputs. Returns a list of integer rewards corresponding to each GSM8k question, and average reward in the minibatch\n",
        "    \"\"\"\n",
        "    n = min(len(pred_texts), len(gold_answers))\n",
        "    if n == 0:\n",
        "        return [], 0.0\n",
        "\n",
        "    rewards = []\n",
        "    for gen, gold in zip(pred_texts[:n], gold_answers[:n]):\n",
        "        pred = extract_answer(gen)\n",
        "        gold_norm = normalize_num(gold)\n",
        "\n",
        "        if pred is None or gold_norm is None:\n",
        "            #TODO STUDENT START:\n",
        "\n",
        "            #TODO STUDENT END\n",
        "\n",
        "        if pred == gold_norm:\n",
        "            #TODO STUDENT START:\n",
        "\n",
        "            #TODO STUDENT END\n",
        "\n",
        "        diff = abs(pred - gold_norm)\n",
        "        denom = max(Decimal(1), abs(gold_norm))\n",
        "        if diff <= abs_tol or diff / denom <= rel_tol:\n",
        "            #TODO STUDENT START:\n",
        "\n",
        "            #TODO STUDENT END\n",
        "        else:\n",
        "            #TODO STUDENT START:\n",
        "\n",
        "            #TODO STUDENT END\n",
        "\n",
        "    #TODO STUDENT START:\n",
        "    baseline =\n",
        "    #TODO STUDENT END\n",
        "    return rewards, baseline\n"
      ]
    },
    {
      "metadata": {
        "id": "2jkhd7Gvbut4"
      },
      "cell_type": "code",
      "outputs": [],
      "execution_count": null,
      "source": [
        "#%%\n",
        "# Note: There are four tasks in the STUDENT START/END block.\n",
        "import torch\n",
        "from transformers import (\n",
        "    AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, BitsAndBytesConfig,\n",
        "    TrainerCallback,\n",
        ")\n",
        "import time\n",
        "import pandas as pd\n",
        "from IPython.display import display, HTML\n",
        "from transformers.trainer_callback import ProgressCallback, PrinterCallback\n",
        "\n",
        "\n",
        "def _fmt_time(seconds):\n",
        "    seconds = int(seconds)\n",
        "    h, rem = divmod(seconds, 3600)\n",
        "    m, s = divmod(rem, 60)\n",
        "    return f\"{h}:{m:02d}:{s:02d}\" if h else f\"{m:02d}:{s:02d}\"\n",
        "\n",
        "\n",
        "class RLTableCallback(TrainerCallback):\n",
        "    \"\"\"Live progress bar (elapsed / remaining time) plus a metrics table, one row per optimizer step.\"\"\"\n",
        "    COLUMNS = {\n",
        "        \"loss\": \"Loss\", \"policy_loss\": \"Policy Loss\", \"kl_loss\": \"KL\",\n",
        "        \"em_batch\": \"EM (batch)\", \"grad_norm\": \"Grad Norm\",\n",
        "        \"learning_rate\": \"LR\", \"eval_loss\": \"Eval Loss\",\n",
        "    }\n",
        "\n",
        "    def __init__(self):\n",
        "        self.rows = {}\n",
        "        self.handle = None\n",
        "        self.start = None\n",
        "        self.step = 0\n",
        "        self.max_steps = 0\n",
        "\n",
        "    def _bar_html(self):\n",
        "        elapsed = time.time() - self.start\n",
        "        if self.step > 0:\n",
        "            per_step = elapsed / self.step\n",
        "            timing = (f\"[{_fmt_time(elapsed)} < {_fmt_time(per_step * (self.max_steps - self.step))}, \"\n",
        "                      f\"{per_step:.1f} s/step]\")\n",
        "        else:\n",
        "            timing = f\"[{_fmt_time(elapsed)} < ?]\"\n",
        "        return (f\"<progress value='{self.step}' max='{self.max_steps}' style='width:300px; height:20px;'></progress>\"\n",
        "                f\" &nbsp;{self.step}/{self.max_steps} {timing}\")\n",
        "\n",
        "    def _render(self):\n",
        "        html = self._bar_html()\n",
        "        if self.rows:\n",
        "            df = pd.DataFrame(list(self.rows.values())).set_index(\"Step\")\n",
        "            styled = df.style.format(\n",
        "                {c: (\"{:.2e}\" if c == \"LR\" else \"{:.4f}\") for c in df.columns}, na_rep=\"\"\n",
        "            )\n",
        "            html += \"<br>\" + styled.to_html()\n",
        "        self.handle.update(HTML(html))\n",
        "\n",
        "    def on_train_begin(self, args, state, control, **kwargs):\n",
        "        self.rows, self.start, self.step, self.max_steps = {}, time.time(), 0, state.max_steps\n",
        "        self.handle = display(HTML(\"\"), display_id=True)\n",
        "        self._render()\n",
        "\n",
        "    def on_step_end(self, args, state, control, **kwargs):\n",
        "        self.step = state.global_step\n",
        "        self._render()\n",
        "\n",
        "    def on_log(self, args, state, control, logs=None, **kwargs):\n",
        "        if not logs or self.handle is None:\n",
        "            return\n",
        "        row = self.rows.setdefault(state.global_step, {\"Step\": state.global_step})\n",
        "        for key, name in self.COLUMNS.items():\n",
        "            if key in logs:\n",
        "                row[name] = logs[key]\n",
        "        self._render()\n",
        "\n",
        "\n",
        "class REINFORCETrainer(Trainer):\n",
        "    def __init__(self, *args, gen_kwargs=None, ref_model=None, kl_beta=0.0, **kwargs):\n",
        "        super().__init__(*args, **kwargs)\n",
        "        self.gen_kwargs = gen_kwargs or dict(\n",
        "            max_new_tokens=300,\n",
        "            do_sample=True, top_p=0.9, temperature=0.7,\n",
        "            pad_token_id=self.processing_class.pad_token_id,\n",
        "            eos_token_id=self.processing_class.eos_token_id,\n",
        "            return_dict_in_generate=True, output_scores=False,  # scores not needed now\n",
        "        )\n",
        "        self.ref_model = ref_model\n",
        "        self.kl_beta = kl_beta\n",
        "        self._rl_metrics = {}           # per-micro-batch values, averaged at each logging step\n",
        "        # Replace the default progress output (raw dict prints / notebook table) with our bar + table\n",
        "        self.remove_callback(ProgressCallback)\n",
        "        self.remove_callback(PrinterCallback)\n",
        "        try:\n",
        "            from transformers.utils.notebook import NotebookProgressCallback\n",
        "            self.remove_callback(NotebookProgressCallback)\n",
        "        except ImportError:\n",
        "            pass\n",
        "        self.add_callback(RLTableCallback())\n",
        "\n",
        "    def _record(self, **metrics):\n",
        "        if not self.model.training:     # don't mix evaluation batches into training metrics\n",
        "            return\n",
        "        for k, v in metrics.items():\n",
        "            self._rl_metrics.setdefault(k, []).append(v)\n",
        "\n",
        "    def log(self, logs, *args, **kwargs):\n",
        "        # Merge averaged RL metrics into the Trainer's regular per-step training log\n",
        "        if \"loss\" in logs and self._rl_metrics:\n",
        "            for k, vals in self._rl_metrics.items():\n",
        "                logs[k] = sum(vals) / len(vals)\n",
        "            self._rl_metrics = {}\n",
        "        super().log(logs, *args, **kwargs)\n",
        "\n",
        "    @torch.no_grad()\n",
        "    def _decode(self, seqs):\n",
        "        return self.processing_class.batch_decode(seqs, skip_special_tokens=True)\n",
        "\n",
        "    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):\n",
        "        # Inputs from collator: input_ids (prompt only), attention_mask, gold_answer (list[str])\n",
        "        input_ids = inputs[\"input_ids\"]\n",
        "        attention_mask = inputs[\"attention_mask\"]\n",
        "        B = input_ids.size(0)\n",
        "        eos_id = self.processing_class.eos_token_id\n",
        "        pad_id = self.processing_class.pad_token_id\n",
        "\n",
        "        # On-policy sampling\n",
        "        with torch.no_grad():\n",
        "            if not hasattr(self, \"_checked_pad\"):\n",
        "              right_zero = (attention_mask[:, -1] == 0).any().item()\n",
        "              assert not right_zero, \"Right padding slipped in\"\n",
        "              self._checked_pad = True\n",
        "\n",
        "            gen = model.generate(input_ids=input_ids,\n",
        "                                 attention_mask=attention_mask,\n",
        "                                 **self.gen_kwargs)\n",
        "            full_ids = gen.sequences                         # [B, T_full]\n",
        "            full_attn = (full_ids != pad_id).long()          # [B, T_full]\n",
        "            prompt_lens = attention_mask.sum(dim=1)          # [B]\n",
        "\n",
        "        T_full = full_ids.size(1)\n",
        "        # forward pass (with grad) over the whole sampled sequence\n",
        "        out = model(input_ids=full_ids[:, :-1], attention_mask=full_attn[:, :-1])\n",
        "        logits = out.logits.float()\n",
        "        # Sanitize the fp32 logits *before* log_softmax.\n",
        "        # This fixes the Inf from the unstable LoRA weights.\n",
        "        logits = torch.nan_to_num(\n",
        "            logits,\n",
        "            nan=0.0,\n",
        "            posinf=torch.finfo(torch.float32).max,\n",
        "            neginf=torch.finfo(torch.float32).min\n",
        "        )\n",
        "        logprobs = torch.log_softmax(logits, dim=-1)\n",
        "\n",
        "\n",
        "        ar = torch.arange(T_full, device=full_ids.device).unsqueeze(0).expand(B, -1)  # [B,T]\n",
        "\n",
        "        # ===== TODO STUDENT START =====\n",
        "        # TODO TASK 1: Build a mask of which positions to score for each sample.\n",
        "        # Requirements:\n",
        "        # - score only the generated positions (not the prompt)\n",
        "        # - stop at first EOS (included)\n",
        "        # - ignore padding\n",
        "        # Output shape: valid_mask: [B, T_full]\n",
        "        #\n",
        "        # Hints:\n",
        "        # - `ar` (defined above) holds the position index t for every row.\n",
        "        # - Prompts are LEFT-padded, so generation starts at the same column for every row. Which column?\n",
        "        # - To cut off after the first EOS, count how many EOS tokens appear before each position (torch.cumsum).\n",
        "        #\n",
        "        valid_mask =\n",
        "\n",
        "        logprob_sums = []\n",
        "        for i in range(B):\n",
        "            # TODO TASK 2: Get the positions to score for sample i: (a) the indices t where valid_mask[i] is True, (b) excluding t = 0.\n",
        "            # (a) get valid positions for this sample\n",
        "            pos =\n",
        "\n",
        "            # (b) skip position 0 (no prediction for t=0)\n",
        "            pos =\n",
        "            if pos.numel() == 0:    # In case there is nothing to score (e.g. the model emitted EOS immediately),\n",
        "                safe_zero = (model.get_input_embeddings().weight[0, 0] * 0.0).to(dtype=logits.dtype)\n",
        "                logprob_sums.append(safe_zero)\n",
        "                continue\n",
        "            # gather next-token logprobs for the actually sampled tokens\n",
        "            tok_ids = full_ids[i, pos]                                                # [Ti]\n",
        "            step_logits = logprobs[i, pos - 1, :]                                     # [Ti, V]\n",
        "            step_logps = step_logits.gather(-1, tok_ids.view(-1, 1)).squeeze(-1)      # [Ti]\n",
        "            step_logps = torch.where(\n",
        "                torch.isfinite(step_logps),\n",
        "                step_logps,\n",
        "                torch.zeros_like(step_logps)\n",
        "            )\n",
        "            step_logps = step_logps.clamp(min=-20.0, max=0.0)\n",
        "\n",
        "            Ti = pos.numel()\n",
        "\n",
        "            # TODO TASK 3: Sum the logprobs for sample i over the valid positions and add the result to logprob_sums.\n",
        "\n",
        "\n",
        "        logprob_sums = torch.stack(logprob_sums, dim=0)                                # [B]\n",
        "\n",
        "        assert logprob_sums.requires_grad, \"logprob_sums lost grad (masking/shift produced all-empty rows)\"\n",
        "\n",
        "        # Rewards + batch baseline\n",
        "        with torch.no_grad():\n",
        "            texts = self._decode(full_ids)\n",
        "            rewards_list, b = reward_numeric(texts, inputs[\"gold_answer\"])\n",
        "            rewards  = torch.tensor(rewards_list, dtype=logprob_sums.dtype, device=logprob_sums.device)  # [B]\n",
        "            baseline = torch.tensor(b, dtype=logprob_sums.dtype, device=logprob_sums.device)\n",
        "\n",
        "        em_batch = rewards.float().mean().item()\n",
        "\n",
        "        # TODO TASK 4: Compute the advantage, normalize it, and compute the REINFORCE loss.\n",
        "        # 1. advantages = rewards - baseline\n",
        "        # 2. optional: normalize to unit variance\n",
        "        # 3. use advantage to weight logprob_sums in the REINFORCE loss\n",
        "\n",
        "        advantages =\n",
        "        std = advantages.std()\n",
        "        if torch.isfinite(std) and std > 0:\n",
        "            advantages =\n",
        "        loss =\n",
        "\n",
        "        # ===== TODO STUDENT END =====\n",
        "        # KL regularization with a frozen ref model could be added here.\n",
        "        kl_loss = torch.tensor(0.0, device=loss.device)\n",
        "        if self.ref_model is not None and self.kl_beta > 0:\n",
        "            with torch.no_grad():\n",
        "                # Third forward pass (no grad) with the REFERENCE model\n",
        "                ref_out = self.ref_model(input_ids=full_ids[:, :-1], attention_mask=full_attn[:, :-1])\n",
        "                ref_logprobs = torch.log_softmax(ref_out.logits.float(), dim=-1)\n",
        "\n",
        "            # Mask for generated tokens (shifted)\n",
        "            mask = valid_mask[:, 1:].contiguous()\n",
        "            mask_float = mask.float()\n",
        "\n",
        "            target_ids = full_ids[:, 1:].unsqueeze(-1)  # [B, T_full-1, 1]\n",
        "\n",
        "            # policy logp\n",
        "            policy_logp = torch.gather(logprobs, -1, target_ids).squeeze(-1)  # [B, T-1]\n",
        "            # ref logp\n",
        "            ref_logp = torch.gather(ref_logprobs, -1, target_ids).squeeze(-1)  # [B, T-1]\n",
        "\n",
        "            # clamp both to avoid -inf / inf\n",
        "            policy_logp = policy_logp.clamp(min=-20.0, max=0.0)\n",
        "            ref_logp    = ref_logp.clamp(min=-20.0, max=0.0)\n",
        "\n",
        "            # KL per token\n",
        "            kl_per_token = (policy_logp - ref_logp) * mask_float\n",
        "\n",
        "            # sanitize per-token KL\n",
        "            kl_per_token = torch.where(torch.isfinite(kl_per_token),\n",
        "                                      kl_per_token,\n",
        "                                      torch.zeros_like(kl_per_token))\n",
        "\n",
        "\n",
        "            # Average KL *per sequence*\n",
        "            kl_per_seq_sum = kl_per_token.sum(dim=1)\n",
        "            valid_tokens_per_seq = mask_float.sum(dim=1).clamp(min=1)\n",
        "            kl_per_seq = kl_per_seq_sum / valid_tokens_per_seq\n",
        "\n",
        "            # Average KL *over the batch*\n",
        "            kl_loss = kl_per_seq.mean()\n",
        "\n",
        "        # Store component values for logging before combining\n",
        "        policy_loss_item = loss.item()\n",
        "        kl_loss_item = kl_loss.item()\n",
        "        if not torch.isfinite(kl_loss):\n",
        "            kl_loss = torch.tensor(0.0, device=loss.device)\n",
        "        # Combine policy loss and KL regularization\n",
        "        loss = loss + self.kl_beta * kl_loss\n",
        "\n",
        "        self._record(em_batch=em_batch, policy_loss=policy_loss_item, kl_loss=kl_loss_item)\n",
        "\n",
        "        outputs = {\n",
        "            \"loss\": loss,\n",
        "            \"policy_loss\": policy_loss_item,\n",
        "            \"kl_loss\": kl_loss_item\n",
        "        }\n",
        "        return (loss, outputs) if return_outputs else loss"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AK65nKUHk34b"
      },
      "source": [
        "## Start Training!\n",
        "\n",
        "Time to train! This step will take much longer than the SFT (and you very well may not get much improvement).\n",
        "\n",
        "Think about how much work is required to get a signal (compared to SFT) and how dense that signal is (compared to SFT)."
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Here are some codes for preprocessing the GSM8K dataset (again just in case)."
      ],
      "metadata": {
        "id": "gD1fC-iN-W94"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "XfpYV85ueAfy"
      },
      "outputs": [],
      "source": [
        "class PromptOnlyCollator:\n",
        "    def __init__(self, tokenizer, pad_to_multiple_of=8):\n",
        "        self.tok = tokenizer\n",
        "        self.pad_to_multiple_of = pad_to_multiple_of\n",
        "    def __call__(self, features):\n",
        "        batch = self.tok.pad(\n",
        "            {\"input_ids\": [f[\"input_ids\"] for f in features]},\n",
        "            padding=True, return_tensors=\"pt\",\n",
        "            pad_to_multiple_of=self.pad_to_multiple_of\n",
        "        )\n",
        "        batch[\"gold_answer\"] = [f[\"gold_answer\"] for f in features]\n",
        "        return batch"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "GGEfrFM1hQ5L"
      },
      "outputs": [],
      "source": [
        "gsm8k_train = load_dataset(\"openai/gsm8k\", 'main', split = \"train\")\n",
        "gsm8k_test = load_dataset(\"openai/gsm8k\",'main', split = \"test\")\n",
        "\n",
        "gsm8k_train = gsm8k_train.map(preprocess_gsm8k, remove_columns=gsm8k_test.column_names)\n",
        "gsm8k_test = gsm8k_test.map(preprocess_gsm8k, remove_columns=gsm8k_test.column_names)\n",
        "\n",
        "gsm8k_test_sample = gsm8k_test.select(range(200))\n",
        "\n",
        "\n",
        "tok = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, use_fast=True)\n",
        "tok.padding_side = \"left\"\n",
        "if tok.pad_token is None:\n",
        "    tok.pad_token = tok.eos_token\n",
        "import os\n",
        "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"true\"\n",
        "\n",
        "tok.truncation_side = \"left\"\n",
        "\n",
        "MAX_LEN = 400\n",
        "BUDGET = MAX_LEN - 1\n",
        "\n",
        "SYS_IDS = [tok.bos_token_id] + tok(PROMPT_GSM8K, add_special_tokens=False)[\"input_ids\"]  # BOS first, as in SFT and evaluation\n",
        "\n",
        "train_tok_rl = gsm8k_train.map(\n",
        "    tokenize_batch,\n",
        "    batched=True,\n",
        "    batch_size=1024,\n",
        "    num_proc=2,\n",
        "    remove_columns=gsm8k_train.column_names,\n",
        "    writer_batch_size=1024,\n",
        "    desc=\"Tokenizing train set\",\n",
        "    fn_kwargs={\"include_answer\": False}\n",
        ")\n",
        "\n",
        "val_tok_rl = gsm8k_test.map(\n",
        "    tokenize_batch,\n",
        "    batched=True,\n",
        "    batch_size=1024,\n",
        "    num_proc=2,\n",
        "    remove_columns=gsm8k_test.column_names,\n",
        "    writer_batch_size=1024,\n",
        "    desc=\"Tokenizing val set\",\n",
        "    fn_kwargs={\"include_answer\": False}\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# OPTIONAL: free GPU memory without restarting the runtime.\n",
        "# Uncomment and run this if you are re-running this section (e.g. to retrain) and run out of GPU memory.\n",
        "# It deletes models/trainers loaded earlier, so run it BEFORE loading the model below, not after creating the Trainer.\n",
        "# import gc, torch\n",
        "# for name in (\"trainer\", \"model\", \"mdl\", \"peft_model\", \"merged\", \"optim\", \"scheduler\"):\n",
        "#     if name in globals(): del globals()[name]\n",
        "# gc.collect()\n",
        "# torch.cuda.empty_cache()"
      ],
      "metadata": {
        "id": "7BgVK9ssrV5I"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Nfi-MgdQvHJa"
      },
      "outputs": [],
      "source": [
        "# Initialize the model and start training\n",
        "import torch\n",
        "import os, logging, warnings\n",
        "from transformers import (\n",
        "    AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments, BitsAndBytesConfig\n",
        ")\n",
        "from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training\n",
        "from transformers.utils import logging as hf_logging\n",
        "\n",
        "hf_logging.set_verbosity_error()\n",
        "hf_logging.enable_progress_bar()\n",
        "\n",
        "tok = AutoTokenizer.from_pretrained(\"./gsm8k_1b_lora_merged\", use_fast=True)\n",
        "tok.pad_token = tok.eos_token\n",
        "tok.padding_side = \"left\"\n",
        "rl_collator = PromptOnlyCollator(tok)\n",
        "\n",
        "model = AutoModelForCausalLM.from_pretrained(\n",
        "    \"./gsm8k_1b_lora_merged\",\n",
        "    device_map=\"auto\",\n",
        "    torch_dtype=torch.float16,\n",
        "    attn_implementation=\"sdpa\",\n",
        ")\n",
        "model.generation_config.return_dict_in_generate = True\n",
        "model.generation_config.output_scores = False\n",
        "model.config.use_cache = False\n",
        "\n",
        "# LoRA config\n",
        "lora_config = LoraConfig(\n",
        "    r=16,                      # 8–16 common; raise if updates feel too weak\n",
        "    lora_alpha=32,\n",
        "    lora_dropout=0.05,\n",
        "    bias=\"none\",\n",
        "    task_type=\"CAUSAL_LM\",\n",
        "    target_modules=[\n",
        "        \"q_proj\",\"k_proj\",\"v_proj\",\"o_proj\",\n",
        "        \"gate_proj\",\"up_proj\",\"down_proj\",\n",
        "    ],\n",
        ")\n",
        "model = get_peft_model(model, lora_config)\n",
        "model.print_trainable_parameters()\n",
        "\n",
        "ref_model = AutoModelForCausalLM.from_pretrained(\n",
        "    \"./gsm8k_1b_lora_merged\",\n",
        "    device_map=\"auto\",\n",
        "    torch_dtype=torch.float16,\n",
        "    attn_implementation=\"sdpa\",\n",
        ")\n",
        "ref_model.eval()\n",
        "ref_model.requires_grad_(False)\n",
        "\n",
        "\n",
        "args = TrainingArguments(\n",
        "    output_dir=\"./gsm8k_rl_lora\",\n",
        "    per_device_train_batch_size=4,\n",
        "    per_device_eval_batch_size=4,\n",
        "    gradient_accumulation_steps=16,\n",
        "    max_grad_norm=1.0,\n",
        "    learning_rate=1e-6,\n",
        "    weight_decay=0.0,\n",
        "    num_train_epochs=0.1,\n",
        "    logging_steps=1,\n",
        "    eval_strategy=\"steps\",\n",
        "    eval_steps=100,\n",
        "    save_steps=500,\n",
        "    save_total_limit=2,\n",
        "    optim=\"adamw_torch\",\n",
        "    fp16=True,\n",
        "    gradient_checkpointing=False,\n",
        "    report_to=\"none\",\n",
        "    remove_unused_columns=False,\n",
        ")\n",
        "\n",
        "\n",
        "trainer = REINFORCETrainer(\n",
        "    model=model,\n",
        "    args=args,\n",
        "    train_dataset=train_tok_rl,\n",
        "    eval_dataset=val_tok_rl.select(range(64)),\n",
        "    data_collator=rl_collator,\n",
        "    processing_class=tok,\n",
        "    gen_kwargs=dict(max_new_tokens=300, min_new_tokens=1, do_sample=True, top_p=0.9),\n",
        "    ref_model=ref_model,\n",
        "    kl_beta=0.1,\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mvYbN6HXCBsP"
      },
      "outputs": [],
      "source": [
        "trainer.train()\n",
        "trainer.save_model()\n",
        "model.push_to_hub(RL_REPO)\n",
        "tok.push_to_hub(RL_REPO)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bzyGQdxEP7mk"
      },
      "outputs": [],
      "source": [
        "from peft import AutoPeftModelForCausalLM\n",
        "tok = AutoTokenizer.from_pretrained(BASE_MODEL_NAME, use_fast=True)\n",
        "\n",
        "# load the trained adapter (it knows the base model from its config)\n",
        "peft_model = AutoPeftModelForCausalLM.from_pretrained(\n",
        "    RL_REPO, torch_dtype=\"auto\", device_map=\"auto\"\n",
        ")\n",
        "\n",
        "# merge LoRA weights into the base weights and drop PEFT wrappers\n",
        "merged = peft_model.merge_and_unload()\n",
        "\n",
        "# save a standard HF model folder\n",
        "merged.save_pretrained(\"./gsm8krl_1b_lora1_merged\", safe_serialization=True)\n",
        "tok.save_pretrained(\"./gsm8krl_1b_lora1_merged\")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c3lDi4CQQFYK"
      },
      "outputs": [],
      "source": [
        "accuracy, outs, generated_answers = evaluate_gsm8k(\"./gsm8krl_1b_lora1_merged\", gsm8k_test_sample[\"question\"], gsm8k_test_sample[\"numeric_answer\"], batch_size=16, prefix=PROMPT_GSM8K)\n",
        "print(f\"Accuracy: {accuracy}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "g6eQUmNCncc8"
      },
      "source": [
        "Please record your accuracy here:\n",
        "\n",
        "\\<ACCURACY\\>\n",
        "\n",
        "And 5 examples here:\n",
        "\n",
        "\\<SAMPLES\\>\n",
        "\n",
        "Do you notice anything different about the model behavior? What would you do to further improve the model?\n",
        "\n",
        "\\<3-5 sentence reflection\\>"
      ]
    },
    {
      "metadata": {
        "id": "Qe0m9NV8h69B"
      },
      "cell_type": "markdown",
      "source": [
        "# Bonus Question\n",
        "<!-- <p align=\"center\">\n",
        "  <img src=\"https://pixeljoint.com/files/icons/full/charmander_evos.png\" width=\"450\">\n",
        "</p>\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://completecollector.co.uk/hubfs/Screenshot%202024-04-07%20at%2022.53.50.png\" width=\"450\">\n",
        "</p>\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://static0.anpoimages.com/wordpress/wp-content/uploads/2022/11/eeveelutionHero.jpg?w=1600&h=900&fit=crop\" width=\"450\">\n",
        "</p> -->\n",
        "\n",
        "<p align=\"center\">\n",
        "  <img src=\"https://www.esports.net/wp-content/uploads/2023/11/eveelutions.jpg\" width=\"650\">\n",
        "</p>\n",
        "\n",
        "Q: What could be the reason for including this image of the Eeveelutions in this assignment?\n",
        "\n",
        "A: \\<YOUR ANSWER\\>"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "# This assignment is created by Daniel Zhang and Lorena Yan."
      ],
      "metadata": {
        "id": "7Iqd3CShosf8"
      },
      "execution_count": null,
      "outputs": []
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "gpuType": "L4",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}