{ "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", "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": "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 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 the repository's `generate.py --adapter outputs/cpt_adapter.pt`. 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 }