{ "cells": [ { "cell_type": "markdown", "id": "c43887b2", "metadata": {}, "source": [ "# Stage 2 · Reward Model (RM)\n", "**End-to-end RLHF, notebook 2 of 4**\n", "\n", "**Goal:** learn a scalar score $r_\\phi(x, y)$ that agrees with human preferences.\n", "People can't easily write the perfect answer, but they can reliably say which of two is better.\n", "\n", "**Bradley–Terry model and loss:**\n", "$$P(y^+ \\succ y^- \\mid x) = \\sigma\\big(r(x,y^+) - r(x,y^-)\\big) \\qquad \\mathcal{L}(\\phi) = -\\log\\sigma\\big(r^+ - r^-\\big)$$\n", "\n", "| | |\n", "|---|---|\n", "| Model in | `outputs/sft` (from notebook 1) |\n", "| Data | `HuggingFaceH4/ultrafeedback_binarized` · split `train_prefs` (columns `chosen`, `rejected`) |\n", "| Model out | `outputs/rm` (used by notebooks 3, 4) |" ] }, { "cell_type": "markdown", "id": "5c64de10", "metadata": {}, "source": [ "## 0 · Setup\n", "Select the GPU, install pinned libraries, then load the shared config." ] }, { "cell_type": "code", "execution_count": 1, "id": "01f1c032", "metadata": {}, "outputs": [], "source": [ "# ---- Pick the GPU FIRST: this must run before torch is imported (restart the kernel if it already was) ----\n", "import os\n", "os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # number GPUs the same way nvidia-smi does\n", "os.environ[\"CUDA_VISIBLE_DEVICES\"] = os.getenv(\"GPU_ID\", \"3\") # \"3\" = the 4th GPU in nvidia-smi\n", "# Inside this notebook that GPU is now visible as cuda:0." ] }, { "cell_type": "code", "execution_count": 2, "id": "e5cd3f2d", "metadata": {}, "outputs": [], "source": [ "# Pinned versions: PPO lives in trl.experimental.ppo and was REMOVED in TRL 1.13;\n", "# TRL 1.12's PPO trainer cannot save on transformers >= 5.19.\n", "# %pip install -q \"trl>=1.10,<1.13\" \"transformers>=5.0,<5.19\" \"accelerate>=1.4.0\" \"datasets>=4.7.0\" \"peft>=0.17\"" ] }, { "cell_type": "code", "execution_count": 3, "id": "34ed5770", "metadata": {}, "outputs": [], "source": [ "# OPTIONAL (Google Colab): keep checkpoints between notebooks/sessions on Google Drive.\n", "# Uncomment both lines, then every notebook reads/writes the same folder.\n", "# from google.colab import drive; drive.mount(\"/content/drive\")\n", "# import os; os.environ[\"OUTPUT_ROOT\"] = \"/content/drive/MyDrive/rlhf_outputs\"" ] }, { "cell_type": "code", "execution_count": 4, "id": "860d6a22", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GPU=NVIDIA RTX 6000 Ada Generation | base=Qwen/Qwen3-0.6B-Base | data=HuggingFaceH4/ultrafeedback_binarized | device=cuda | bf16=True | outputs -> outputs\n" ] } ], "source": [ "# ===================== Shared configuration (identical in all 4 notebooks) =====================\n", "import os, math, json\n", "import torch\n", "from datasets import load_dataset, load_from_disk\n", "from transformers import AutoTokenizer\n", "\n", "def _env(name, default, cast=str):\n", " v = os.getenv(name)\n", " return default if v is None else cast(v)\n", "\n", "# --- Models -------------------------------------------------------------------------------\n", "BASE_MODEL = _env(\"BASE_MODEL\", \"Qwen/Qwen3-0.6B-Base\") # base (not instruct) decoder-only LM\n", "GOLD_RM = _env(\"GOLD_RM\", \"Skywork/Skywork-Reward-V2-Qwen3-0.6B\") # independent judge, EVAL ONLY (\"\" = skip)\n", "\n", "# --- Data ---------------------------------------------------------------------------------\n", "DATASET = _env(\"DATASET\", \"HuggingFaceH4/ultrafeedback_binarized\")\n", "N_SFT, N_RM, N_PPO = _env(\"N_SFT\", 20_000, int), _env(\"N_RM\", 20_000, int), _env(\"N_PPO\", 10_000, int)\n", "N_EVAL, N_GEN = _env(\"N_EVAL\", 500, int), _env(\"N_GEN\", 200, int)\n", "MAX_PROMPT_TOKENS = _env(\"MAX_PROMPT_TOKENS\", 512, int)\n", "\n", "# --- Training size knobs (lower BATCH / raise GRAD_ACC if you run out of memory) ------------\n", "BATCH, GRAD_ACC = _env(\"BATCH\", 8, int), _env(\"GRAD_ACC\", 4, int)\n", "MAX_STEPS = _env(\"MAX_STEPS\", -1, int) # -1 = full epoch\n", "USE_LORA = _env(\"USE_LORA\", \"0\") == \"1\" # PPO only: saves memory on 24 GB GPUs\n", "\n", "# --- Paths --------------------------------------------------------------------------------\n", "OUT = _env(\"OUTPUT_ROOT\", \"outputs\")\n", "SFT_DIR, RM_DIR, PPO_DIR, EVAL_DIR = f\"{OUT}/sft\", f\"{OUT}/rm\", f\"{OUT}/ppo\", f\"{OUT}/eval\"\n", "\n", "# --- Special tokens & precision -----------------------------------------------------------\n", "EOS_TOKEN = \"<|im_end|>\" # end of an assistant turn: generation stops here\n", "PAD_TOKEN = \"<|endoftext|>\" # must differ from EOS (PPO masks every pad token)\n", "USE_BF16 = torch.cuda.is_available() and torch.cuda.is_bf16_supported()\n", "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "\n", "# ChatML template. {% generation %} marks assistant text -> assistant-only loss mask.\n", "CHATML_TEMPLATE = r\"\"\"{%- for message in messages %}\n", "{%- if message['role'] == 'assistant' %}\n", "{{- '<|im_start|>assistant\\n' }}{% generation %}{{- message['content'] + '<|im_end|>' }}{% endgeneration %}{{- '\\n' }}\n", "{%- else %}\n", "{{- '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>\\n' }}\n", "{%- endif %}\n", "{%- endfor %}\n", "{%- if add_generation_prompt %}\n", "{{- '<|im_start|>assistant\\n' }}\n", "{%- endif %}\"\"\"\n", "\n", "def load_split(split, n=None, start=0):\n", " \"\"\"A dataset split from the Hub (or from disk if DATASET is a local folder).\"\"\"\n", " ds = load_from_disk(DATASET)[split] if os.path.isdir(DATASET) else load_dataset(DATASET, split=split)\n", " end = len(ds) if n is None else min(len(ds), start + n)\n", " return ds.select(range(start, end))\n", "\n", "def load_tokenizer(path, padding_side=\"right\"):\n", " \"\"\"Configure the tokenizer IDENTICALLY in every stage.\"\"\"\n", " tok = AutoTokenizer.from_pretrained(path, padding_side=padding_side)\n", " tok.chat_template = CHATML_TEMPLATE\n", " tok.eos_token, tok.pad_token = EOS_TOKEN, PAD_TOKEN\n", " assert tok.pad_token_id != tok.eos_token_id, \"pad and eos must be different tokens\"\n", " return tok\n", "\n", "def precision_kwargs():\n", " return {\"bf16\": USE_BF16, \"fp16\": False, \"use_cpu\": not torch.cuda.is_available()}\n", "\n", "@torch.no_grad()\n", "def chat(model, tok, prompt, max_new_tokens=200):\n", " \"\"\"Greedy single-turn reply, used for quick qualitative checks.\"\"\"\n", " text = tok.apply_chat_template([{\"role\": \"user\", \"content\": prompt}], add_generation_prompt=True, tokenize=False)\n", " batch = tok(text, return_tensors=\"pt\", add_special_tokens=False).to(model.device)\n", " out = model.generate(**batch, max_new_tokens=max_new_tokens, do_sample=False,\n", " eos_token_id=tok.eos_token_id, pad_token_id=tok.pad_token_id)\n", " return tok.decode(out[0, batch[\"input_ids\"].shape[1]:], skip_special_tokens=True)\n", "\n", "print(f\"GPU={torch.cuda.get_device_name(0) if torch.cuda.is_available() else None} | base={BASE_MODEL} | data={DATASET} | device={DEVICE} | bf16={USE_BF16} | outputs -> {OUT}\")" ] }, { "cell_type": "markdown", "id": "ba5a0819", "metadata": {}, "source": [ "## 2.1 · Same tokenizer as the policy\n", "Loaded from `SFT_DIR`, not the base model. Non-negotiable: in PPO the RM receives the policy's token ids directly." ] }, { "cell_type": "code", "execution_count": 5, "id": "f9346889", "metadata": {}, "outputs": [], "source": [ "tokenizer = load_tokenizer(SFT_DIR, padding_side=\"right\")" ] }, { "cell_type": "markdown", "id": "6ffb02b0", "metadata": {}, "source": [ "## 2.2 · The model: same body, new head\n", "`AutoModelForSequenceClassification(num_labels=1)` keeps the SFT transformer body, **drops the LM head** (hidden → vocab) and adds a fresh **score head** (hidden → 1).\n", "Expect a warning that `score.weight` is MISSING / newly initialised — that's the head we're about to train.\n", "\n", "The score is read at the **last non-pad token** (with causal attention, the only position that has seen the whole response), so the model must know the pad id." ] }, { "cell_type": "code", "execution_count": 6, "id": "ad7dcb1a", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "810b5b626eaa498a950c04374e6d13d4", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Loading weights: 0%| | 0/310 [00:00, ?it/s]" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stderr", "output_type": "stream", "text": [ "[transformers] \u001b[1mQwen3ForSequenceClassification LOAD REPORT\u001b[0m from: outputs/sft\n", "Key | Status | \n", "-------------+---------+-\n", "score.weight | MISSING | \n", "\n", "Notes:\n", "- MISSING:\tthose params were newly initialized because missing from the checkpoint. Consider training on your downstream task.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linear(in_features=1024, out_features=1, bias=False)\n" ] } ], "source": [ "from transformers import AutoModelForSequenceClassification\n", "model = AutoModelForSequenceClassification.from_pretrained(SFT_DIR, num_labels=1, dtype=torch.float32)\n", "model.config.pad_token_id = tokenizer.pad_token_id\n", "print(model.score) # the new linear head: hidden_size -> 1" ] }, { "cell_type": "markdown", "id": "27996e49", "metadata": {}, "source": [ "## 2.3 · Data: preference pairs\n", "Each row has a `chosen` and a `rejected` conversation sharing the same user prompt (an *implicit* prompt).\n", "We drop the string `prompt` column so it isn't mistaken for an explicit-prompt dataset." ] }, { "cell_type": "code", "execution_count": 7, "id": "4cce949e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "PROMPT : how can i develop a habit of drawing daily\n", "\n", "CHOSEN : Developing a daily habit of drawing can be challenging but with consistent practice and a few tips, it can become an enjoyable and rewarding part of your daily routine. Here are some strategies to help you develop the habit of drawing daily:\n", "\n", "1. Set a specific time: Allocate a specific time of the d\n", "\n", "REJECTED: As an AI language model, I cannot personally develop habits for you. But, here are some tips for developing a habit of drawing daily:\n", "\n", "1. Start small: Start with simple drawings or doodles and gradually increase the complexity of your drawings.\n", "\n", "2. Set a schedule: Set a specific time every day to dr\n" ] } ], "source": [ "train_ds = load_split(\"train_prefs\", N_RM).select_columns([\"chosen\", \"rejected\"])\n", "eval_ds = load_split(\"test_prefs\", N_EVAL).select_columns([\"chosen\", \"rejected\"])\n", "ex = train_ds[0]\n", "print(\"PROMPT :\", ex[\"chosen\"][0][\"content\"][:300])\n", "print(\"\\nCHOSEN :\", ex[\"chosen\"][-1][\"content\"][:300])\n", "print(\"\\nREJECTED:\", ex[\"rejected\"][-1][\"content\"][:300])" ] }, { "cell_type": "markdown", "id": "a5c0267e", "metadata": {}, "source": [ "## 2.4 · Hyperparameters\n", "\n", "| Setting | Value | Why |\n", "|---|---|---|\n", "| `learning_rate` | 1e-5 | full fine-tune (TRL's 1e-4 default suits LoRA) |\n", "| `num_train_epochs` | 1 | reward models overfit fast |\n", "| `max_length` | 1024 | pairs longer than this are dropped, not truncated |\n", "| `center_rewards_coefficient` | 0.01 | BT loss ignores a constant offset; keep mean reward near 0 |\n", "| `disable_dropout` | True | same input → same score |" ] }, { "cell_type": "code", "execution_count": 8, "id": "40dc6167", "metadata": {}, "outputs": [], "source": [ "from trl import RewardConfig, RewardTrainer\n", "\n", "args = RewardConfig(\n", " output_dir=RM_DIR,\n", " max_length=1024,\n", " num_train_epochs=1, max_steps=MAX_STEPS,\n", " per_device_train_batch_size=BATCH, gradient_accumulation_steps=GRAD_ACC,\n", " learning_rate=1e-5, lr_scheduler_type=\"cosine\", warmup_steps=0.03,\n", " center_rewards_coefficient=0.01,\n", " disable_dropout=True,\n", " gradient_checkpointing=True,\n", " logging_steps=10, eval_strategy=\"steps\", eval_steps=200,\n", " save_strategy=\"no\", report_to=\"none\",\n", " **precision_kwargs(),\n", ")\n", "\n", "trainer = RewardTrainer(\n", " model=model, args=args,\n", " train_dataset=train_ds, eval_dataset=eval_ds,\n", " processing_class=tokenizer,\n", " # peft_config=LoraConfig(..., modules_to_save=[\"score\"]), # LoRA: the new head must be trainable\n", ")" ] }, { "cell_type": "markdown", "id": "7279dfda", "metadata": {}, "source": [ "## 2.5 · Train\n", "At the start the loss should be ≈ **0.69** (= log 2, the model is guessing). Watch `accuracy` (share of pairs with r⁺ > r⁻) and `margin` (mean r⁺ − r⁻)." ] }, { "cell_type": "code", "execution_count": 9, "id": "b0967628", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
| Step | \n", "Training Loss | \n", "Validation Loss | \n", "Num Tokens | \n", "Min Reward | \n", "Mean Reward | \n", "Max Reward | \n", "Accuracy | \n", "Margin | \n", "
|---|---|---|---|---|---|---|---|---|
| 200 | \n", "0.523871 | \n", "0.571909 | \n", "4861357.000000 | \n", "-1.826628 | \n", "-0.265804 | \n", "1.407031 | \n", "0.704167 | \n", "0.607562 | \n", "
| 400 | \n", "0.508453 | \n", "0.554971 | \n", "9735577.000000 | \n", "-1.854883 | \n", "-0.044411 | \n", "1.586523 | \n", "0.712500 | \n", "0.693549 | \n", "
| 590 | \n", "0.535345 | \n", "0.555116 | \n", "14300506.000000 | \n", "-2.010905 | \n", "-0.084100 | \n", "1.566081 | \n", "0.704167 | \n", "0.737808 | \n", "
"
],
"text/plain": [
" "
],
"text/plain": [
"\n",
" \n",
"
\n",
" \n",
" \n",
" \n",
" Training Loss \n",
" Validation Loss \n",
" Step \n",
" Num Tokens \n",
" Min Reward \n",
" Mean Reward \n",
" Max Reward \n",
" Accuracy \n",
" Margin \n",
" \n",
" \n",
" \n",
"0.535345 \n",
" 0.555116 \n",
" 590 \n",
" 14300506.000000 \n",
" -2.010905 \n",
" -0.084100 \n",
" 1.566081 \n",
" 0.704167 \n",
" 0.737808 \n",
"