File size: 21,324 Bytes
85676f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
{
 "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",
       "    <div>\n",
       "      \n",
       "      <progress value='590' max='590' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [590/590 48:17, Epoch 1/1]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Step</th>\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "      <th>Num Tokens</th>\n",
       "      <th>Min Reward</th>\n",
       "      <th>Mean Reward</th>\n",
       "      <th>Max Reward</th>\n",
       "      <th>Accuracy</th>\n",
       "      <th>Margin</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>200</td>\n",
       "      <td>0.523871</td>\n",
       "      <td>0.571909</td>\n",
       "      <td>4861357.000000</td>\n",
       "      <td>-1.826628</td>\n",
       "      <td>-0.265804</td>\n",
       "      <td>1.407031</td>\n",
       "      <td>0.704167</td>\n",
       "      <td>0.607562</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>400</td>\n",
       "      <td>0.508453</td>\n",
       "      <td>0.554971</td>\n",
       "      <td>9735577.000000</td>\n",
       "      <td>-1.854883</td>\n",
       "      <td>-0.044411</td>\n",
       "      <td>1.586523</td>\n",
       "      <td>0.712500</td>\n",
       "      <td>0.693549</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>590</td>\n",
       "      <td>0.535345</td>\n",
       "      <td>0.555116</td>\n",
       "      <td>14300506.000000</td>\n",
       "      <td>-2.010905</td>\n",
       "      <td>-0.084100</td>\n",
       "      <td>1.566081</td>\n",
       "      <td>0.704167</td>\n",
       "      <td>0.737808</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ccd14fc18b144088a376289bbae2e74f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Writing model shards:   0%|          | 0/1 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "('outputs/rm/tokenizer_config.json',\n",
       " 'outputs/rm/chat_template.jinja',\n",
       " 'outputs/rm/tokenizer.json')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "trainer.train()\n",
    "trainer.save_model(RM_DIR)\n",
    "tokenizer.save_pretrained(RM_DIR)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f434b71",
   "metadata": {},
   "source": [
    "## 2.6 · Held-out accuracy\n",
    "50% is a coin flip. Notebook 4 also checks whether the RM beats a trivial \"longer answer wins\" baseline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "a0d36372",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='60' max='60' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [60/60 00:15]\n",
       "    </div>\n",
       "    "
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "      <th>Step</th>\n",
       "      <th>Num Tokens</th>\n",
       "      <th>Min Reward</th>\n",
       "      <th>Mean Reward</th>\n",
       "      <th>Max Reward</th>\n",
       "      <th>Accuracy</th>\n",
       "      <th>Margin</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>0.535345</td>\n",
       "      <td>0.555116</td>\n",
       "      <td>590</td>\n",
       "      <td>14300506.000000</td>\n",
       "      <td>-2.010905</td>\n",
       "      <td>-0.084100</td>\n",
       "      <td>1.566081</td>\n",
       "      <td>0.704167</td>\n",
       "      <td>0.737808</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "held-out accuracy: 0.704 | margin: 0.738\n"
     ]
    }
   ],
   "source": [
    "metrics = trainer.evaluate()\n",
    "print(f\"held-out accuracy: {metrics['eval_accuracy']:.3f} | margin: {metrics.get('eval_margin', float('nan')):.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff712597",
   "metadata": {},
   "source": [
    "## 2.7 · Try the reward model yourself\n",
    "Score two answers to the same question. A good RM should prefer the helpful one."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "de74d19c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "helpful answer : -1.555\n",
      "unhelpful answer: -3.281\n"
     ]
    }
   ],
   "source": [
    "@torch.no_grad()\n",
    "def score(prompt, answer):\n",
    "    conv = [{\"role\": \"user\", \"content\": prompt}, {\"role\": \"assistant\", \"content\": answer}]\n",
    "    text = tokenizer.apply_chat_template(conv, tokenize=False)\n",
    "    batch = tokenizer(text, return_tensors=\"pt\", add_special_tokens=False).to(trainer.model.device)\n",
    "    return trainer.model(**batch).logits[0, 0].item()\n",
    "\n",
    "q = \"How do I boil an egg?\"\n",
    "good = \"Place the egg in boiling water for about 9 minutes, then cool it in cold water before peeling.\"\n",
    "bad = \"Eggs are eggs.\"\n",
    "print(f\"helpful answer : {score(q, good):+.3f}\")\n",
    "print(f\"unhelpful answer: {score(q, bad):+.3f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "405b3450",
   "metadata": {},
   "source": [
    "**Next:** notebook 3 uses this RM (frozen) to train the SFT policy with PPO."
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "research",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}