{ "cells": [ { "cell_type": "markdown", "id": "c6dd254f", "metadata": {}, "source": [ "# 3 · RL: sample, score, update, inspect\n", "\n", "This is a small **on-policy REINFORCE** exercise with a leave-one-out baseline and a KL penalty toward the frozen Slayer1B-1.09 parent. It is not PPO, GRPO, RLHF, or a demonstrated poetry-quality improvement. No RL was used to produce the released poetry adapter.\n", "\n", "We score a simple observable proxy: approximately four nonempty lines, distinct lines, and some minimum word count. This reward does **not** understand imagery, coherence, rhyme, truth or literary value. The lesson is how a reward changes optimization—and how it can be gamed. Start a fresh kernel." ] }, { "cell_type": "code", "execution_count": null, "id": "d34ec8f9", "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": "16d4e883", "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": "83cc790d", "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": "0a37a95e", "metadata": {}, "outputs": [], "source": [ "for text in [\"\", \"one line\", \"one\\ntwo\\nthree\\nfour\", \"same\\nsame\\nsame\\nsame\"]:\n", " print(repr(text), \"->\", form_reward(text))\n", "print(\"Nonsense can score well:\", form_reward(\"amber blue stone river moon bell\\ncopper green cloud window rain ash\\nsilver red leaf bridge snow dusk\\ngolden black wind candle lake dawn\"))" ] }, { "cell_type": "markdown", "id": "8f66bb89", "metadata": {}, "source": [ "## The update, in order\n", "\n", "1. Sample a fresh group of completions from the current policy at temperature 1 with no top-k, repetition penalty or EOS suppression.\n", "2. Score each completion. Subtract the mean reward of the *other* group members, then detach the resulting advantage.\n", "3. Recompute each sampled completion's log probability, summing only completion positions (including EOS if sampled).\n", "4. Minimize `−advantage × sum(log π(token | prefix))` plus a full categorical `KL(policy || parent)` averaged across completion positions.\n", "5. Take one clipped-gradient optimizer step, then discard the group and sample again.\n", "\n", "The parent reference uses the same frozen weights with LoRA disabled, avoiding a second full model. Eval mode makes rollout and scoring distributions consistent; gradients still work. There is no clipping objective, replay, or filtered sampling/log-probability mismatch. The KL regularizes token distributions at sampled prefixes; this is a teaching surrogate, not a complete sequence-level trust-region method. Group size 4 gives a noisy estimator. If rewards are identical, policy-gradient advantages are zero." ] }, { "cell_type": "code", "execution_count": null, "id": "893eb658", "metadata": {}, "outputs": [], "source": [ "prompts = [\"The evening rain\", \"A candle in the window\", \"Beyond the river\"]\n", "if RUN_TRAINING:\n", " history = workshop.rl(prompts, form_reward, updates=3, group_size=4,\n", " max_new_tokens=24, kl_beta=0.02)\n", " workshop.save(\"outputs/rl_adapter.pt\")\n", " Path(\"outputs/rl_history.json\").write_text(json.dumps(history, indent=2))\n", "else:\n", " print(\"Training skipped. Set RUN_TRAINING=True after reading the reward and objective.\")" ] }, { "cell_type": "markdown", "id": "97e4777c", "metadata": {}, "source": [ "## Inspect reward hacking before celebrating a rising score\n", "\n", "Read every logged completion. Is the model generating line breaks instead of meaningful verse? Are the lines distinct only because of random words? Does it avoid EOS to collect length reward? Track reward components, length, EOS frequency and KL as well as total reward.\n", "\n", "Compare blinded generations on prompts that never enter the reward loop. Keep a separate rubric for fluency, coherence, imagery, requested form and completeness. An increase in this reward alone supports only improvement on this proxy—not better poems. If you later train a preference reward model, validate its judgments separately and reserve held-out human comparisons.\n", "\n", "For a serious run, begin with a useful SFT policy, freeze its reference, collect validated preferences or a task-specific verifiable reward, and use a tested RL trainer with token-budget and failure monitoring. This notebook intentionally starts from the parent and uses a transparent toy reward to isolate the mechanics. It is not a recommendation to scale this exact loop or reward." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }