Metadata-Version: 2.5
Name: baby-llm
Version: 0.2.0
Summary: A developer-first PyTorch engine for explicit, modular LLM training. Zero magic.
Project-URL: Homepage, https://github.com/700799/baby-llm
Project-URL: Repository, https://github.com/700799/baby-llm
Project-URL: Issues, https://github.com/700799/baby-llm/issues
Author: Baby LLM contributors
License-Expression: MIT
License-File: LICENSE
Keywords: dpo,fine-tuning,flash-attention,llm,lora,pytorch,sft,training,triton
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic>=2.7
Requires-Dist: torch>=2.3
Requires-Dist: typer>=0.12
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff==0.17.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: flash
Requires-Dist: flash-attn>=2.5.8; extra == 'flash'
Provides-Extra: gguf
Requires-Dist: gguf>=0.10; extra == 'gguf'
Requires-Dist: safetensors>=0.4; extra == 'gguf'
Provides-Extra: hf
Requires-Dist: safetensors>=0.4; extra == 'hf'
Requires-Dist: transformers<6,>=4.56; extra == 'hf'
Provides-Extra: triton
Requires-Dist: triton>=3.0; extra == 'triton'
Provides-Extra: yaml
Requires-Dist: pyyaml>=6.0; extra == 'yaml'
Description-Content-Type: text/markdown

# Baby LLM

[![CI](https://github.com/700799/baby-llm/actions/workflows/ci.yml/badge.svg)](https://github.com/700799/baby-llm/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue)
![License](https://img.shields.io/badge/license-MIT-green)

**A developer-first PyTorch engine for explicit, modular LLM training.**

Baby LLM trains language models with a loop you can read. No `Trainer` class, no
callback graph, no hidden hook order — a recipe is one Python file, the loop inside it is
~60 lines of raw PyTorch, and every config key maps to a line of code you can point at.

> The package is `baby-llm` on PyPI and imports as `baby_llm` (Python modules
> can't contain hyphens). The CLI is `baby-llm`, or the alias `babyllm`.

## Why this exists

Most training libraries are *configuration* surfaces: you describe what you want and a
framework assembles the loop. That's efficient right up until you need to change the
mechanics — and with LLMs, changing the mechanics is the job.

Say you want to drop in a fused Triton attention kernel, or clip gradients differently per
parameter group, or find out why memory spikes on step 2. In a high-level trainer you're
now reverse-engineering someone else's abstraction: which of eleven callbacks fires first,
whether `accelerator.backward()` already unscaled your gradients, what the config key
actually toggles three layers down. The code you need to understand is real; it's just not
in front of you.

Baby LLM inverts that. The things you're most likely to modify — the loop, the
attention kernel, gradient accumulation, the memory trade-offs — are the things written
out in plain sight:

- **The loop is the trainer.** `baby_llm/recipes/minimal_sft.py` is a file you read top
  to bottom, then edit. Forking a recipe is the supported way to change training.
- **Kernels are a registry, not a fork.** One `Attention` module with interchangeable
  execution paths — SDPA, FlashAttention-2/3, or a Triton kernel you register in five
  lines — switchable by a string, including on a live module for A/B tests.
- **Memory is a budget you set, not a mystery.** Gradient accumulation, activation
  checkpointing, and activation offloading are each one visible construct in the loop.
- **Mistakes fail at parse time, not step 40 000.** Configs are Pydantic V2 models with
  cross-field validators, so a bad GQA head count or a flash backend in `float32` is
  rejected before the GPU warms up.

This is aimed at people modifying training, not just running it: kernel work, custom
optimizers and backward passes, teaching, and debugging. See
[Status and limitations](#status-and-limitations) for what it deliberately isn't.

## Install

Requires **Python 3.11+**.

```bash
pip install baby-llm            # the engine and the tiny from-scratch recipe
pip install "baby-llm[hf]"      # + fine-tuning Hugging Face models, LoRA and DPO
```

The tutorial runs commands from a checkout, so clone the repo to follow along:

```bash
git clone https://github.com/700799/baby-llm baby-llm && cd baby-llm
pip install -e ".[dev,yaml,hf,gguf]"
```

`torch>=2.3` resolves to the default CUDA wheel, which is several GB. For CPU-only work,
install torch from PyTorch's CPU index first:

```bash
pip install torch --index-url https://download.pytorch.org/whl/cpu
pip install -e ".[hf]"
```

| Extra | Installs | For |
|---|---|---|
| `yaml` | PyYAML | YAML configs (TOML needs nothing — it's stdlib) |
| `hf` | transformers, safetensors | the Hugging Face recipes and `baby-llm eval` (steps 8–15) |
| `gguf` | gguf, safetensors | `baby-llm export` to llama.cpp and Ollama (step 16) |
| `flash` | flash-attn | the `flash_attention_2` backend |
| `triton` | triton | writing your own Triton kernels |
| `dev` | pytest, ruff, mypy | the test suite and checks |

---

# Tutorial

Steps 1–7 train a tiny model from scratch and need no dataset, GPU, or tokenizer.
Steps 8–11 fine-tune a real pretrained model, add LoRA and preference tuning, and read
the metrics every run writes. Steps 12–16 scale it up and ship it: packing, chunked
loss, multiple GPUs, evaluation, and export to llama.cpp and Ollama.

## 1. Train something

```bash
baby-llm run --config configs/minimal_sft.toml \
  --set training.max_steps=4 --set training.checkpoint_interval=2 \
  --set training.log_interval=2 --set model.dtype=float32 \
  --set training.seq_len=64 --set training.micro_batch_size=2 \
  --set training.output_dir=runs/tutorial
```

```
recipe: minimal_sft
data: 3,988 tokens from built-in demo corpus
model: training from random init
model: 3,082,496 params | device: cpu | attention backend: sdpa
step      2/4 | loss  5.6940 | lr 2.60e-04 | grad_norm  6.118 | 1,962 tok/s
checkpoint: saved step 2 -> runs/tutorial/step_000002.pt
step      4/4 | loss  5.2823 | lr 6.95e-05 | grad_norm  4.962 | 1,734 tok/s
checkpoint: saved step 4 -> runs/tutorial/step_000004.pt
checkpoint: saved step 4 -> runs/tutorial/final.pt
```

(Throughput varies by machine; the losses are from a real CPU run.)

That's a real LLaMA-style decoder — RMSNorm, rotary embeddings, SwiGLU, grouped-query
attention — training on a built-in demo corpus with a byte-level tokenizer. Loss starts
near `ln(vocab_size)` (random guessing) and falls from there.

Two commands worth knowing before you go further:

```bash
baby-llm recipes                            # what recipes are registered
baby-llm validate configs/minimal_sft.toml  # parse + validate, without importing torch
```

`validate` is genuinely torch-free, which means you can check configs on a laptop or in a
CI job with no ML stack installed. CI has a dedicated job that proves it stays that way.

## 2. Read the loop you just ran

This is the part that matters. Open `baby_llm/recipes/minimal_sft.py` and you'll find
the whole thing — here it is, unabridged:

```python
for step in range(start_step, train.max_steps + 1):
    lr = lr_at_step(step - 1, cfg)
    for group in optimizer.param_groups:
        group["lr"] = lr

    optimizer.zero_grad(set_to_none=True)

    # ── gradient accumulation: N micro-batches, one optimizer step ──
    micro_losses = []
    for _ in range(cfg.memory.grad_accum_steps):
        x, y = sample_batch(stream, train.micro_batch_size, train.seq_len, data_rng)
        x, y = x.to(device), y.to(device)
        with offload_ctx():
            with torch.autocast(device.type, dtype=autocast_dtype, enabled=amp_enabled):
                logits = model(x)
            loss = F.cross_entropy(logits.float().view(-1, cfg.model.vocab_size), y.view(-1))
        scaler.scale(loss / cfg.memory.grad_accum_steps).backward()
        micro_losses.append(loss.detach())

    # ── clip in true (unscaled) gradient space, then step ──
    if cfg.optimizer.grad_clip_norm is not None:
        scaler.unscale_(optimizer)
        grad_norm = torch.nn.utils.clip_grad_norm_(
            raw_model.parameters(), cfg.optimizer.grad_clip_norm
        ).item()
    scaler.step(optimizer)
    scaler.update()
```

Everything is in the open, including the parts other frameworks bury:

- **The LR schedule is stateless.** `lr_at_step(step - 1, cfg)` is a pure function of the
  step, so there's no scheduler object whose internal counter can drift out of sync with
  your checkpoint.
- **The loss is divided by `grad_accum_steps` before `.backward()`**, so accumulated
  gradients average rather than sum. That single `/` is the difference between a correct
  effective batch and a silently 8× learning rate.
- **`scaler.unscale_()` runs before clipping.** Clip a scaled gradient and your "max norm
  1.0" is really `1.0 / scale_factor` — a classic AMP bug, visible here as ordering you
  can check.
- **`logits.float()` before cross-entropy** keeps the softmax in fp32 under autocast.

You don't have to trust that these are right. You can see them, and change them.

## 3. Swap the attention kernel

The same module runs any registered backend, so you can compare them on identical weights:

```python
from baby_llm.modules.attention import Attention, force_attention_backend

attn = Attention(hidden_size=256, num_heads=8, num_kv_heads=4, backend="sdpa")
out_fast = attn(x)

with force_attention_backend("eager"):  # explicit matmul→softmax reference
    out_reference = attn(x)

torch.testing.assert_close(out_fast, out_reference, atol=1e-5, rtol=1e-5)
```

Or switch the whole model from a config file, no code change:

```bash
baby-llm run --config configs/minimal_sft.toml --set model.attention.backend=eager
```

Registering your own kernel is the same mechanism the built-ins use — there's no private
fast path:

```python
from baby_llm.modules.attention import register_attention_backend


@register_attention_backend("my_triton_attn")
def my_triton_attn(q, k, v, *, attn_mask, dropout_p, is_causal, scale):
    # q, k, v are (batch, heads, seq, head_dim). k/v may have fewer heads than q (GQA);
    # call repeat_kv() first if your kernel doesn't handle that natively.
    return my_fused_kernel(q, k, v, causal=is_causal, sm_scale=scale)
```

Then `--set model.attention.backend=my_triton_attn`. The project's own test suite checks
`eager` against `sdpa` for both forward *and* backward agreement — copy that test for your
kernel and you'll know immediately whether your gradients are right.

| Backend | Notes |
|---|---|
| `eager` | explicit matmul → mask → softmax reference; materializes the full score matrix |
| `sdpa` | PyTorch picks the fastest fused kernel (default) |
| `sdpa_math`, `sdpa_flash`, `sdpa_mem_efficient` | pinned to one SDPA backend — **errors** instead of silently falling back, which is what you want in a benchmark |
| `flash_attention_2` | needs `flash-attn`; fp16/bf16 only, no dense masks; GQA native |
| `flash_attention_3` | Hopper; no dropout, no dense masks |

## 4. Make it fit in less memory

Three independent knobs, each one line in the loop:

```bash
# Same effective batch (2 × 8 = 16 sequences), a quarter of the activation memory
baby-llm run --config configs/minimal_sft.toml \
  --set training.micro_batch_size=2 --set memory.grad_accum_steps=8

# Recompute each block in backward instead of storing activations
baby-llm run --config configs/minimal_sft.toml --set memory.activation_checkpointing=true
```

| Setting | Costs | Buys |
|---|---|---|
| `memory.grad_accum_steps` | wall-clock per step | larger effective batch at fixed memory |
| `memory.activation_checkpointing` | ~30% more compute | large activation-memory savings |
| `memory.activation_offloading` | PCIe traffic; CUDA only | parks activations in pinned CPU RAM |
| `training.compile` | one-off compile latency | `torch.compile` throughput |
| `model.dtype` | precision | autocast speed; params stay fp32 |

Offloading and checkpointing together are **rejected at parse time** — checkpointing
discards the very activations offloading would move, so asking for both is a mistake worth
an error rather than silent waste.

## 5. Interrupt it, then resume exactly

Checkpoints are written atomically (temp file → fsync → rename), so a crash mid-save can't
leave you a truncated file. And they carry everything a run *is*: weights, optimizer
moments, GradScaler state, and the data/torch RNG streams.

```bash
baby-llm run --config configs/minimal_sft.toml --set training.max_steps=6 \
  --set training.log_interval=1 \
  --set training.resume_from=runs/tutorial/step_000002.pt
```

```
resume: continuing from runs/tutorial/step_000002.pt at step 3
step      3/6 | loss  5.3751 | lr 2.32e-04 | grad_norm  5.073 | 2,000 tok/s
```

It picks up at step 3 — not step 1, and not step 2 again. The strength of the guarantee is
worth stating plainly: **3 steps plus a resume for 3 more produces bitwise-identical
weights to 6 straight steps.** That's not a claim in a docstring, it's
`test_resume_matches_uninterrupted` in `tests/test_checkpointing.py`, asserted with
`rtol=0, atol=0`. No incomplete checkpoint can pass it.

Note the deliberate distinction between two things frameworks often conflate:

```toml
[training]
resume_from = "runs/tutorial/step_000002.pt"  # continue THIS run where it stopped
[model]
init_from = "runs/tutorial/final.pt"          # start a NEW run (fresh optimizer,
                                              # schedule, data order) from these weights
```

Setting both is a validation error, because you have to mean one of them.

## 6. Train on your own text

Point `data.path` at any UTF-8 file:

```bash
baby-llm run --config configs/minimal_sft.toml --set data.path=my_corpus.txt
```

The bundled tokenizer is byte-level — 256 byte values plus an EOS token. That's a
deliberate demo choice: zero dependencies, zero out-of-vocabulary tokens, and trivially
reversible, so nothing about tokenization is hiding. It is *not* what you'd train a real
model with; see the limitations below.

## 7. Write your own recipe

There's no base class and no hook to implement. Copy the file, edit the loop, register it:

```python
# baby_llm/recipes/my_recipe.py
def run(cfg: TrainerConfig) -> dict[str, float]:
    # Your loop, your rules. Copy the body of minimal_sft.run() and edit it.
    ...
```

```python
# baby_llm/recipes/__init__.py
RECIPE_REGISTRY = {
    "minimal_sft": "baby_llm.recipes.minimal_sft",
    "hf_sft": "baby_llm.recipes.hf_sft",
    "dpo": "baby_llm.recipes.dpo",
    "my_recipe": "baby_llm.recipes.my_recipe",  # <- add this line
}
```

```bash
baby-llm run --recipe my_recipe --config your.toml
```

The registry imports lazily, so adding recipes never slows down `--help`. And because
`run()` is an ordinary function taking a config, you can skip the CLI entirely:

```python
from baby_llm.configs import TrainerConfig
from baby_llm.recipes.minimal_sft import run

cfg = TrainerConfig.from_file("configs/minimal_sft.toml")
metrics = run(cfg.apply_overrides({"training.max_steps": "50"}))
```

## 8. Fine-tune a real model

Steps 1–7 trained a 3M-parameter toy. To make something useful, start from a pretrained
model instead. The `hf_sft` recipe loads any Hugging Face causal LM, trains it with the
same kind of readable loop, and saves it back in Hugging Face format.

The data is JSONL, one example per line, in either of two shapes:

```json
{"prompt": "Write a Python function that reverses a string.", "response": "def reverse(s): return s[::-1]"}
{"messages": [{"role": "user", "content": "What is [1, 2, 3][::-1]?"}, {"role": "assistant", "content": "[3, 2, 1]"}]}
```

```bash
baby-llm run --config configs/hf_sft_smollm2.toml
```

That fine-tunes [SmolLM2-135M-Instruct](https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct)
on `examples/data/sft_sample.jsonl`, small enough to run on a laptop CPU. Swap
`hf.name_or_path` for any other model, a Hub id or a local directory. The result lands
in `runs/hf_sft/hf/`, and any Hugging Face tool loads it:

```python
from transformers import AutoModelForCausalLM, AutoTokenizer

model = AutoModelForCausalLM.from_pretrained("runs/hf_sft/hf")
tokenizer = AutoTokenizer.from_pretrained("runs/hf_sft/hf")
```

Open `baby_llm/recipes/hf_sft.py` and three things are worth finding:

- **The prompt is masked out of the loss.** The model should learn to write answers, not
  to predict your questions. `baby_llm/data.py` tokenizes the prompt *on its own* and
  labels each of its tokens `-100`, which the loss skips. Counting the prompt's tokens
  separately is what makes the boundary exact; a test checks it for both chat-template
  and plain tokenizers.
- **Gradient accumulation is weighted by tokens.** Examples have different lengths. The
  usual "average each micro-batch, then average those" quietly gives a short example as
  much say as a long one. The loop counts the target tokens in the whole step first,
  then divides each micro-batch's *summed* loss by that one number. A test proves two
  micro-batches of 2 produce the same update as one batch of 4.
- **Every example is seen once per epoch.** An `EpochSampler` shuffles with a seed per
  epoch, and its whole state is two integers, so `training.resume_from` continues on
  exactly the example the run would have seen next. Resume is bitwise identical here
  too.

Set `data.val_fraction` (or `data.val_path`) and the run reports held-out loss. Add
`eval.sample_prompts` and every evaluation also prints the model's greedy answer to
each prompt. A falling training loss can hide overfitting; watching answers change
cannot.

## 9. Fit a bigger model with LoRA

Full fine-tuning with AdamW needs roughly 16 bytes per parameter: weights, gradients and
two optimizer moments. A 7B model needs over 100 GB before activations. LoRA freezes the
model and trains two small matrices beside chosen layers instead:

```
y = W x  +  (alpha / r) * B (A x)          A: [r, in],  B: [out, r]
```

```bash
baby-llm run --config configs/hf_sft_smollm2.toml \
  --set lora.enabled=true --set optimizer.lr=2e-4 --set hf.load_dtype=bfloat16
```

With rank 16 on the four attention projections, about 1.4% of SmolLM2-135M's
parameters train, and about 0.2% of a typical 7B model's. Only those carry gradients and
optimizer state. With `hf.load_dtype = "bfloat16"` the frozen weights take 2 bytes per
parameter, so a 7B fine-tune fits on one 24 GB GPU with small batches and
`memory.activation_checkpointing = true`. The adapters themselves stay in float32.

`baby_llm/modules/lora.py` is about 100 lines and worth reading in full. `B` starts at
zero, so at step 0 the model is exactly the pretrained one. Checkpoints hold only the
adapters, so they are tiny. When training ends, `merge_lora` folds the adapters back into
the weights, so `runs/hf_sft/hf/` is an ordinary model that needs no LoRA code to run.

LoRA also works in `minimal_sft`, on top of a checkpoint from an earlier run:
`--set model.init_from=runs/tutorial/final.pt --set lora.enabled=true`. It writes
`merged.pt` next to `final.pt`. Turning LoRA on with no `init_from` is rejected at load
time, because freezing random weights would train adapters on noise.

## 10. Teach it preferences with DPO

SFT teaches a model to imitate answers. Preference tuning teaches it which of two answers
is better. The `dpo` recipe implements
[Direct Preference Optimization](https://arxiv.org/abs/2305.18290) on data like this:

```json
{"prompt": "Write a function that checks if n is even.", "chosen": "return n % 2 == 0", "rejected": "return n / 2 == 0"}
```

```bash
baby-llm run --config configs/hf_sft_smollm2.toml   # SFT first: writes runs/hf_sft/hf
baby-llm run --config configs/dpo_smollm2.toml      # then DPO on top of it
```

DPO compares how much more likely the model being trained makes each answer than a
frozen *reference* copy of the starting model does, and pushes that gap toward the
chosen answer:

```
margin = beta * ((log p(chosen) - log ref(chosen)) - (log p(rejected) - log ref(rejected)))
loss   = -log sigmoid(margin)
```

Two things in `baby_llm/recipes/dpo.py` make this easy to trust:

- **It starts at exactly `ln 2` (0.6931).** Before any update the model *is* the
  reference, so every margin is zero. If step 1 logs anything else, something is wrong,
  and a test checks it.
- **With LoRA the reference costs no memory.** It is the same network with the adapters
  switched off (`lora_disabled`). Without LoRA it is a frozen copy, which doubles weight
  memory.

The log reports `reward_acc`, the fraction of pairs where the model now prefers the
chosen answer, and the mean `margin`. Both should rise as training proceeds.

## 11. Read the metrics

Every recipe writes `<output_dir>/metrics.jsonl`, one JSON object per logged step. Each
line is flushed as it is written, so a crashed run keeps everything up to the crash. A
resumed run appends to the same file.

```python
import pandas as pd

m = pd.read_json("runs/hf_sft/metrics.jsonl", lines=True)
m[m["split"] == "train"].plot(x="step", y="loss")
m[m["split"] == "val"][["step", "loss", "samples"]]
```

```bash
jq -c 'select(.split == "train") | {step, loss, tokens_per_s, mem_peak_rss_mib}' runs/hf_sft/metrics.jsonl
```

Training rows carry `loss`, `lr`, `grad_norm`, `tokens_per_s` and peak memory. Peak
memory is the CUDA allocator peak on a GPU and the process peak RSS on CPU. Validation
rows carry the held-out loss and the sample answers, and DPO adds `reward_accuracy` and
`reward_margin`. Set `training.metrics = false` to turn the file off.

## 12. Pack short examples together

Chat data is mostly short examples. Padding each one to the longest in its batch wastes
compute on padding tokens. `data.packing = true` fills each row with several examples
instead:

```bash
baby-llm run --config configs/hf_sft_smollm2.toml --set data.packing=true
```

The run log reports how many examples went into how many rows, and how full the rows
are. `micro_batch_size` then counts rows, not examples.

Packing is only correct if a packed row trains exactly like its examples would alone.
`collate_packed` in `baby_llm/data.py` makes that true in three visible steps:

- positions restart at 0 for each example, so rotary embeddings see normal positions;
- a block-diagonal causal mask stops tokens attending across example boundaries;
- each example's first token is not a target, because in the row it would be
  "predicted" from the previous example.

A test runs a real model on a packed row and gets the same logits as running each
example on its own. Packing works with the `eager` and `sdpa` attention backends;
others are rejected at load time until they can be verified.

## 13. Fit a large vocabulary with chunked loss

The output layer scores every vocabulary token at every position. With Llama 3's
128,256-token vocabulary, a batch of 8 × 4096 tokens produces about 16.8 GB of float32
logits, held until backward. `memory.chunked_loss = true` computes the output layer and
loss a chunk of positions at a time and recomputes each chunk in backward, so only one
chunk's logits exist at once:

```bash
baby-llm run --config configs/hf_sft_smollm2.toml \
  --set memory.chunked_loss=true --set memory.loss_chunk_size=4096
```

It gives the same loss and the same gradients, at the cost of one extra output-layer
matmul per chunk. Tests check both, and measure that autograd keeps less than a tenth
of the logits' size alive. Some models change their logits after the output layer,
such as Gemma 2's soft-capping. A one-pass check at startup refuses those rather than
compute a different loss.

## 14. Train on many GPUs with FSDP2

`fsdp_sft` is `hf_sft` spread across GPUs. Each process holds 1/N of every weight,
gradient and optimizer moment, gathering a layer's full weights only while it runs:

```bash
torchrun --nproc-per-node 8 -m baby_llm.cli run --config configs/fsdp_sft_smollm2.toml
```

`baby_llm/recipes/fsdp_sft.py` writes out every piece of the distribution, and the rule
it follows is to compute exactly what one big GPU would:

- every process draws the same global batch from the same seeded sampler and trains
  on its own slice;
- the loss is divided by the target-token count of the whole global batch;
- FSDP averages gradients across processes, so the loss is also multiplied by the
  number of processes, turning that average back into the sum.

A test runs two processes and checks they reach the same weights as single-process
`hf_sft` with a batch twice the size, with gradient accumulation, LoRA, and packing.
Checkpoints are sharded, so each process writes its own piece and saving never gathers
the model. Resume works from them. The final save gathers the weights once and writes
an ordinary Hugging Face directory. `micro_batch_size` is per process.

## 15. Score your model

Training loss says how well a model fits its training data. `baby-llm eval` scores a
saved model on data it has not seen, so two runs can be compared on one number:

```bash
baby-llm eval runs/hf_sft/hf examples/data/sft_sample.jsonl        # loss, perplexity
baby-llm eval runs/hf_sft/hf examples/eval/choice_sample.jsonl     # multiple choice
baby-llm eval runs/hf_sft/hf examples/eval/generate_sample.jsonl   # generation
baby-llm eval runs/hf_sft/hf my_eval.jsonl --out results.json      # + per-example detail
```

The task follows from the shape of the records:

| Records | Task | Reports |
|---|---|---|
| `{"prompt", "response"}`, `{"messages"}` or `{"text"}` | loss | loss per target token, perplexity |
| `{"prompt", "choices": [...], "answer": <index>}` | choice | `accuracy`, `accuracy_norm` |
| `{"prompt", "answer"}` | generate | `exact_match`, `contains` |

Multiple choice is scored the way MMLU, HellaSwag and ARC are: the model "picks" the
choice it finds most probable after the prompt. `accuracy_norm` divides by each
choice's length so long answers are not penalised. Any benchmark converted to one of
these shapes runs as is.

## 16. Run it in llama.cpp or Ollama

`baby-llm export` writes one GGUF file, the format llama.cpp and Ollama load:

```bash
pip install "baby-llm[gguf]"
baby-llm export runs/hf_sft/hf model.gguf --dtype q8_0   # or f16, bf16, f32
llama-cli -m model.gguf -p "Write a Python function that reverses a string."
```

For Ollama, put `FROM ./model.gguf` in a file named `Modelfile`, then run
`ollama create my-model -f Modelfile` and `ollama run my-model`. The file carries the
model's chat template; if replies look unformatted, add a `TEMPLATE` line for the
model's chat format to the Modelfile.

`baby_llm/export.py` is short enough to read. Most of it maps Hugging Face tensor names
to llama.cpp's. The one real transformation reorders the query and key weights from
Hugging Face's rotary layout into llama.cpp's. Tests load the exported file in
llama.cpp and check it reproduces the Hugging Face logits. A negative control with that
reordering removed must fail, so the check is known to be sensitive. The text-splitting
rule llama.cpp needs is detected from `tokenizer.json` for GPT-2, SmolLM and Llama 3
style tokenizers; for others, pass `--pre-tokenizer`. Export supports Llama-architecture
models (Llama, Mistral, SmolLM) without rope scaling.

---

## Configuration reference

One TOML (or YAML) file, nine sections, each a Pydantic model in
`baby_llm/configs/base.py`. Unknown keys are rejected, so typos fail loudly instead of
being ignored.

| Section | Key fields |
|---|---|
| `[model]` | `hidden_size`, `num_layers`, `num_heads`, `num_kv_heads` (GQA), `vocab_size`, `max_seq_len`, `ffn_hidden_size`, `rope_theta`, `norm_eps`, `tie_embeddings`, `dtype`, `init_from` |
| `[model.attention]` | `backend`, `dropout`, `bias` |
| `[optimizer]` | `name` (adamw/adam/sgd), `lr`, `weight_decay`, `betas`, `eps`, `momentum`, `fused`, `scheduler` (cosine/linear/constant), `warmup_steps` \| `warmup_ratio`, `min_lr_ratio`, `grad_clip_norm` |
| `[memory]` | `grad_accum_steps`, `activation_checkpointing`, `activation_offloading`, `chunked_loss`, `loss_chunk_size` |
| `[training]` | `micro_batch_size`, `seq_len`, `max_steps`, `seed`, `device`, `compile`, `log_interval`, `checkpoint_interval`, `output_dir`, `resume_from`, `metrics` |
| `[data]` | `format` (text/sft_jsonl/preference_jsonl), `path`, `val_path` \| `val_fraction`, `packing` |
| `[hf]` | `name_or_path`, `revision`, `load_dtype`, `trust_remote_code` (hf_sft, dpo) |
| `[lora]` | `enabled`, `rank`, `alpha`, `dropout`, `target_modules` |
| `[eval]` | `interval`, `max_batches`, `sample_prompts`, `max_new_tokens` (hf_sft, dpo) |
| `[dpo]` | `beta` (dpo) |

`[model]` describes the built-in tiny model. With `hf.name_or_path` set, only
`model.dtype` and `model.attention.backend` apply, because the pretrained model brings its
own architecture.

Any field is overridable with dotted keys; values are coerced by Pydantic, so everything
can be passed as a string:

```bash
baby-llm run --config configs/minimal_sft.toml \
  --set training.max_steps=500 --set model.dtype=bfloat16 --set optimizer.scheduler=linear
```

Caught at parse time rather than mid-run: GQA head divisibility, `warmup_steps` vs
`warmup_ratio`, a flash backend with `float32`, `seq_len` exceeding the RoPE cache,
`resume_from` with `init_from`, and offloading with checkpointing. Also: a recipe given
the wrong data format, or a section it never reads, such as `[dpo]` on an SFT run; a
tiny-model field set alongside a pretrained model, where it would be silently ignored;
an attention backend with no Hugging Face equivalent; LoRA on random weights; packing
with an attention backend it is not verified on; `training.compile` on a recipe that
does not read it; and float16 with `fsdp_sft`.

## Status and limitations

Alpha (`0.2.0`), so the API will still change. What it deliberately does *not* do yet:

- **Data parallel only.** `fsdp_sft` shards a model across GPUs, but there is no tensor
  or pipeline parallelism, so each GPU still runs whole layers. DPO runs on one device.
- **Packing needs `eager` or `sdpa` attention** for now; flash backends are refused
  until they can be verified.
- **GGUF export covers Llama-architecture models** without rope scaling.
- **DPO without LoRA keeps a second copy of the model** as its reference. Use LoRA, or
  budget twice the weight memory.
- **The tiny model is a teaching tool.** `minimal_sft`'s byte tokenizer and 3M-parameter
  decoder exist to make the loop legible; use `hf_sft` for anything you want to keep.
  Its `generate()` also has no KV cache, written for clarity.

Planned next: packing with flash attention, multi-GPU DPO, more export architectures,
and first-party Triton kernels.

## Project layout

```
baby-llm/
├── pyproject.toml                # packaging, deps, `baby-llm` CLI entry point
├── configs/                      # one example config per recipe
├── examples/data/                # sample SFT and preference JSONL
├── examples/eval/                # sample multiple-choice and generation evals
├── baby_llm/
│   ├── cli.py                    # typer CLI: run / recipes / validate / eval / export
│   ├── configs/base.py           # Pydantic V2 schema + TOML/YAML loaders + overrides
│   ├── training.py               # optimizer, LR schedule, AMP, atomic checkpoints, resume
│   ├── data.py                   # JSONL, prompt masking, epoch sampler, padding, packing
│   ├── losses.py                 # chunked cross-entropy
│   ├── evaluate.py               # baby-llm eval: loss, multiple choice, generation
│   ├── export.py                 # baby-llm export: GGUF for llama.cpp / Ollama
│   ├── metrics.py                # metrics.jsonl writer + peak memory
│   ├── hf.py                     # load/save Hugging Face models
│   ├── modules/attention.py      # backend-switchable Attention + kernel registry
│   ├── modules/lora.py           # LoRALinear, apply/merge, lora_disabled
│   ├── kernels/                  # first-party kernels (same registry user code uses)
│   ├── recipes/minimal_sft.py    # tiny model from scratch, single device
│   ├── recipes/hf_sft.py         # fine-tune a Hugging Face model on JSONL
│   ├── recipes/fsdp_sft.py       # the same across GPUs with FSDP2
│   ├── recipes/dpo.py            # preference tuning
│   └── py.typed                  # ships inline type hints
├── tests/                        # offline: a tiny Llama is built locally, no Hub needed
└── .github/workflows/            # ci.yml (lint, torch-free proof, test matrix)
                                  # publish.yml (TestPyPI + PyPI via Trusted Publishing)
```

## Development

```bash
pytest -m "not network"            # full suite minus tests that download models
ruff check . && ruff format --check .
python -m mypy
```

CI runs exactly those, plus a job that installs the package *without* torch and runs the
config tests — keeping the torch-free claim honest. See
[CONTRIBUTING.md](https://github.com/700799/baby-llm/blob/main/CONTRIBUTING.md) for the
philosophy guardrails changes are reviewed against.

## License

MIT — see [LICENSE](LICENSE).
