{ "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", "ROOT = Path(snapshot_download(\"SlayerLab/Slayer1B-Poetry\", allow_patterns=[\n", " \"tokenizer.json\", \"tutorials/average_checkpoints.py\", \"tutorials/inspect_checkpoint.py\"\n", "]))\n", "sys.path.insert(0, str(ROOT / \"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 }