{ "cells": [ { "cell_type": "markdown", "id": "b3e5c999", "metadata": {}, "source": [ "# 2 · SFT: teach a request → response relationship\n", "\n", "**Supervised fine-tuning** teaches responses to explicit prompts. Unlike CPT, prompt tokens here are context only: their labels are `-100`, so they contribute no loss. Response tokens and the final EOS are supervised.\n", "\n", "This is a new teaching experiment, not a stage that was applied to the published poetry adapter. Start from the original Slayer1B-1.09 in a fresh kernel. We use a plain text template because this base has no established chat protocol. Inference must use the same template." ] }, { "cell_type": "code", "execution_count": null, "id": "260a5786", "metadata": {}, "outputs": [], "source": [ "%pip -q install \"torch>=2.4\" \"huggingface_hub>=0.26\" \"tokenizers>=0.20\" \"pydantic>=2\" numpy tqdm\n" ] }, { "cell_type": "code", "execution_count": null, "id": "d94f2c55", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import sys, json\n", "from huggingface_hub import snapshot_download\n", "ROOT = Path(snapshot_download(\"SlayerLab/Slayer1B-Poetry\", allow_patterns=[\n", " \"common.py\", \"lora.py\", \"recipe.json\", \"tokenizer.json\",\n", " \"tutorials/slayer_training.py\", \"baseline-samples.json\", \"samples.json\", \"result.json\"\n", "]))\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(ROOT / \"tutorials\"))\n", "from slayer_training import Workshop, Config, form_reward\n" ] }, { "cell_type": "code", "execution_count": null, "id": "5f5fa2f9", "metadata": {}, "outputs": [], "source": [ "import torch\n", "print(\"CUDA available:\", torch.cuda.is_available())\n", "# Downloads and SHA256-checks the pinned ~4.3 GB parent checkpoint.\n", "# Needs host RAM for loading plus GPU memory for the model and activations.\n", "# This is a microbatch-1 teaching recipe, not a measured VRAM guarantee.\n", "workshop = Workshop(ROOT, Config(context=128, learning_rate=1e-4, seed=42))\n", "RUN_TRAINING = False # Change to True after inspecting the examples and selecting your GPU.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "68bb5d37", "metadata": {}, "outputs": [], "source": [ "def prompt_for(request):\n", " return f\"Request: {request}\\nPoem:\\n\"\n", "\n", "# Original illustrative pairs, not a validated instruction dataset.\n", "examples = [\n", " {\"prompt\": prompt_for(\"Write two lines about rain.\"),\n", " \"response\": \"The rain taps softly on the pane;\\nThe street gives back the light again.\"},\n", " {\"prompt\": prompt_for(\"Write two lines about a river.\"),\n", " \"response\": \"The river carries leaves away;\\nThe bridge holds still above the day.\"},\n", " {\"prompt\": prompt_for(\"Write two lines about a window.\"),\n", " \"response\": \"One window shines above the square;\\nA quiet room is waiting there.\"}\n", "]\n", "x, labels = workshop.encode_sft(examples[0])\n", "print(\"Prompt:\", examples[0][\"prompt\"])\n", "print(\"Response:\", examples[0][\"response\"])\n", "print(\"Ignored target positions:\", int((labels == -100).sum()))\n", "print(\"Supervised target positions:\", int((labels != -100).sum()))\n", "print(\"First supervised token:\", workshop.tokenizer.decode(labels[labels != -100][:1].tolist()))\n", "assert labels[0, -1].item() == 0 # Teach the response to end.\n" ] }, { "cell_type": "markdown", "id": "995773b4", "metadata": {}, "source": [ "## Why the boundary matters\n", "\n", "The prompt is tokenized separately from the response to define a stable boundary. For a prompt with P tokens including initial EOS, targets `0 ... P-2` are ignored; target `P-1` predicts the first response token. Masking P positions would accidentally drop that first token. Oversized examples raise an error instead of silently truncating away the answer.\n", "\n", "The same convention must be used for generation: tokenize the complete prompt first, then generate the response. There is no padding in this microbatch-1 loop. With larger batches, also mask padded labels and handle attention consistently." ] }, { "cell_type": "code", "execution_count": null, "id": "1bc30c76", "metadata": {}, "outputs": [], "source": [ "heldout_prompt = prompt_for(\"Write two lines about the moon.\")\n", "before = workshop.sample(heldout_prompt, max_new_tokens=32, seed=1234)[1]\n", "print(\"BEFORE:\", before)\n", "if RUN_TRAINING:\n", " losses = workshop.sft(examples, steps=10)\n", " workshop.save(\"outputs/sft_adapter.pt\")\n", " after = workshop.sample(heldout_prompt, max_new_tokens=32, seed=1234)[1]\n", " print(\"AFTER:\", after)\n", "else:\n", " print(\"Training skipped. Set RUN_TRAINING=True to run the lesson.\")" ] }, { "cell_type": "markdown", "id": "c48f6942", "metadata": {}, "source": [ "## What would count as progress?\n", "\n", "Evaluate unseen topics, wording and requested forms. Check whether the output obeys the request, remains fluent, avoids copying training lines and ends cleanly. A decreasing loss on three memorized pairs is not evidence of general instruction following.\n", "\n", "A real dataset needs varied, high-quality, rights-cleared request/poem pairs and source-disjoint validation. Do not fabricate request metadata that the paired poem does not satisfy. You can later start SFT from a CPT adapter, but use a separate experiment and compare it against both the parent and CPT model. All three lessons default to independent runs from the parent to keep attribution clear." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }