Add self-contained base-model CPT, SFT, RL and checkpoint averaging notebook tutorials
Browse filesFiles changed (25)
- README.md+14
- tutorials/00_generation_comparison.ipynbAdded+268
- tutorials/01_cpt.ipynbAdded+155
- tutorials/02_sft.ipynbAdded+142
- tutorials/03_rl.ipynbAdded+130
- tutorials/04_checkpoint_averaging.ipynbAdded+157
- tutorials/AVERAGING_RESULTS.mdAdded+86
- tutorials/README.mdAdded+60
- tutorials/SHA256SUMSAdded+23
- tutorials/VALIDATION.mdAdded+22
- tutorials/average-45k-55k.merge.jsonAdded+32
- tutorials/average_checkpoints.pyAdded+70
- tutorials/inspect_checkpoint.pyAdded+48
- tutorials/merge-comparison.jsonAdded+53
- tutorials/requirements.txtAdded+7
- tutorials/runtime/baseline-samples.jsonAdded+32
- tutorials/runtime/common.pyAdded+25
- tutorials/runtime/generate.pyAdded+23
- tutorials/runtime/lora.pyAdded+22
- tutorials/runtime/recipe.jsonAdded+40
- tutorials/runtime/result.jsonAdded+22
- tutorials/runtime/samples.jsonAdded+32
- tutorials/runtime/sampling.pyAdded+13
- tutorials/runtime/tokenizer.jsonAdded
- tutorials/slayer_training.pyAdded+174
136 unmodified lines137138139140141142136 unmodified lines- **Why this checkpoint:** an openly released 1.07B-parameter model with published intermediate weights and a reproducible native PyTorch loader.- **Know before you load:** this is a **base model**, not a chat assistant. It has not been instruction-tuned and has no chat template or demonstrated tool-use behavior.## Model details| Property | Specification |136 unmodified lines137138139140141142143144145146147148149150151152153154155156136 unmodified lines- **Why this checkpoint:** an openly released 1.07B-parameter model with published intermediate weights and a reproducible native PyTorch loader.- **Know before you load:** this is a **base model**, not a chat assistant. It has not been instruction-tuned and has no chat template or demonstrated tool-use behavior.## Train your own Slayer1B: CPT, SFT and RL notebooksStart directly from this **Slayer1B-1.09 base model**, pinned to the released update-45,000 checkpoint. These tutorials include the native loader, tokenizer and training loops in this repository; no poetry adapter is required. Each training lesson starts independently from the frozen base and updates LoRA parameters.| Notebook | Learn by doing || --- | --- || [00 · Compare generation quality](tutorials/00_generation_comparison.ipynb) | Inspect the published poetry CPT case study and design a fair before/after evaluation || [01 · CPT on raw text](tutorials/01_cpt.ipynb) | Predict every next token in domain text; save an adapter and compare continuations || [02 · SFT on prompt/response pairs](tutorials/02_sft.ipynb) | Mask prompt labels, train response tokens and use a consistent inference template || [03 · Reward-based RL](tutorials/03_rl.ipynb) | Run a small on-policy REINFORCE loop with rewards and frozen-parent KL; inspect reward hacking || [04 · Average N checkpoints](tutorials/04_checkpoint_averaging.ipynb) | Build a full averaged checkpoint, check compatibility and compare it with every source |[Setup and walkthrough](tutorials/README.md) · [Training-loop source](tutorials/slayer_training.py) · [Checks actually run](tutorials/VALIDATION.md). Download a notebook and open it in Jupyter, VS Code, or Google Colab. Training cells are opt-in. Toy SFT/RL examples teach the mechanics; they are not claims that this base model has undergone instruction tuning or RL. The verse-form reward does not measure literary quality.## Model details| Property | Specification |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268{ "cells": [ { "cell_type": "markdown", "id": "0d698d75", "metadata": {}, "source": [ "# 0 · What changed when Slayer learned poetry?\n", "\n", "Start with behavior, then learn how to change it. Regular **Slayer1B-1.09** is a base continuation model; **Slayer1B-Poetry** is a raw-poem CPT LoRA adaptation. This notebook displays all three recorded matched sample pairs without loading weights or renting a GPU.\n", "\n", "This series uses native Slayer PyTorch code, not Transformers/PEFT wrappers. Next: [CPT](01_cpt.ipynb), [SFT](02_sft.ipynb), [RL](03_rl.ipynb)." ] }, { "cell_type": "code", "execution_count": 1, "id": "644f4675", "metadata": { "execution": { "iopub.execute_input": "2026-11-18T03:45:49.184826Z", "iopub.status.busy": "2026-11-18T03:45:49.184751Z", "iopub.status.idle": "2026-11-18T03:45:49.187533Z", "shell.execute_reply": "2026-11-18T03:45:49.187150Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dependencies already installed for validation\n" ] } ], "source": [ "%pip -q install \"torch>=2.4\" \"huggingface_hub>=0.26\" \"tokenizers>=0.20\" \"pydantic>=2\" numpy tqdm\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "9cb422db", "metadata": { "execution": { "iopub.execute_input": "2026-11-18T03:45:49.188560Z", "iopub.status.busy": "2026-11-18T03:45:49.188492Z", "iopub.status.idle": "2026-11-18T03:45:49.774788Z", "shell.execute_reply": "2026-11-18T03:45:49.774330Z" } }, "outputs": [], "source": [ "from pathlib import Path\n", "import sys, json\n", "from huggingface_hub import snapshot_download\n", "RELEASE = Path(snapshot_download(\"SlayerLab/Slayer1B-1.09\", allow_patterns=[\"tutorials/*\"]))\n", "ROOT = RELEASE / \"tutorials\" / \"runtime\"\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(RELEASE / \"tutorials\"))\n", "from slayer_training import Workshop, Config, form_reward\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "f610a058", "metadata": { "execution": { "iopub.execute_input": "2026-11-18T03:45:49.776178Z", "iopub.status.busy": "2026-11-18T03:45:49.776056Z", "iopub.status.idle": "2026-11-18T03:45:49.780806Z", "shell.execute_reply": "2026-11-18T03:45:49.780459Z" } }, "outputs": [ { "data": { "text/markdown": [ "### Opening: `The night`" ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "REGULAR SLAYER:\n", "The night-crawlers of the genus Trapezias are crustaceans that spend almost all of their life lives in burrows that they excavate. At night the crustaceans feed on insects they can hide under objects and in crevices. Most species are nocturnal, but there is also one day-time dwelling species with an unusual behaviour: it does not burrow at all during the daytime, and wakes up in the morning to res\n", "\n", "POETRY ADAPTER:\n", "The night-crowd of the streets\n", "Foamed and frothed to and fro;\n", "And many a wiry streetman in white was shaded\n", "By the flurry: all he felt had been washed with his blood.\n", "\n", "And lo, the sun had risen; yet still\n", "His smile seemed sad, with no change in his eyes for sorrow\n", "— Thrust from behind, and backward again,\n", "He heard his old\n", "\n" ] }, { "data": { "text/markdown": [ "### Opening: `On the shore`" ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "REGULAR SLAYER:\n", "On the shore of a lake or in a river, there are numerous plant communities. There could be grasses on the surface or sedges on the bottom. Mosses and the mushrooms that grow from them add colour to the scene and may attract some insects. If you look closely, there usually is some sort of creature beneath the vegetation too; often they can’t see because it is below the water level, but if your eyes are sufficiently sharp, you will spot an occasional\n", "\n", "POETRY ADAPTER:\n", "On the shore of a deep bay.\n", "It's a lonely island;--\n", "The island is small.\n", "\n" ] }, { "data": { "text/markdown": [ "### Opening: `A small bird`" ], "text/plain": [ "<IPython.core.display.Markdown object>" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "REGULAR SLAYER:\n", "A small bird with a short tail. The red-winged Blackbird is a popular game bird and is found wherever there are people. Often they will be seen in backyards, fields or woodland edge all over the world, but is equally at home in farmland fields, forest margins and shrubby areas. It has small grey/brown body, yellowish eyes on a green black background, yellow wing patches, and a white patch above its chest and a red\n", "\n", "POETRY ADAPTER:\n", "A small bird that went forth\n", "And sang from its nest so long\n", "It was not a song of woe,\n", "Nor a warlike tirpe’r the same.\n", "\n", "Shared sampling: {'temperature': 1.0, 'top_k': 50, 'repetition_penalty': 1.1, 'seed': 1234, 'max_new_tokens': 96}\n" ] } ], "source": [ "from IPython.display import display, Markdown\n", "base = json.loads((ROOT / \"baseline-samples.json\").read_text())\n", "poetry = json.loads((ROOT / \"samples.json\").read_text())\n", "for b, p in zip(base, poetry):\n", " assert b[\"opening\"] == p[\"opening\"]\n", " display(Markdown(f\"### Opening: `{b['opening']}`\"))\n", " print(\"REGULAR SLAYER:\\n\" + b[\"text\"])\n", " print(\"\\nPOETRY ADAPTER:\\n\" + p[\"text\"] + \"\\n\")\n", "print(\"Shared sampling:\", {k: base[0][k] for k in [\"temperature\", \"top_k\", \"repetition_penalty\", \"seed\", \"max_new_tokens\"]})" ] }, { "cell_type": "markdown", "id": "95d131bb", "metadata": {}, "source": [ "## Read the samples critically\n", "\n", "The parent produces descriptive prose for all three openings; the adapter produces lineated verse. Look for imagery, coherence, repetition, natural phrasing and whether the ending resolves. In the bird sample, “tirpe’r” is a clear defect. The shore sample is short and plain. Line breaks show a style shift; they do not prove better literature.\n", "\n", "These prompts were existing run diagnostics. They are not a blinded preference study. Both sides used temperature 1, top-k 50, repetition penalty 1.1, seed 1234, at most 96 new tokens and a 16-token EOS suppression period. Token caps can cut a sentence short." ] }, { "cell_type": "code", "execution_count": 4, "id": "080bf53d", "metadata": { "execution": { "iopub.execute_input": "2026-11-18T03:45:49.782231Z", "iopub.status.busy": "2026-11-18T03:45:49.782149Z", "iopub.status.idle": "2026-11-18T03:45:49.784141Z", "shell.execute_reply": "2026-11-18T03:45:49.783729Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"processed_tokens\": 37657600,\n", " \"updates\": 2299,\n", " \"selected_update\": 2299,\n", " \"baseline_validation\": {\n", " \"ce\": 3.4131230413913727,\n", " \"perplexity\": 30.35991161803797,\n", " \"tokens\": 65536\n", " },\n", " \"selected_full_validation\": {\n", " \"ce\": 3.289073363389119,\n", " \"perplexity\": 26.818001596520336,\n", " \"tokens\": 827392\n", " },\n", " \"test\": {\n", " \"ce\": 3.2436408333964164,\n", " \"perplexity\": 25.62685521306139,\n", " \"tokens\": 788480\n", " },\n", " \"elapsed_seconds\": 421.2775601008907,\n", " \"peak_allocated_GiB\": 31.86785888671875\n", "}\n" ] } ], "source": [ "print(json.dumps(json.loads((ROOT / \"result.json\").read_text()), indent=2))" ] }, { "cell_type": "markdown", "id": "af81ebda", "metadata": {}, "source": [ "## A quality evaluation you can repeat\n", "\n", "Before training, freeze a separate list of openings spanning nature, urban scenes, dialogue and emotional tones. Keep training authors/texts out of that list. Generate each model with the same prompt list, sampling settings, length limits and several seeds. Hide model identity and randomize left/right order. Score coherence, imagery, fluency, repetition, form and completeness separately. Record ties and failed samples as well as wins. Check suspicious passages against training data before claiming originality.\n", "\n", "Keep this held-out evaluation out of checkpoint selection and reward design. Report prompt count, seed count, raw outputs and rater agreement; do not turn three demonstrations into a general win rate. Lower validation perplexity is useful supporting evidence, but not a substitute for reader judgment." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.14.7" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155{ "cells": [ { "cell_type": "markdown", "id": "19c7c921", "metadata": {}, "source": [ "# 1 · CPT: teach a domain through raw text\n", "\n", "**Continued pretraining** predicts every next token in raw documents. There are no user/assistant labels. Here we adapt native Slayer1B-1.09 with LoRA while freezing the base. LoRA describes which parameters change; CPT describes the learning objective.\n", "\n", "The published poetry run used 55,699 English training documents, 37.66M processed tokens and 2,299 updates. This small notebook demonstrates the mechanism; ten updates on a few toy verses do not reproduce that result. Full run evidence and recipe remain in the [model card](https://huggingface.co/SlayerLab/Slayer1B-Poetry). Start a fresh kernel for each lesson." ] }, { "cell_type": "code", "execution_count": null, "id": "51b5b1d4", "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": "adff5481", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import sys, json\n", "from huggingface_hub import snapshot_download\n", "RELEASE = Path(snapshot_download(\"SlayerLab/Slayer1B-1.09\", allow_patterns=[\"tutorials/*\"]))\n", "ROOT = RELEASE / \"tutorials\" / \"runtime\"\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(RELEASE / \"tutorials\"))\n", "from slayer_training import Workshop, Config, form_reward\n" ] }, { "cell_type": "code", "execution_count": null, "id": "42c3e512", "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": "markdown", "id": "6d01297a", "metadata": {}, "source": [ "## Inspect the data and targets\n", "\n", "The following tiny original teaching verses are deliberately small enough to read. They are not the published training corpus. Replace them with texts you have rights to use. Split by author/source before tokenization, deduplicate, and keep validation/test separate.\n", "\n", "Each document gets EOS boundaries (`0`). We concatenate documents and take nonoverlapping windows of `context + 1` tokens. Input is the window without its last token; target is the same window shifted by one. Every target contributes to loss. Attention can cross EOS boundaries." ] }, { "cell_type": "code", "execution_count": null, "id": "88935657", "metadata": {}, "outputs": [], "source": [ "texts = [\n", " \"The rain returns to empty streets.\\nA window keeps a square of light.\\nThe river folds the roofs away.\\nA footstep warms the edge of night.\",\n", " \"A cup grows cold beside the door.\\nThe morning rests upon the stair.\\nOne sparrow tests the quiet air.\\nThe house remembers nothing more.\",\n", " \"Beyond the bridge the willows lean.\\nTheir branches write across the stream.\\nThe stones are dark, the water green.\\nThe current will not keep a dream.\"\n", "]\n", "stream = [token for text in texts for token in [0] + workshop.ids(text) + [0]]\n", "print(\"Toy corpus tokens:\", len(stream))\n", "print(\"Input:\", stream[:12])\n", "print(\"Target:\", stream[1:13])" ] }, { "cell_type": "code", "execution_count": null, "id": "f7f54eef", "metadata": {}, "outputs": [], "source": [ "openings = [\"The evening train\", \"Beneath the bridge\"] # Reserve before training.\n", "before = {p: workshop.sample(p, max_new_tokens=32, seed=1234)[1] for p in openings}\n", "print(before)" ] }, { "cell_type": "code", "execution_count": null, "id": "14637feb", "metadata": {}, "outputs": [], "source": [ "if RUN_TRAINING:\n", " losses = workshop.cpt(texts, steps=10)\n", " workshop.save(\"outputs/cpt_adapter.pt\")\n", "else:\n", " print(\"Training skipped. Set RUN_TRAINING=True to run 10 teaching updates.\")" ] }, { "cell_type": "code", "execution_count": null, "id": "7f342537", "metadata": {}, "outputs": [], "source": [ "if RUN_TRAINING:\n", " for prompt in openings:\n", " print(\"OPENING:\", prompt)\n", " print(\"BEFORE:\", prompt + before[prompt])\n", " print(\"AFTER:\", prompt + workshop.sample(prompt, max_new_tokens=32, seed=1234)[1])" ] }, { "cell_type": "markdown", "id": "885053a4", "metadata": {}, "source": [ "## Scale the experiment\n", "\n", "Use a validation CE curve to detect overfitting, then compare fixed held-out generations. Increase corpus variety before increasing repeated passes over a tiny corpus. Track actual processed tokens, optimizer updates and the exact selected checkpoint. Keep the original checkpoint immutable.\n", "\n", "This helper uses one short window per update and materializes its logits to make the objective easy to inspect. It is not the published high-throughput trainer. For large corpora use memory-mapped tokens, accumulation, chunked loss, periodic validation and recoverable optimizer checkpoints; the poetry case-study repository's original `train.py` records that run's implementation. Do not use its hardcoded local corpus paths as a ready-made public dataset.\n", "\n", "The saved adapter works with `python runtime/generate.py --adapter outputs/cpt_adapter.pt` from a local download. The helper records weights/provenance for inference, not full optimizer/RNG state for exact resume." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142{ "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", "RELEASE = Path(snapshot_download(\"SlayerLab/Slayer1B-1.09\", allow_patterns=[\"tutorials/*\"]))\n", "ROOT = RELEASE / \"tutorials\" / \"runtime\"\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(RELEASE / \"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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130{ "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", "RELEASE = Path(snapshot_download(\"SlayerLab/Slayer1B-1.09\", allow_patterns=[\"tutorials/*\"]))\n", "ROOT = RELEASE / \"tutorials\" / \"runtime\"\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(RELEASE / \"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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157{ "cells": [ { "cell_type": "markdown", "id": "e05c115d", "metadata": {}, "source": [ "# 4 · Build a model by averaging N checkpoints\n", "\n", "Instead of training another model, form a new full checkpoint by averaging compatible weights:\n", "\n", "`θ_average = Σᵢ αᵢ θᵢ`, with `αᵢ ≥ 0` and `Σᵢ αᵢ = 1`.\n", "\n", "The archive contains 11 weights-only checkpoints, every 5,000 updates from 5,000 through 55,000, at pinned revision `32a7304dc2208acb3fb4a6e957498116552a4b18` (inspected 18 November 2026). They come from the same documented continuing run. The initial experiment is **45k + 50k + 55k, equal weights**. Nearby later checkpoints are a more focused first candidate than averaging the entire early-to-late trajectory; this is an experiment, not a guarantee of improvement.\n", "\n", "This is **full-weight checkpoint averaging**. It is neither an inference ensemble nor merging the poetry LoRA into its parent. Never average LoRA A/B matrices independently and assume it equals averaging their products. The output here is a standalone native full checkpoint." ] }, { "cell_type": "code", "execution_count": null, "id": "7bbef847", "metadata": {}, "outputs": [], "source": [ "%pip -q install \"torch>=2.4\" \"huggingface_hub>=0.26\" \"tokenizers>=0.20\" numpy tqdm" ] }, { "cell_type": "code", "execution_count": null, "id": "2a87ae4a", "metadata": {}, "outputs": [], "source": [ "from pathlib import Path\n", "import sys, json, gc\n", "from huggingface_hub import snapshot_download, hf_hub_download\n", "RELEASE = Path(snapshot_download(\"SlayerLab/Slayer1B-1.09\", allow_patterns=[\"tutorials/*\"]))\n", "ROOT = RELEASE / \"tutorials\" / \"runtime\"\n", "sys.path.insert(0, str(ROOT))\n", "sys.path.insert(0, str(RELEASE / \"tutorials\"))\n", "from average_checkpoints import from_hub, REPO, REVISION\n", "from inspect_checkpoint import NativeCheckpoint\n", "RUN_MERGE = False # Read disk/RAM requirements first.\n", "STEPS = [45000, 50000, 55000]\n", "WEIGHTS = [1., 1., 1.] # Normalized by the helper.\n", "OUTPUT = Path(\"outputs/slayer1b-average-45k-55k.pt\")" ] }, { "cell_type": "markdown", "id": "1c77f425", "metadata": {}, "source": [ "## Resources and compatibility checks\n", "\n", "No GPU is required to average. Each source file is about 4.3 GB. Three uncached sources plus the FP32 output require roughly 17.2 GB disk, plus filesystem/cache headroom. The FP32 accumulator alone needs roughly 4.3 GB RAM, alongside mmap source pages and temporary tensors; leave substantial headroom. This is not a measured peak-memory guarantee. Generation/evaluation is faster on a GPU.\n", "\n", "The helper pins the archive revision and verifies each source SHA256 before loading. It checks exact configs, tensor names, shapes, dtypes, finite weights, and tied embedding/output values. Nonfloating buffers must match exactly. Floating tensors accumulate in FP32. Source files remain immutable. Optimizer states are not averaged.\n", "\n", "It writes `model`, `config`, `step=0`, and merge metadata. Step 0 explicitly denotes a derived model, not a newly trained update. The sidecar records source steps, normalized coefficients, archive revision and checksums. Embedding/head tying is retained. A mismatch raises an error rather than silently mixing incompatible models." ] }, { "cell_type": "code", "execution_count": null, "id": "031ac767", "metadata": {}, "outputs": [], "source": [ "if RUN_MERGE:\n", " metadata = from_hub(STEPS, WEIGHTS, OUTPUT)\n", " print(json.dumps(metadata, indent=2))\n", "else:\n", " print(\"Merge skipped. Set RUN_MERGE=True to download and average.\")" ] }, { "cell_type": "markdown", "id": "bebdb924", "metadata": {}, "source": [ "## Compare every source against the average\n", "\n", "Do not compare only against the oldest checkpoint. An average that beats 45k but loses to 55k may offer no practical benefit. Use identical tokenization, dtype, prompts, sampler, seed and evaluation text. The small original snippets below are a smoke probe, not a benchmark. For real selection, replace them with a source-disjoint validation corpus and reserve a separate untouched test set.\n", "\n", "Evaluate fluency, imagery, instruction behavior (if applicable), repetition and completeness using blinded human comparisons. Include Polish and general-language retention checks if those capabilities matter. Once candidate coefficients/checkpoint subsets are selected on validation, evaluate the final choice on test only once. Do not choose weights after seeing test results." ] }, { "cell_type": "code", "execution_count": null, "id": "68f44566", "metadata": {}, "outputs": [], "source": [ "import torch\n", "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "probe_texts = [\n", " \"The tram crossed the bridge before sunrise. In the bakery, someone was arranging cups beside a warm oven.\",\n", " \"The moon rests on the window sill.\\nA folded letter keeps its light.\\nThe house is quiet on the hill.\\nThe river carries on through night.\"\n", "]\n", "openings = [\"The night\", \"On the shore\"]\n", "results = {}\n", "RUN_EVALUATION = False\n", "if RUN_EVALUATION:\n", " assert OUTPUT.exists(), \"Run the merge first\"\n", " sources = {f\"step_{s}\": hf_hub_download(REPO, f\"wagi_{s}.pt\", revision=REVISION) for s in STEPS}\n", " for label, path in {**sources, \"equal_average\": str(OUTPUT)}.items():\n", " candidate = NativeCheckpoint(path, ROOT / \"tokenizer.json\", device=DEVICE)\n", " results[label] = {\"probe\": candidate.evaluate(probe_texts),\n", " \"samples\": {p: candidate.generate(p, tokens=32, seed=1234) for p in openings}}\n", " print(label, json.dumps(results[label], indent=2))\n", " del candidate\n", " gc.collect()\n", " if DEVICE == \"cuda\": torch.cuda.empty_cache()\n", " Path(\"outputs/merge_comparison.json\").write_text(json.dumps(results, indent=2))" ] }, { "cell_type": "markdown", "id": "54a0e5dc", "metadata": {}, "source": [ "## Next experiments\n", "\n", "Compare equal averages of the last 2 versus last 3 checkpoints, then a small validation-selected set of nonnegative weights. Keep the candidate count small and report all tried recipes. Averaging checkpoints from a shared trajectory can smooth parameter noise, but a constant-learning-rate run, changes in data, and checkpoints 5,000 updates apart can still yield a worse model. It is not automatically stochastic weight averaging (SWA), which describes a particular collection/training procedure, and it is not “model soup” evidence by itself.\n", "\n", "The output can be loaded by `NativeCheckpoint`, evaluated, further trained with a fresh optimizer, or published as a separate derived model with its merge recipe. Existing poetry adapters were trained against update 45k: applying them to this averaged base changes their reference and is a separate unvalidated experiment.\n", "\n", "See [validation and local pilot results](AVERAGING_RESULTS.md) for what was actually run. This notebook does not silently overwrite the released poetry model." ] }, { "cell_type": "markdown", "id": "8a403b7d", "metadata": {}, "source": [ "## References\n", "\n", "- [PyTorch weight averaging documentation](https://docs.pytorch.org/docs/stable/generated/torch.optim.swa_utils.AveragedModel.html): equal and custom weight averages.\n", "- [Latest Weight Averaging paper](https://arxiv.org/abs/2209.14981): averaging recent checkpoints along a training trajectory. Its reported results do not establish results for Slayer.\n", "- [Pinned Slayer checkpoint archive](https://huggingface.co/SlayerLab/Slayer1B-1.09-checkpoints/tree/32a7304dc2208acb3fb4a6e957498116552a4b18): source weights and SHA256 manifest.\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 5}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Averaging 45k, 50k and 55k: measured pilot
An actual full native checkpoint was created locally on 18 November 2026:
`θ_average = (θ_45000 + θ_50000 + θ_55000) / 3`.
All three sources came from archive revision `32a7304dc2208acb3fb4a6e957498116552a4b18`. Source checksums, configs, tensor names/shapes/dtypes, finite values and embedding tying passed. The output is FP32, with no optimizer state; independent arithmetic spot checks and native-model reload/generation also passed. Its SHA256 is `05c8dadf591ff3c642ce9ac2c737b3ade9ab887c679c722e6d5e6787f82b2e8e`. Recipe/provenance: [average-45k-55k.merge.json](average-45k-55k.merge.json).
The full candidate weights are a local experiment, **not part of the published poetry adapter or a newly released benchmark-winning model**. Reproduce them with notebook 04 or `python tutorials/average_checkpoints.py --steps 45000 50000 55000 --output outputs/slayer1b-average.pt`.
## Tiny text probe
Two original English snippets (one prose, one verse), totaling **64 predicted tokens** including boundaries, evaluated with the same tokenizer and BF16 CPU loader. These snippets were used only for this smoke probe. They are not a representative validation corpus, benchmark, decontamination guarantee or literary-quality assessment.
| Candidate | Probe CE | Probe perplexity || --- | ---: | ---: || step_45000 | 3.844746 | 46.746803 || step_50000 | 3.757317 | 42.833363 || step_55000 | 3.834984 | 46.292690 || equal_average | 3.774177 | 43.561625 |
**Interpretation:** On this tiny probe, the average predicts the text better than the 45k and 55k sources, but worse than the 50k source. This does not establish a practical benefit over selecting a single checkpoint. No coefficient sweep or held-out benchmark was performed.
## Matched generation samples
Two openings, seed 1234, temperature 1, top-k 50, maximum 32 new tokens, no repetition penalty and no forced minimum length. These settings are shared across all four candidates here; they differ from the original poetry experiment's sampler. All outputs below are complete recorded outputs; cap truncation is visible. Statements in the generated prose have not been fact-checked.
### Opening: `The night`
**step_45000**
```textThe night before the test was long and arduous. With his bag on his back, and the backpacks packed with other gear, it took him over an```
**step_50000**
```textThe night before the elections last year, a white woman standing on a rope in front of a crowd, holding a torch, said, “Our future is in the```
**step_55000**
```textThe night before the deadline, the Supreme Court asked why an eight-year-old is being convicted for a crime she probably never committed, the New York Post```
**equal_average**
```textThe night before the deadline, the Supreme Court asked justices to hear oral arguments from nine judges on a case involving an African American, a young black woman, being```
### Opening: `On the shore`
**step_45000**
```textOn the shore of the Marmara Sea, on the western shore of Asia Minor, is a mound called Troy. The Marmara Sea is the smallest```
**step_50000**
```textOn the shore of the Marmara Sea, on the western shore of Asia Minor, is located Izmir, Turkey. The city was founded in 1825 by```
**step_55000**
```textOn the shore of the Marmara, a small Turkish village whose name has no meaning, is a mansion that is almost 40 years old. The mansion, now```
**equal_average**
```textOn the shore of the Marmara Sea, on the western edge of Asia Minor, is a mound that is almost 40 m high and 1.6 m wide```
The averaged model remains a general prose continuation model in these samples. It has not acquired the poetry adapter's style just by averaging general checkpoints. The outputs do not provide evidence of stronger coherence, factual accuracy or literary quality.
## What to do next
Compare last-two and last-three averages on a meaningful validation corpus and a fixed multilingual/general/poetry prompt suite, including the best individual source. Hide checkpoint identities for human ratings. Choose the recipe using validation only, then measure the final choice on an untouched test set. Publish all attempted recipes and raw samples. A narrow pilot improvement is insufficient to name an average the new default.
References: [PyTorch parameter averaging](https://docs.pytorch.org/docs/stable/generated/torch.optim.swa_utils.AveragedModel.html), [Latest Weight Averaging](https://arxiv.org/abs/2209.14981). These motivate experiments; their results are not Slayer results.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# Train the Slayer1B-1.09 base model
These notebooks live with **SlayerLab/Slayer1B-1.09** and start from its original update-45,000 base checkpoint. They include their own loader, tokenizer and training code. You do not need to download or load the poetry adapter.
| Notebook | Objective | What changes || --- | --- | --- || [00 · Compare generations](00_generation_comparison.ipynb) | Read an existing CPT case study | No training; inspect matched parent/adapted samples || [01 · CPT](01_cpt.ipynb) | Predict next tokens in raw domain text | Loss on every target token || [02 · SFT](02_sft.ipynb) | Learn prompt → response examples | Loss on response tokens and EOS only || [03 · RL](03_rl.ipynb) | Sample, score and update behavior | REINFORCE with a leave-one-out baseline and frozen-parent KL || [04 · Checkpoint averaging](04_checkpoint_averaging.ipynb) | Combine compatible full checkpoints | FP32 weighted arithmetic average; no optimizer updates |
The three training lessons independently attach native LoRA adapters to the frozen original base. LoRA is the parameter-update method; CPT, SFT and RL are different learning objectives. Start a fresh kernel for each lesson. The toy examples use verse to stay easy to inspect; replace them with rights-cleared domain text, prompt/response pairs or an appropriate reward for your task.
## Open in Jupyter or Colab
Download an `.ipynb` above and open it in JupyterLab or VS Code. In Google Colab, use **File → Upload notebook** and choose the downloaded file. Select a CUDA GPU runtime for practical training speed. Notebook 00 needs no GPU.
Each notebook installs dependencies and downloads its tutorial support files **from this base-model repository**. When you load the training model, the loader separately downloads and SHA256-checks the pinned native base checkpoint (about 4.3 GB). The model architecture is pinned to a specific source revision; review downloaded Python code before running it. This uses native Slayer PyTorch code, not Transformers/PEFT.
For local use:
```bashhf download SlayerLab/Slayer1B-1.09 --include 'tutorials/*' --local-dir Slayer1B-trainingpython -m pip install -r Slayer1B-training/tutorials/requirements.txtjupyter lab Slayer1B-training/tutorials```
Run setup/loading cells, inspect the examples and set `RUN_TRAINING=True` to enable a short training exercise. For notebook 04, the equivalent switches are `RUN_MERGE` and `RUN_EVALUATION`. No notebook provisions infrastructure or starts a paid GPU.
The teaching configuration uses short contexts and microbatch 1. CUDA BF16 is used; actual memory requirements depend on runtime, context and rollout length. Reduce context or rollout length if necessary. A universal memory-fit guarantee has not been measured.
## Workflow
1. Freeze your validation prompts and data before training. Capture parent generations with fixed sampling settings.2. Choose CPT for raw domain text, SFT for explicit request/response behavior, or RL for a reward you can meaningfully validate.3. Inspect the exact tokens that contribute to the objective. For SFT, verify prompt labels are ignored; for RL, verify sampling and scored probabilities describe the same policy.4. Run a small update, inspect gradients/loss and read samples before scaling.5. Compare held-out outputs for fluency, coherence, instruction adherence, repetition and completeness. Use blinded human comparisons for subjective quality.6. Save an adapter as a separate artifact, keeping the parent immutable. Record data, revisions, settings and actual measurements.
These lessons default to independent experiments so their effects are attributable. You may later continue SFT from a CPT adapter, but that is a new experiment requiring a deliberate adapter load and a documented reference choice for RL; running the lessons in sequence does not automatically compose them.
## Generate from your saved adapter
The notebooks write adapters under `outputs/` relative to the notebook's working directory. With a local download, run from `Slayer1B-training/tutorials/`, where notebook-created `outputs/` is stored:
```bashpython runtime/generate.py --adapter outputs/sft_adapter.pt --opening $'Request: Write two lines about the moon.\nPoem:\n' --tokens 64```
The inference CLI selects CUDA or CPU and uses its documented top-k/repetition defaults. The teaching sampler is unfiltered temperature-1 sampling to keep RL rollouts and log probabilities consistent. Use one identical sampler across checkpoints in a given comparison.
## What is measured, and what is illustrative?
The poetry CPT case study in notebook 00 is a separately published adaptation, illustrated by the three archived parent/poetry sample pairs. Copies of those sample/metric artifacts are included under `runtime/` for display; the training lessons do not load the poetry weights.
The short SFT dataset and verse-form RL reward are teaching examples. A high form score can reward nonsense. No SFT/RL quality win, literary improvement, Colab end-to-end run or production scaling result is claimed. The small known-shape and actual 1B-model smoke checks are recorded in [VALIDATION.md](VALIDATION.md).
[slayer_training.py](slayer_training.py) contains the actual loops and strict input/config models. They provide no distributed training, full optimizer resume, large-corpus memory mapping or validation scheduler. Adapter checkpoints are for inference, not exact training resume. Use [the averaging report](AVERAGING_RESULTS.md) to see why a technically valid merge is not automatically a better model.123456789101112131415161718192021222321e0fc6608f924ba6d8db428b1e9098f6dcdc835bd421a0118d129eb249f14a3 00_generation_comparison.ipynb69af0389845831fa8b0050ca38dc6299a01851c50c0cf5dc476144b8db3d0618 01_cpt.ipynbce962a86411d174e52bc424e1cfcd80e80e194497e421acfd111643939c5fbdb 02_sft.ipynb84cde1a82c26b0f6e64b57b66b445deb041f580316754c99a92ad5de339fbaf7 03_rl.ipynb348330e9719eb506966320061576250f739aa5975c63a38bc7eadce255038395 04_checkpoint_averaging.ipynb4d21692fce7904458039a50166484898ee7d06225a0fb8ec166af31860e71350 AVERAGING_RESULTS.mdd0b2d4f50ea4cd22ed770fd9702d16c7744d2ebc1f2deaac2ad6d7f80e8e22b6 README.mdae8d9351a0a3150d8f610c728df1d847367225f6e20f75bf460e8a7e3d291fbf VALIDATION.md4cc8febda614a7d7f3026f2918b5cc439ef47d850f6985efef987c9f1eddb8de average-45k-55k.merge.jsonf120917201aeb2fd43152d6545dc088995e4fdd5c54b2b5a23a7635f1feb9500 average_checkpoints.py2fcb006089d1922a293a8faa01164aafaa6702239d5f0432ac891d48d6193e29 inspect_checkpoint.py798cd426d413db284bd51b7f0fa1d73eb35d774afdef445180b7758bc9619ec8 merge-comparison.json344c432a8514e06bf6d6251732dda4d735c6bbef5cff1eebd85a61f41beceb5b requirements.txt81b7853aecdd181bf57310e15d70ccb06efb8c147941184da8b1cded1257f2ed runtime/baseline-samples.json20a506ff7e7914817599b09f0f7bfc912d1fb849b92b05f4ccd62da36bc9735f runtime/common.py7e087ba531e6a7ed7a74a9ffd27dac04f3888f8f2c8af4377da5a9469beb89e6 runtime/generate.py966fca0f426ac7a978a647370ff95c5bd0c335d7ae9fc3561e0d49f8a044a514 runtime/lora.pyb9f85fa2062f4412b8cbd452cb5212308623a0971cacc1e4b6377ecb94571633 runtime/recipe.json73791725ffea6aa57f35d85034eb542119024ebe811b725e1f9f0c2f0f9f6d1c runtime/result.jsonc859166dbd3e67c0247635939d0b0bb1f4b5802a604bedf9f63198782d04c12f runtime/samples.json2e67257887e4c61468bd5d756ec96178980fe35afa8c48e590e41b8a875ebed5 runtime/sampling.py0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd runtime/tokenizer.json28b2c929e947622ef1f96cd352c50d9df23796ea240b15bd0197c912342edf32 slayer_training.py12345678910111213141516171819202122# What was checked
On 18 November 2026, locally on CPU with PyTorch 2.10.0:
- Loaded the actual pinned Slayer1B-1.09 update-45,000 checkpoint and verified its checksum.- Completed one native 1B-model CPT optimizer update (16-token context). Adapter weights changed, and frozen base parameters had no gradients. Observed training CE: 3.864333.- Verified the SFT mask includes the first response token and final EOS, then completed one real-model response-only SFT update. Observed response CE: 4.256570.- Completed one on-policy RL optimizer update using two 2-token rollouts. A string-length diagnostic reward deliberately produced unequal rewards (7 and 8), exercising nonzero advantages. Parent-reference KL was 0 at the reset policy. This tests execution, not learning quality or the notebook's verse-form reward.- Saved an inference adapter checkpoint.- Executed the generation-comparison notebook using local copies of the published artifacts; its displayed sample/metric outputs are embedded. Portable Hub bootstrap cells were restored afterward.- Validated all notebook schemas and parsed their ordinary Python cells.
The full default 10-step CPT/SFT lessons and 3-update verse-form RL lesson have not been run as quality experiments. No GPU memory fit, training improvement, human preference gain, Colab end-to-end execution, or distributed scaling result is claimed. Training notebooks contain no invented training outputs.
## Checkpoint averaging
- Inspected the live archive and pinned revision `32a7304dc2208acb3fb4a6e957498116552a4b18`.- Downloaded 45k, 50k and 55k weights; matched all three SHA256 values to the archive manifest.- Confirmed exact source configs, state names/shapes/dtypes, finite values and tied embeddings; produced their equal FP32 average locally.- Reloaded the full output, independently spot-checked arithmetic for embedding, attention and normalization tensors, and verified shared embedding/head storage.- Checked the helper on small known weighted inputs, including integer-buffer preservation and rejection of negative coefficients and incompatible configs.- See `AVERAGING_RESULTS.md` and `merge-comparison.json` for the measured pilot; these do not establish a benchmark improvement.1234567891011121314151617181920212223242526272829303132{ "method": "normalized arithmetic weight average in FP32", "sources": [ { "file": "wagi_45000.pt", "sha256": "e6dd131a1e7b6a25d0421260bb8a24a52a95f48b01cfecb183987c65bb97d827", "step": 45000, "weight": 0.3333333333333333 }, { "file": "wagi_50000.pt", "sha256": "4a913162116e78e497399b20cccaf896aa79663f7bbca31a6a7964b72001b20f", "step": 50000, "weight": 0.3333333333333333 }, { "file": "wagi_55000.pt", "sha256": "d398310c12cc5b71e5e09fcf63c99153dc516e496002d4c6a713512fd6fa6da6", "step": 55000, "weight": 0.3333333333333333 } ], "step_note": "0 denotes a derived model, not an optimizer update", "output_sha256": "05c8dadf591ff3c642ce9ac2c737b3ade9ab887c679c722e6d5e6787f82b2e8e", "repo": "SlayerLab/Slayer1B-1.09-checkpoints", "revision": "32a7304dc2208acb3fb4a6e957498116552a4b18", "source_filenames": [ "wagi_45000.pt", "wagi_50000.pt", "wagi_55000.pt" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Average compatible native Slayer full checkpoints in FP32, with provenance."""from pathlib import Pathimport argparse,hashlib,json,mathimport torchfrom huggingface_hub import hf_hub_downloadREPO='SlayerLab/Slayer1B-1.09-checkpoints'REVISION='32a7304dc2208acb3fb4a6e957498116552a4b18'
def sha256(path): h=hashlib.sha256() with open(path,'rb') as f: for chunk in iter(lambda:f.read(8*1024*1024),b''):h.update(chunk) return h.hexdigest()
def average(paths,weights,output): if not paths or len(paths)!=len(weights):raise ValueError('One weight per checkpoint is required') if not all(math.isfinite(w) and w>=0 for w in weights) or sum(weights)<=0:raise ValueError('Need finite nonnegative weights with positive total') if len(set(map(str,paths)))!=len(paths):raise ValueError('Duplicate checkpoint paths') weights=[w/sum(weights) for w in weights] accumulator={};config=None;keys=None;dtypes={};sources=[] for path,weight in zip(paths,weights): checkpoint=torch.load(path,map_location='cpu',weights_only=True,mmap=True) state=checkpoint['model'] if config is None: config=dict(checkpoint['config']);keys=set(state) elif checkpoint['config']!=config or set(state)!=keys:raise ValueError('Configuration or parameter keys differ') if not torch.equal(state['tok.weight'],state['head.weight']):raise ValueError('Source embeddings/head are not tied-equivalent') for key,tensor in state.items(): if not isinstance(tensor,torch.Tensor):raise ValueError('Expected tensor state') if key not in accumulator: dtypes[key]=tensor.dtype accumulator[key]=torch.zeros_like(tensor,dtype=torch.float32) if tensor.is_floating_point() else tensor.clone() elif accumulator[key].shape!=tensor.shape or dtypes[key]!=tensor.dtype:raise ValueError(f'Shape/dtype mismatch: {key}') if tensor.is_floating_point(): if not torch.isfinite(tensor).all():raise ValueError(f'Nonfinite source: {key}') accumulator[key].add_(tensor,alpha=weight) elif not torch.equal(accumulator[key],tensor):raise ValueError(f'Nonfloat buffers differ: {key}') sources.append({'file':Path(path).name,'sha256':sha256(path),'step':int(checkpoint['step']),'weight':weight}) del state,checkpoint print('Accumulated',sources[-1],flush=True) for key,tensor in accumulator.items(): if tensor.is_floating_point() and not torch.isfinite(tensor).all():raise ValueError('Nonfinite average') # Preserve aliasing explicitly in the output checkpoint. accumulator['head.weight']=accumulator['tok.weight'] merged={'model':accumulator,'config':config,'step':0, 'merge_metadata':{'method':'normalized arithmetic weight average in FP32','sources':sources, 'step_note':'0 denotes a derived model, not an optimizer update'}} output=Path(output);output.parent.mkdir(parents=True,exist_ok=True) temp=output.with_suffix(output.suffix+'.tmp');torch.save(merged,temp);temp.replace(output) metadata={**merged['merge_metadata'],'output_sha256':sha256(output)} output.with_suffix('.merge.json').write_text(json.dumps(metadata,indent=2)+'\n') return metadata
def from_hub(steps,weights,output,revision=REVISION): sums=Path(hf_hub_download(REPO,'SHA256SUMS',revision=revision)).read_text() expected={line.split()[1]:line.split()[0] for line in sums.splitlines() if line.strip()} paths=[] for step in steps: name=f'wagi_{step}.pt' path=hf_hub_download(REPO,name,revision=revision) if sha256(path)!=expected[name]:raise ValueError(f'Checksum mismatch: {name}') paths.append(path) metadata=average(paths,weights,output) metadata.update(repo=REPO,revision=revision,source_filenames=[f'wagi_{s}.pt' for s in steps]) Path(output).with_suffix('.merge.json').write_text(json.dumps(metadata,indent=2)+'\n') return metadata
if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--steps',type=int,nargs='+',default=[45000,50000,55000]);p.add_argument('--weights',type=float,nargs='+');p.add_argument('--output',default='outputs/slayer1b-average.pt');a=p.parse_args() print(json.dumps(from_hub(a.steps,a.weights or [1.]*len(a.steps),a.output),indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Load a native full checkpoint for fixed-setting generation and text CE."""from pathlib import Pathfrom types import SimpleNamespaceimport hashlib,importlib.util,mathimport torchimport torch.nn.functional as Ffrom huggingface_hub import hf_hub_downloadfrom tokenizers import Tokenizer
class NativeCheckpoint: def __init__(self,path,tokenizer_path,device='cpu'): source=hf_hub_download('SlayerLab/Slayer1B-1.09','train_gpt_ref_r24_2.py',revision='58d8f359c1fdd887f1b7344ec52c5511c111f790') assert hashlib.sha256(Path(source).read_bytes()).hexdigest()=='46f83b51fcec18ffc3273d80fb9eab29e182c52d8667800dab27b80f7ff18afc' spec=importlib.util.spec_from_file_location('slayer_merge_arch',source);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) checkpoint=torch.load(path,map_location='cpu',weights_only=True,mmap=True) config=SimpleNamespace(**checkpoint['config']);config.act_ckpt=False;config.loss_chunk=0;config.z_loss=0. with torch.device('meta'):model=module.GPT(config.vocab,config.n_layer,config.n_embd,config.n_head,config.block,config) model.load_state_dict(checkpoint['model'],strict=True,assign=True);model.head.weight=model.tok.weight self.model=model.to(device=device,dtype=torch.bfloat16).eval();self.device=device assert hashlib.sha256(Path(tokenizer_path).read_bytes()).hexdigest()=='0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd' self.tokenizer=Tokenizer.from_file(str(tokenizer_path))
@torch.no_grad() def generate(self,prompt,tokens=32,seed=1234): torch.manual_seed(seed);seq=[0]+self.tokenizer.encode(prompt,add_special_tokens=False).ids;out=[] for i in range(tokens): with torch.autocast(self.device,dtype=torch.bfloat16):z,_=self.model(torch.tensor([seq[-1024:]],device=self.device)) logits=z[0,-1].float() # Fixed top-k 50, temperature 1; no forced minimum length. logits[logits<logits.topk(50).values[-1]]=-float('inf') token=int(torch.multinomial(logits.softmax(-1),1)) if token==0:break seq.append(token);out.append(token) return prompt+self.tokenizer.decode(out)
@torch.no_grad() def evaluate(self,texts,context=128): total=0.;count=0 for text in texts: ids=[0]+self.tokenizer.encode(text,add_special_tokens=False).ids+[0] for start in range(0,len(ids)-1,context): chunk=ids[start:start+context+1] if len(chunk)<2:continue x=torch.tensor([chunk[:-1]],device=self.device);y=torch.tensor(chunk[1:],device=self.device) with torch.autocast(self.device,dtype=torch.bfloat16):z,_=self.model(x) total+=float(F.cross_entropy(z[0].float(),y,reduction='sum'));count+=len(y) if not count:raise ValueError('Empty evaluation') ce=total/count;return {'ce':ce,'perplexity':math.exp(ce),'tokens':count}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253{ "note": "Two original illustrative text probes, not a benchmark or quality verdict. BF16 CPU; seed 1234; top-k 50; temperature 1; no repetition penalty or EOS suppression; 32-token cap.", "probe_texts": [ "The tram crossed the bridge before sunrise. In the bakery, someone was arranging cups beside a warm oven.", "The moon rests on the window sill.\nA folded letter keeps its light.\nThe house is quiet on the hill.\nThe river carries on through night." ], "results": { "step_45000": { "probe": { "ce": 3.8447458744049072, "perplexity": 46.74680328213153, "tokens": 64 }, "samples": { "The night": "The night before the test was long and arduous. With his bag on his back, and the backpacks packed with other gear, it took him over an", "On the shore": "On the shore of the Marmara Sea, on the western shore of Asia Minor, is a mound called Troy. The Marmara Sea is the smallest" } }, "step_50000": { "probe": { "ce": 3.757317304611206, "perplexity": 42.833362843113264, "tokens": 64 }, "samples": { "The night": "The night before the elections last year, a white woman standing on a rope in front of a crowd, holding a torch, said, \u201cOur future is in the", "On the shore": "On the shore of the Marmara Sea, on the western shore of Asia Minor, is located Izmir, Turkey. The city was founded in 1825 by" } }, "step_55000": { "probe": { "ce": 3.834984064102173, "perplexity": 46.29268994649519, "tokens": 64 }, "samples": { "The night": "The night before the deadline, the Supreme Court asked why an eight-year-old is being convicted for a crime she probably never committed, the New York Post", "On the shore": "On the shore of the Marmara, a small Turkish village whose name has no meaning, is a mansion that is almost 40 years old. The mansion, now" } }, "equal_average": { "probe": { "ce": 3.774176597595215, "perplexity": 43.56162479784854, "tokens": 64 }, "samples": { "The night": "The night before the deadline, the Supreme Court asked justices to hear oral arguments from nine judges on a case involving an African American, a young black woman, being", "On the shore": "On the shore of the Marmara Sea, on the western edge of Asia Minor, is a mound that is almost 40 m high and 1.6 m wide" } } }}1234567torch>=2.4huggingface_hub>=0.26tokenizers>=0.20pydantic>=2numpytqdmjupyterlab1234567891011121314151617181920212223242526272829303132[ { "opening": "The night", "text": "The night-crawlers of the genus Trapezias are crustaceans that spend almost all of their life lives in burrows that they excavate. At night the crustaceans feed on insects they can hide under objects and in crevices. Most species are nocturnal, but there is also one day-time dwelling species with an unusual behaviour: it does not burrow at all during the daytime, and wakes up in the morning to res", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }, { "opening": "On the shore", "text": "On the shore of a lake or in a river, there are numerous plant communities. There could be grasses on the surface or sedges on the bottom. Mosses and the mushrooms that grow from them add colour to the scene and may attract some insects. If you look closely, there usually is some sort of creature beneath the vegetation too; often they can’t see because it is below the water level, but if your eyes are sufficiently sharp, you will spot an occasional", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }, { "opening": "A small bird", "text": "A small bird with a short tail. The red-winged Blackbird is a popular game bird and is found wherever there are people. Often they will be seen in backyards, fields or woodland edge all over the world, but is equally at home in farmland fields, forest margins and shrubby areas. It has small grey/brown body, yellowish eyes on a green black background, yellow wing patches, and a white patch above its chest and a red", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }]12345678910111213141516171819202122232425"""Pinned native Slayer model acquisition and LoRA attachment."""import hashlib,importlib.util,json,pathlibfrom types import SimpleNamespaceimport torchfrom huggingface_hub import hf_hub_downloadfrom lora import inject
def load_base(recipe,device='cuda'): b=recipe['base'];path=hf_hub_download(b['archive_repo'],b['checkpoint'],revision=b['archive_revision']) sums=pathlib.Path(hf_hub_download(b['archive_repo'],'SHA256SUMS',revision=b['archive_revision'])).read_text() expected={s.split()[1]:s.split()[0] for s in sums.splitlines() if s.strip()}[b['checkpoint']] with open(path,'rb') as f:actual=hashlib.file_digest(f,'sha256').hexdigest() if actual!=expected:raise ValueError('Base checkpoint SHA256 mismatch') trainer_path=hf_hub_download(b['model_repo'],'train_gpt_ref_r24_2.py',revision=b['trainer_revision']) spec=importlib.util.spec_from_file_location('slayer_native_trainer',trainer_path);mod=importlib.util.module_from_spec(spec);spec.loader.exec_module(mod) state=torch.load(path,map_location='cpu',weights_only=True,mmap=True);cfg=SimpleNamespace(**state['config']) with torch.device('meta'):model=mod.GPT(cfg.vocab,cfg.n_layer,cfg.n_embd,cfg.n_head,cfg.block,cfg) model.load_state_dict(state['model'],strict=True,assign=True);model.head.weight=model.tok.weight;del state model=model.to(device=device,dtype=torch.bfloat16);cfg.act_ckpt=recipe['training'].get('activation_checkpointing',True);cfg.loss_chunk=recipe['training'].get('loss_chunk',128);cfg.z_loss=0. return model,{'base_sha256':actual,'trainer_sha256':hashlib.sha256(pathlib.Path(trainer_path).read_bytes()).hexdigest(),'native_config':vars(cfg)}
def attach(model,recipe): c=recipe['lora'];names=inject(model,c['rank'],c['alpha'],c['dropout'],c['targets']) if len(names)!=100:raise ValueError(f'Expected 100 LoRA linears, found {len(names)}') return names1234567891011121314151617181920212223"""Generate a continuation with the native base plus a trusted poetry adapter."""import argparse,contextlib,hashlib,json,pathlib,sysimport torchfrom tokenizers import Tokenizerfrom common import load_base,attachsys.path.insert(0,str(pathlib.Path(__file__).resolve().parents[1]))from sampling import penalize_repetitionp=argparse.ArgumentParser();p.add_argument('--adapter',required=True);p.add_argument('--tokenizer',default=str(pathlib.Path(__file__).with_name('tokenizer.json')));p.add_argument('--opening',default='The night');p.add_argument('--tokens',type=int,default=256);p.add_argument('--temperature',type=float,default=1.0);p.add_argument('--repetition-penalty',type=float,default=1.1);p.add_argument('--seed',type=int,default=1234);a=p.parse_args()assert a.temperature>0 and a.tokens>0ck=torch.load(a.adapter,map_location='cpu',weights_only=True)assert hashlib.sha256(pathlib.Path(a.tokenizer).read_bytes()).hexdigest()==ck['tokenizer_sha256']device='cuda' if torch.cuda.is_available() else 'cpu';model,_=load_base(ck['recipe'],device);attach(model,ck['recipe'])expected={n for n,p in model.named_parameters() if p.requires_grad};assert set(ck['adapters'])==expectedmodel.load_state_dict(ck['adapters'],strict=False);model.eval();t=Tokenizer.from_file(a.tokenizer);torch.manual_seed(a.seed)seq=[0]+t.encode(a.opening,add_special_tokens=False).ids;generated=[]for i in range(a.tokens): with torch.no_grad(),torch.autocast(device,dtype=torch.bfloat16):logits,_=model(torch.tensor([seq[-1024:]],device=device)) logits=logits[:,-1].float()/a.temperature;penalize_repetition(logits,seq,a.repetition_penalty,first_text_id=1) if i<16:logits[:,0]=-float('inf') logits[logits<logits.topk(50).values[:,-1:]]=-float('inf');n=int(torch.multinomial(logits.softmax(-1),1)) if n==0:break seq.append(n);generated.append(n)print(a.opening+t.decode(generated))12345678910111213141516171819202122"""Native nn.Linear LoRA adapters; base weights are frozen and preserved."""import mathimport torchfrom torch import nnfrom torch.nn import functional as Fclass LoRALinear(nn.Module): def __init__(self,base,rank=32,alpha=32,dropout=0.): super().__init__();self.base=base;self.scaling=alpha/rank;self.dropout=nn.Dropout(dropout) self.A=nn.Parameter(torch.empty(rank,base.in_features,dtype=torch.float32,device=base.weight.device)) self.B=nn.Parameter(torch.zeros(base.out_features,rank,dtype=torch.float32,device=base.weight.device));nn.init.kaiming_uniform_(self.A,a=math.sqrt(5)) self.base.requires_grad_(False) def forward(self,x): return self.base(x)+(F.linear(F.linear(self.dropout(x),self.A),self.B)*self.scaling).to(x.dtype)def inject(model,rank,alpha,dropout,targets): model.requires_grad_(False);names=[] for name,module in list(model.named_modules()): if isinstance(module,nn.Linear) and name.startswith('blocks.') and any(name.endswith('.'+s) for s in targets): parent,leaf=name.rsplit('.',1);setattr(model.get_submodule(parent),leaf,LoRALinear(module,rank,alpha,dropout));names.append(name) if not names:raise ValueError('No LoRA target modules matched') return names
def adapter_state(model):return {n:p.detach().cpu() for n,p in model.named_parameters() if p.requires_grad}12345678910111213141516171819202122232425262728293031323334353637383940{ "base": { "model_repo": "SlayerLab/Slayer1B-1.09", "model_revision": "2507f7129527025c559b7ec5835f2b96aa3a51c7", "archive_repo": "SlayerLab/Slayer1B-1.09-checkpoints", "archive_revision": "33d2faef5ee09de7baa2feb65131e8e9e2c0c008", "checkpoint": "wagi_45000.pt", "trainer_revision": "58d8f359c1fdd887f1b7344ec52c5511c111f790", "tokenizer_revision": "5f854a0cc7160594d54d1788d37a44e8ebabe16c" }, "lora": { "rank": 32, "alpha": 32, "dropout": 0.0, "targets": [ "qkv", "proj", "mlp.gate", "mlp.up", "mlp.down" ] }, "training": { "seed": 20261117, "context": 1024, "micro_batch": 16, "grad_accum": 1, "epochs": 1, "learning_rate": 0.0001, "min_lr_ratio": 0.1, "warmup_fraction": 0.05, "weight_decay": 0.01, "grad_clip": 1.0, "eval_every": 200, "save_every": 20, "validation_tokens": 65536, "activation_checkpointing": false, "loss_chunk": 256 }}12345678910111213141516171819202122{ "processed_tokens": 37657600, "updates": 2299, "selected_update": 2299, "baseline_validation": { "ce": 3.4131230413913727, "perplexity": 30.35991161803797, "tokens": 65536 }, "selected_full_validation": { "ce": 3.289073363389119, "perplexity": 26.818001596520336, "tokens": 827392 }, "test": { "ce": 3.2436408333964164, "perplexity": 25.62685521306139, "tokens": 788480 }, "elapsed_seconds": 421.2775601008907, "peak_allocated_GiB": 31.86785888671875}1234567891011121314151617181920212223242526272829303132[ { "opening": "The night", "text": "The night-crowd of the streets\nFoamed and frothed to and fro;\nAnd many a wiry streetman in white was shaded\nBy the flurry: all he felt had been washed with his blood.\n\nAnd lo, the sun had risen; yet still\nHis smile seemed sad, with no change in his eyes for sorrow\n— Thrust from behind, and backward again,\nHe heard his old", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }, { "opening": "On the shore", "text": "On the shore of a deep bay.\nIt's a lonely island;--\nThe island is small.", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }, { "opening": "A small bird", "text": "A small bird that went forth\nAnd sang from its nest so long\nIt was not a song of woe,\nNor a warlike tirpe’r the same.", "temperature": 1.0, "top_k": 50, "repetition_penalty": 1.1, "seed": 1234, "max_new_tokens": 96, "min_new_tokens": 16 }]12345678910111213"""Sign-aware token repetition penalty, excluding document-control token IDs."""import mathimport torch
def penalize_repetition(logits,token_ids,penalty=1.1,first_text_id=6): if not math.isfinite(penalty) or penalty<1:raise ValueError('repetition penalty must be finite and >= 1') if penalty==1:return logits seen=sorted({n for n in token_ids if first_text_id<=n<logits.shape[-1]}) if not seen:return logits ids=torch.tensor(seen,device=logits.device,dtype=torch.long) values=logits.index_select(-1,ids) logits.index_copy_(-1,ids,torch.where(values<0,values*penalty,values/penalty)) return logits123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Small, inspectable native Slayer LoRA teaching loops; not a production trainer."""from pathlib import Pathfrom contextlib import contextmanagerimport hashlib, json, randomimport torchimport torch.nn.functional as Ffrom pydantic import BaseModel, ConfigDict, Fieldfrom tokenizers import Tokenizerfrom common import load_base, attachfrom lora import adapter_state, LoRALinear
class Config(BaseModel): model_config = ConfigDict(extra='forbid', frozen=True, strict=True) context: int = Field(default=128, ge=8, le=1024) learning_rate: float = Field(default=1e-4, gt=0, le=0.01) seed: int = 42
class Example(BaseModel): model_config = ConfigDict(extra='forbid', frozen=True, strict=True) prompt: str = Field(min_length=1) response: str = Field(min_length=1)
class Workshop: def __init__(self, root, config=Config()): self.root=Path(root); self.config=config random.seed(config.seed); torch.manual_seed(config.seed) self.recipe=json.loads((self.root/'recipe.json').read_text()) self.recipe['training'].update(activation_checkpointing=True, loss_chunk=0) self.device='cuda' if torch.cuda.is_available() else 'cpu' self.model,self.provenance=load_base(self.recipe,self.device) attach(self.model,self.recipe) assert hashlib.sha256((self.root/'tokenizer.json').read_bytes()).hexdigest() == '0640d3bd3674d7a6e59c540d945a2ad275a12e1bcaeb6007c37a90751f9815dd' self.tokenizer=Tokenizer.from_file(str(self.root/'tokenizer.json')) self.params=[p for p in self.model.parameters() if p.requires_grad] self.optimizer=torch.optim.AdamW(self.params,lr=config.learning_rate) self.steps=0 print(f'{self.device}: {sum(p.numel() for p in self.params):,} trainable parameters')
def amp(self): return torch.autocast(self.device,dtype=torch.bfloat16) def ids(self,text): return self.tokenizer.encode(text,add_special_tokens=False).ids
@contextmanager def parent(self): """Disable native adapters without copying the 1B reference model.""" modules=[m for m in self.model.modules() if isinstance(m,LoRALinear)] scales=[m.scaling for m in modules] try: for m in modules:m.scaling=0. yield finally: for m,s in zip(modules,scales):m.scaling=s
def reset(self): """Independent lesson: zero B restores parent; reset optimizer as well.""" with torch.no_grad(): for m in self.model.modules(): if isinstance(m,LoRALinear):m.B.zero_() self.optimizer=torch.optim.AdamW(self.params,lr=self.config.learning_rate) self.steps=0
def update(self,loss): if not torch.isfinite(loss):raise ValueError('Nonfinite loss') self.optimizer.zero_grad(set_to_none=True);loss.backward() torch.nn.utils.clip_grad_norm_(self.params,1.,error_if_nonfinite=True) self.optimizer.step();self.steps+=1 return float(loss.detach())
def cpt(self,texts,steps=10): """All next tokens supervised, EOS boundaries; incomplete tail omitted.""" stream=[] for text in texts:stream += [0]+self.ids(text)+[0] n=self.config.context windows=[stream[i:i+n+1] for i in range(0,len(stream)-n,n)] if not windows:raise ValueError('Need at least context+1 tokens') self.model.train();history=[] for step in range(steps): z=torch.tensor([random.choice(windows)],device=self.device) with self.amp(): logits,_=self.model(z[:,:-1]);loss=F.cross_entropy(logits.float().reshape(-1,logits.size(-1)),z[:,1:].reshape(-1)) history.append(self.update(loss));print({'step':step+1,'cpt_ce':history[-1]}) return history
def encode_sft(self,example): """Separate encoding defines a stable boundary; no silent truncation.""" e=Example.model_validate(example) prompt=[0]+self.ids(e.prompt);response=self.ids(e.response)+[0] tokens=prompt+response if len(tokens)-1>self.config.context:raise ValueError('Example too long: shorten it or increase context') x=torch.tensor([tokens[:-1]],device=self.device) y=torch.tensor([tokens[1:]],device=self.device) # y[j] predicts tokens[j+1]; first response is tokens[len(prompt)]. y[:,:len(prompt)-1]=-100 return x,y
def sft(self,examples,steps=10): batches=[self.encode_sft(e) for e in examples] if not batches:raise ValueError('No SFT examples') self.model.train();history=[] for step in range(steps): x,y=random.choice(batches) with self.amp(): logits,_=self.model(x);loss=F.cross_entropy(logits.float().reshape(-1,logits.size(-1)),y.reshape(-1),ignore_index=-100) history.append(self.update(loss));print({'step':step+1,'response_ce':history[-1]}) return history
@torch.no_grad() def sample(self,prompt,max_new_tokens=48,seed=1234): """Unfiltered categorical sampling at temperature 1: on-policy for RL.""" self.model.eval();torch.manual_seed(seed) ids=[0]+self.ids(prompt);completion=[] if len(ids)+max_new_tokens>self.config.context:raise ValueError('Prompt + rollout exceeds context') for _ in range(max_new_tokens): with self.amp():logits,_=self.model(torch.tensor([ids],device=self.device)) t=int(torch.multinomial(logits[0,-1].float().softmax(-1),1)) ids.append(t);completion.append(t) if t==0:break return completion,self.tokenizer.decode(completion)
def rl(self,prompts,reward,updates=3,group_size=4,max_new_tokens=24,kl_beta=.02): """On-policy REINFORCE + leave-one-out baseline + full categorical KL.
One optimizer step per freshly sampled group. No PPO/GRPO clipping, replay, reward model, filtering or temperature/logprob mismatch. Reference is always the frozen parent (adapters disabled). """ if group_size<2:raise ValueError('group_size must be >=2') history=[] for u in range(updates): prompt=prompts[u%len(prompts)] rolls=[self.sample(prompt,max_new_tokens,self.config.seed+u*group_size+i) for i in range(group_size)] scores=torch.tensor([float(reward(text)) for _,text in rolls],device=self.device) if not torch.isfinite(scores).all():raise ValueError('Nonfinite reward') advantages=(scores-(scores.sum()-scores)/(group_size-1)).detach() self.optimizer.zero_grad(set_to_none=True) # Eval mode keeps rollout and scoring distributions identical. self.model.eval();pg_total=kl_total=0. for (completion,_),advantage in zip(rolls,advantages): prefix=[0]+self.ids(prompt);seq=prefix+completion x=torch.tensor([seq[:-1]],device=self.device) targets=torch.tensor(completion,device=self.device) start=len(prefix)-1 with torch.no_grad(),self.parent(),self.amp():ref,_=self.model(x) ref_logp=ref[0,start:].float().log_softmax(-1).detach();del ref with self.amp():logits,_=self.model(x) logp=logits[0,start:].float().log_softmax(-1) chosen=logp.gather(-1,targets[:,None]).squeeze(-1) # Sequence log probability (sum) is the REINFORCE estimator. pg=-advantage*chosen.sum() kl=(logp.exp()*(logp-ref_logp)).sum(-1).mean() loss=(pg+kl_beta*kl)/group_size if not torch.isfinite(loss):raise ValueError('Nonfinite RL loss') loss.backward();pg_total+=float(pg.detach())/group_size;kl_total+=float(kl.detach())/group_size torch.nn.utils.clip_grad_norm_(self.params,1.,error_if_nonfinite=True) self.optimizer.step();self.steps+=1 row={'update':u+1,'mean_reward':float(scores.mean()),'reward_std':float(scores.std(unbiased=False)), 'policy_loss':pg_total,'reference_kl':kl_total,'samples':[{'text':t,'reward':float(r)} for (_,t),r in zip(rolls,scores)]} history.append(row);print(json.dumps(row)) return history
def save(self,path): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) torch.save({'adapters':adapter_state(self.model),'recipe':self.recipe,'step':self.steps, 'provenance':self.provenance,'tokenizer_sha256':hashlib.sha256((self.root/'tokenizer.json').read_bytes()).hexdigest()},path) print('Saved',path)
def form_reward(text): """Toy observable form proxy, explicitly not literary quality.""" lines=[s.strip() for s in text.splitlines() if s.strip()] if not lines:return 0. four_lines=max(0.,1.-abs(len(lines)-4)/4) distinct=len(set(lines))/len(lines) length=min(len(text.split())/24,1.) return .5*four_lines+.25*distinct+.25*lengthREADME.md+14
tutorials/00_generation_comparison.ipynbAdded+268
tutorials/01_cpt.ipynbAdded+155
tutorials/02_sft.ipynbAdded+142
tutorials/03_rl.ipynbAdded+130
tutorials/04_checkpoint_averaging.ipynbAdded+157
tutorials/AVERAGING_RESULTS.mdAdded+86
tutorials/README.mdAdded+60
tutorials/SHA256SUMSAdded+23
tutorials/VALIDATION.mdAdded+22
tutorials/average-45k-55k.merge.jsonAdded+32
tutorials/average_checkpoints.pyAdded+70
tutorials/inspect_checkpoint.pyAdded+48
tutorials/merge-comparison.jsonAdded+53
tutorials/requirements.txtAdded+7
tutorials/runtime/baseline-samples.jsonAdded+32
tutorials/runtime/common.pyAdded+25
tutorials/runtime/generate.pyAdded+23
tutorials/runtime/lora.pyAdded+22
tutorials/runtime/recipe.jsonAdded+40
tutorials/runtime/result.jsonAdded+22
tutorials/runtime/samples.jsonAdded+32
tutorials/runtime/sampling.pyAdded+13
tutorials/runtime/tokenizer.jsonAdded
tutorials/slayer_training.pyAdded+174