File size: 28,922 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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4c624e43",
   "metadata": {},
   "source": [
    "# Stage 1 Β· Supervised Fine-Tuning (SFT)\n",
    "**End-to-end RLHF, notebook 1 of 4** β€” SFT β†’ Reward Model β†’ PPO β†’ Evaluation\n",
    "\n",
    "**Goal:** turn a *base* LM (which only continues text) into an assistant that answers in the chat format and knows when to stop, by imitating good demonstrations.\n",
    "\n",
    "**Loss:** next-token cross-entropy on **assistant tokens only**\n",
    "\n",
    "$$\\mathcal{L}_{SFT}(\\theta) = -\\sum_{t \\in \\text{assistant}} \\log \\pi_\\theta(y_t \\mid x, y_{<t})$$\n",
    "\n",
    "| | |\n",
    "|---|---|\n",
    "| Model in | `Qwen/Qwen3-0.6B-Base` |\n",
    "| Data | `HuggingFaceH4/ultrafeedback_binarized` Β· split `train_sft` (column `messages`) |\n",
    "| Model out | `outputs/sft` (used by notebooks 2, 3, 4) |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5875def",
   "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": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "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": "8eb5f955",
   "metadata": {},
   "source": [
    "## 1.1 Β· Choosing the model and tokenizer\n",
    "- **Base, not instruct:** an instruct checkpoint is already aligned, so we couldn't see what each stage adds.\n",
    "- **0.6B parameters:** PPO later holds four models in memory at once.\n",
    "- **One tokenizer for every stage:** in PPO the reward model reads the policy's *token ids*, never text.\n",
    "- **Right padding** for training (left padding only when generating).\n",
    "\n",
    "Let's inspect what the tokenizer does."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "37cf1603",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "vocab size : 151669\n",
      "10 tokens: ['RL', 'HF', 'Δ align', 's', 'Δ language', 'Δ models', 'Δ with', 'Δ human', 'Δ preferences', '.']\n",
      "eos / pad  : <|im_end|> 151645 / <|endoftext|> 151643\n"
     ]
    }
   ],
   "source": [
    "tokenizer = load_tokenizer(BASE_MODEL, padding_side=\"right\")\n",
    "\n",
    "text = \"RLHF aligns language models with human preferences.\"\n",
    "ids = tokenizer(text)[\"input_ids\"]\n",
    "print(\"vocab size :\", len(tokenizer))\n",
    "print(f\"{len(ids)} tokens:\", tokenizer.convert_ids_to_tokens(ids))\n",
    "print(\"eos / pad  :\", tokenizer.eos_token, tokenizer.eos_token_id, \"/\", tokenizer.pad_token, tokenizer.pad_token_id)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "366d22ec",
   "metadata": {},
   "source": [
    "## 1.2 Β· The chat template\n",
    "Models see one token stream, not JSON. The template wraps each turn in `<|im_start|>role … <|im_end|>`.\n",
    "The `{% generation %}` tags let us ask for an **assistant mask**: 1 on tokens the model should learn to produce."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "40384395",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<|im_start|>user\n",
      "What color is the sky?<|im_end|>\n",
      "<|im_start|>assistant\n",
      "It is blue.<|im_end|>\n",
      "\n",
      "  -   '<|im_start|>'\n",
      "  -   'user'\n",
      "  -   '\\n'\n",
      "  -   'What'\n",
      "  -   ' color'\n",
      "  -   ' is'\n",
      "  -   ' the'\n",
      "  -   ' sky'\n",
      "  -   '?'\n",
      "  -   '<|im_end|>'\n",
      "  -   '\\n'\n",
      "  -   '<|im_start|>'\n",
      "  -   'assistant'\n",
      "  -   '\\n'\n",
      "LOSS  'It'\n",
      "LOSS  ' is'\n",
      "LOSS  ' blue'\n",
      "LOSS  '.'\n",
      "LOSS  '<|im_end|>'\n",
      "  -   '\\n'\n"
     ]
    }
   ],
   "source": [
    "example = [{\"role\": \"user\", \"content\": \"What color is the sky?\"},\n",
    "           {\"role\": \"assistant\", \"content\": \"It is blue.\"}]\n",
    "print(tokenizer.apply_chat_template(example, tokenize=False))\n",
    "\n",
    "enc = tokenizer.apply_chat_template(example, tokenize=True, return_dict=True, return_assistant_tokens_mask=True)\n",
    "for tid, m in zip(enc[\"input_ids\"], enc[\"assistant_masks\"]):\n",
    "    print(f\"{'LOSS ' if m else '  -  '} {tokenizer.decode([tid])!r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "06344188",
   "metadata": {},
   "source": [
    "## 1.3 Β· Data\n",
    "UltraFeedback's `train_sft` split holds full conversations in a `messages` column.\n",
    "We keep **only** that column β€” TRL detects the dataset format from column names, and a stray string `prompt` column would confuse it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "12034c3d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset({\n",
      "    features: ['messages'],\n",
      "    num_rows: 20000\n",
      "})\n",
      "[\n",
      " {\n",
      "  \"content\": \"how can i develop a habit of drawing daily\",\n",
      "  \"role\": \"user\"\n",
      " },\n",
      " {\n",
      "  \"content\": \"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\\n1. Set a specific time: Allocate a specific time of the day to draw. It could be in the morning, afternoon, or evening. Make drawing a part of your daily routine.\\n2. Set a specific duration: Determine the amount of time you want to spend on drawing each day. It can be as little as 10 minutes or as long as an hour. Be consistent with the duration to help build the habit.\\n3. Start small and simple: Don't try to create a masterpiece every day, start \n"
     ]
    }
   ],
   "source": [
    "train_ds = load_split(\"train_sft\", N_SFT).select_columns([\"messages\"])\n",
    "eval_ds  = load_split(\"test_sft\", N_EVAL).select_columns([\"messages\"])\n",
    "print(train_ds)\n",
    "print(json.dumps(train_ds[0][\"messages\"][:2], indent=1)[:800])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0826eb57",
   "metadata": {},
   "source": [
    "## 1.4 Β· Before training: what does the base model do?\n",
    "A base model continues text; it doesn't know the chat format or when to stop. Keep this output to compare after SFT."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8e4eefa6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "813e596ccf0b457ba3923c5f1f8d0016",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/310 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BASE MODEL:\n",
      " Explain in two sentences why the sky is blue. βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      " βš‡ βš‡\n",
      "\n"
     ]
    }
   ],
   "source": [
    "DEMO_PROMPT = \"Explain in two sentences why the sky is blue.\"\n",
    "from transformers import AutoModelForCausalLM\n",
    "base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.bfloat16 if USE_BF16 else torch.float32).to(DEVICE)\n",
    "print(\"BASE MODEL:\\n\", chat(base, tokenizer, DEMO_PROMPT))\n",
    "del base; torch.cuda.empty_cache() if torch.cuda.is_available() else None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82624674",
   "metadata": {},
   "source": [
    "**Why the `βš‡` loop?** The base model has never seen `<|im_start|>` / `<|im_end|>`. After this unfamiliar format it has no idea what should come next, so it falls into a repetition loop β€” and it never learned to stop.\n",
    "\n",
    "**Same model, plain text instead of chat format:** give it an ordinary sentence to continue. It *does* know why the sky is blue β€” the knowledge is there, only the assistant behaviour is missing. That is what SFT adds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5828d94f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "83454f022aa049349453749c0bde5387",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/310 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The sky is blue because the molecules in the air are ________.\n",
      "Answer:\n",
      "The sky is blue because the molecules in the air are **reflected**. The molecules in the air are scattered in all directions by the sun\n"
     ]
    }
   ],
   "source": [
    "from transformers import AutoModelForCausalLM\n",
    "base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, dtype=torch.bfloat16).to(DEVICE)\n",
    "ids = tokenizer(\"The sky is blue because\", return_tensors=\"pt\").to(DEVICE)\n",
    "out = base.generate(**ids, max_new_tokens=40, do_sample=False)\n",
    "print(tokenizer.decode(out[0], skip_special_tokens=True))\n",
    "del base; torch.cuda.empty_cache()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e88ad47",
   "metadata": {},
   "source": [
    "## 1.5 Β· Hyperparameters\n",
    "\n",
    "| Setting | Value | Why |\n",
    "|---|---|---|\n",
    "| `assistant_only_loss` | True | no loss on user/system tokens |\n",
    "| `eos_token` | `<|im_end|>` | the model must learn to end its turn |\n",
    "| `learning_rate` | 2e-5 | full fine-tune (use ~1e-4 with LoRA) |\n",
    "| `num_train_epochs` | 1 | small SFT sets overfit fast |\n",
    "| effective batch | BATCH Γ— GRAD_ACC | 8 Γ— 4 = 32 by default |\n",
    "| `max_length` | 1024 | longer conversations truncated |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "669e6c34",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a4969eb177fa46f6b514900935f5c51b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Loading weights:   0%|          | 0/310 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "5d3db8244dea409a98f0a553582f142a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Truncating train dataset:   0%|          | 0/20000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "349949b795a04e0187d5a36e87a126a0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropping fully masked examples from train dataset:   0%|          | 0/20000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b73ddc5779d646b28a124613e0cf8d42",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Tokenizing eval dataset:   0%|          | 0/500 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a8f6514fbf0345218b7a8c877018f6a8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Building labels for eval dataset:   0%|          | 0/500 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ac283385027e4726910d996ac8dfee29",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Truncating eval dataset:   0%|          | 0/500 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6309c6b5d696466c904acd08f6ad3ad1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropping fully masked examples from eval dataset:   0%|          | 0/500 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from trl import SFTConfig, SFTTrainer\n",
    "\n",
    "args = SFTConfig(\n",
    "    output_dir=SFT_DIR,\n",
    "    max_length=1024,\n",
    "    assistant_only_loss=True,      # mask system/user tokens out of the loss\n",
    "    eos_token=EOS_TOKEN,           # each assistant turn ends with <|im_end|>\n",
    "    packing=False,\n",
    "    num_train_epochs=1, max_steps=MAX_STEPS,\n",
    "    per_device_train_batch_size=BATCH, gradient_accumulation_steps=GRAD_ACC,\n",
    "    learning_rate=2e-5, lr_scheduler_type=\"cosine\", warmup_steps=0.03,\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 = SFTTrainer(\n",
    "    model=BASE_MODEL,              # a string -> TRL loads AutoModelForCausalLM\n",
    "    args=args,\n",
    "    train_dataset=train_ds,\n",
    "    eval_dataset=eval_ds,\n",
    "    processing_class=tokenizer,\n",
    "    # peft_config=LoraConfig(r=16, lora_alpha=32, target_modules=\"all-linear\"),  # LoRA option\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3628fd8c",
   "metadata": {},
   "source": [
    "## 1.6 Β· Sanity check: exactly which tokens are trained on?\n",
    "TRL folds the mask into `labels`: **-100 = ignored**, otherwise the token id. The trained text should be only the assistant reply, ending in `<|im_end|>`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3477b581",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loss on 342/360 tokens\n",
      "TRAINED-ON TEXT (end): \"rce of motivation and help you see how far you've come.\\n\\nRemember, developing a habit takes time and patience. Stay consistent with your drawing practice, be flexible and open to trying new things, and with time, you'll develop a habit of daily drawing that brings you joy and satisfaction.<|im_end|>\"\n"
     ]
    }
   ],
   "source": [
    "sample = trainer.train_dataset[0]\n",
    "labels_on = [t for t in sample[\"labels\"] if t != -100]\n",
    "print(f\"loss on {len(labels_on)}/{len(sample['input_ids'])} tokens\")\n",
    "print(\"TRAINED-ON TEXT (end):\", repr(tokenizer.decode(labels_on)[-300:]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22aa7827",
   "metadata": {},
   "source": [
    "## 1.7 Β· Train and save\n",
    "Watch `loss`, `eval_loss` (rising while train loss falls = overfitting) and `mean_token_accuracy`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f4541f0f",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "[transformers] The tokenizer has new PAD/BOS/EOS tokens that differ from the model config and generation config. The model config and generation config were aligned accordingly, being updated with the tokenizer's values. Updated tokens: {'eos_token_id': 151645, 'bos_token_id': None, 'pad_token_id': 151643}.\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='616' max='616' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [616/616 29:01, 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>Entropy</th>\n",
       "      <th>Num Tokens</th>\n",
       "      <th>Mean Token Accuracy</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>200</td>\n",
       "      <td>1.166805</td>\n",
       "      <td>1.199224</td>\n",
       "      <td>1.210859</td>\n",
       "      <td>2680591.000000</td>\n",
       "      <td>0.683660</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>400</td>\n",
       "      <td>1.206783</td>\n",
       "      <td>1.179244</td>\n",
       "      <td>1.173303</td>\n",
       "      <td>5382684.000000</td>\n",
       "      <td>0.687719</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>600</td>\n",
       "      <td>1.182281</td>\n",
       "      <td>1.169583</td>\n",
       "      <td>1.162805</td>\n",
       "      <td>8056049.000000</td>\n",
       "      <td>0.689425</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>616</td>\n",
       "      <td>1.169028</td>\n",
       "      <td>1.169366</td>\n",
       "      <td>1.162697</td>\n",
       "      <td>8263048.000000</td>\n",
       "      <td>0.689398</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": "d698b536a49640efa44053bae82538df",
       "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/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='62' max='62' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [62/62 00:09]\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>Entropy</th>\n",
       "      <th>Num Tokens</th>\n",
       "      <th>Mean Token Accuracy</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>1.169028</td>\n",
       "      <td>1.169366</td>\n",
       "      <td>616</td>\n",
       "      <td>1.162697</td>\n",
       "      <td>8263048.000000</td>\n",
       "      <td>0.689398</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": [
      "{'eval_loss': 1.1693661212921143, 'eval_entropy': 1.162696687444564, 'eval_num_tokens': 8263048.0, 'eval_mean_token_accuracy': 0.6893984262020357}\n"
     ]
    }
   ],
   "source": [
    "trainer.train()\n",
    "trainer.save_model(SFT_DIR)\n",
    "tokenizer.save_pretrained(SFT_DIR)     # the tokenizer travels with every checkpoint\n",
    "print(trainer.evaluate())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2bad0b09",
   "metadata": {},
   "source": [
    "## 1.8 Β· After training: same prompt, SFT model\n",
    "It should now answer in the assistant turn and stop on its own."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "f730adc4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SFT MODEL:\n",
      " The sky appears blue due to the scattering of sunlight by the Earth's atmosphere, which causes shorter wavelengths of light (like blue) to scatter more than longer wavelengths (like red) in the atmosphere.\n"
     ]
    }
   ],
   "source": [
    "sft_model = trainer.model.eval()\n",
    "print(\"SFT MODEL:\\n\", chat(sft_model, tokenizer, DEMO_PROMPT))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e3d02ef",
   "metadata": {},
   "source": [
    "**Next:** notebook 2 trains a reward model starting from `outputs/sft`."
   ]
  }
 ],
 "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
}