{ "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_{= 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` / `<|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` | 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\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", "
\n", " \n", " \n", " [616/616 29:01, Epoch 1/1]\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", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
StepTraining LossValidation LossEntropyNum TokensMean Token Accuracy
2001.1668051.1992241.2108592680591.0000000.683660
4001.2067831.1792441.1733035382684.0000000.687719
6001.1822811.1695831.1628058056049.0000000.689425
6161.1690281.1693661.1626978263048.0000000.689398

" ], "text/plain": [ "" ] }, "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\n", " \n", " \n", " [62/62 00:09]\n", " \n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/html": [ "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Training LossValidation LossStepEntropyNum TokensMean Token Accuracy
1.1690281.1693666161.1626978263048.0000000.689398

" ], "text/plain": [ "" ] }, "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 }