Skip to main content

PyLLM

An educational large language model built from scratch in Python.

Part of the "from scratch in Python" series. Built incrementally with TDD, every concept explained with analogies a 12-year-old can follow. The only dependency is numpy (for fast array math) — the autograd engine, neural-net layers, attention, the Transformer, the tokenizer, the optimizer, the training loop, and sampling are all ours.

Quick Start

uv sync --all-extras
uv run pytest

Dream up new Pokémon (generates instantly)

PyLLM ships with a tiny pre-trained GPT, so it invents Pokémon-ish names the moment you launch it — no training wait:

$ uv run pyllm --seed 0 --max-new-tokens 40
machop
machoke
machamp
bellsprout
weepin

Turn the boldness dial with --temperature (0 = safe/greedy, higher = wilder) and add a --top-k guardrail. Start from a prompt with --prompt "pi".

Train your own model

Pick a rung on the teaching ladder (bigram, mlp, or gpt) and point it at any text file (defaults to the bundled Pokémon corpus):

$ uv run pyllm train --model gpt --steps 2000 --seed 0 --out mine.npz
step 0: loss 3.4070
...
final loss 0.2996; saved checkpoint to mine.npz

$ uv run pyllm --checkpoint mine.npz --max-new-tokens 60

The flagship: teach PyLLM to write Pebble

There's no corpus of Pebble code in the wild — so we grow our own. A generator emits random-but-provably-valid Pebble ASTs (100% parse under Pebble's own parser), a harvester scrapes real snippets from Pebble's docs, and — because we own the language toolchain — we grade the trained model by running its output back through Pebble's real parser and reporting what percentage parses:

$ uv run pyllm pebble --seed 7 --temperature 0.5 --score
let total = n * (5 + n)
        let a = 6
    }
    let a = result * (6 - result)
...
parse rate: 0.0% of 1 programs

The bundled checkpoint is tiny (a few-minute char-level GPT), so it writes Pebble-flavoured code and only some of it parses — and that's the whole point: the parser is an honest, objective judge, so you can watch the score go up as you train longer or bigger. Almost no LLM project can grade its own output like this.

Call in the referee: always-valid Pebble

Add --constrained and a from-scratch grammar referee vetoes every character that would break Pebble's rules, so the model rolls again until it picks a legal one. Same tiny brain — but now every program it returns parses:

$ uv run pyllm pebble --seed 7 --constrained --score
let total = result + j * 3

parse rate: 100.0% of 1 programs

From Python: generate_pebble(constrained=True). See docs/concepts/the-referee.md.

Grow a fresh synthetic corpus with uv run pyllm gen-corpus. Live scoring needs the optional fromscratch-pebble dependency (uv sync --all-extras); generation and training work without it. See docs/concepts/grow-your-own-data.md.

See how text becomes tokens

$ uv run pyllm tokenize --text "pika"
'p' -> 16
'i' -> 9
'k' -> 11
'a' -> 1

The teaching ladder

Each rung is a real, trainable language model that fixes a weakness of the one below it, so you feel why each idea exists:

  1. Bigram — "what character usually comes next?" A lookup table.
  2. MLP — a small neural net over the last few characters (embeddings + a hidden layer).
  3. GPT — stacked Transformer blocks (multi-head attention + feed-forward + LayerNorm + residuals) with positional information. The real thing.

Learn the ideas

Kid-friendly explanations live in docs/concepts/: the breadcrumb trail (autograd), tokens, embeddings, attention, how a Transformer is built, how a model learns, sampling, and — the flagship lesson — growing your own data.

Developing alongside a sibling

PyLLM uses a released version of Pebble from PyPI (fromscratch-pebble, the optional pebble extra). To try an unreleased Pebble change, install your local checkout over the released one:

uv pip install -e ../pebble-lang
uv run --no-sync pytest

Use uv run --no-sync while you do this: a plain uv run (like uv sync) puts the released version back, which is how you undo the override.

Releasing

  1. Merge the change to main.
  2. Release it: gh release create vX.Y.Z --target main --generate-notes (or push a vX.Y.Z tag); the release workflow publishes it to PyPI. A change to the public API bumps the minor version (v0.1.0 → v0.2.0); anything else bumps the patch (v0.1.0 → v0.1.1).
  3. Projects that use PyLLM (like PyStack) upgrade by raising their fromscratch-pyllm>=X.Y.Z floor and running uv lock --upgrade-package fromscratch-pyllm, in a pull request so CI checks the pair.

PyLLM inside PyStack

PyLLM is the brain of a family of educational projects, each building a real system from scratch to teach how it works. They're tied together by PyStack, where a Pebble program can even import "llm" and ask PyLLM to write more code.

Once PyLLM is installed as a PyStack plugin, any Pebble program can call it:

import "llm"
let code = llm_generate("a function that adds two numbers")
print(code)

This project is one of a series that builds real systems "from scratch in Python" to teach how they work. See the series home for the full story.

Project What it teaches Repository Docs PyPI
PyOS Operating systems py-os Docs fromscratch-pyos
Pebble Compilers and programming languages pebble-lang Docs fromscratch-pebble
PyDB Relational databases pydb Docs fromscratch-pydb
PyKV Key-value stores pykv Docs fromscratch-pykv
PyDocDB Document databases pydoc-db Docs fromscratch-pydocdb
PyGraphDB Graph databases pygraphdb Docs fromscratch-pygraphdb
PyTSDB Time-series databases pytsdb Docs fromscratch-pytsdb
PyVecDB Vector databases pyvecdb Docs fromscratch-pyvecdb
PyColDB Column-family databases pycoldb Docs fromscratch-pycoldb
PyCrypt Cryptography pycrypt Docs fromscratch-pycrypt
PyNet Computer networking pynet Docs fromscratch-pynet
PyWeb HTTP web servers pyweb Docs fromscratch-pyweb
PyGit Version control pygit Docs fromscratch-pygit
PySearch Search engines pysearch Docs fromscratch-pysearch
PyMQ Message queues pymq Docs fromscratch-pymq
PyLLM Language models (the brain) pyllm Docs fromscratch-pyllm
PyScheduler Job scheduling pyscheduler Docs fromscratch-pyscheduler
PyStack Full-stack integration pystack Docs fromscratch-pystack

Documentation

Full docs (with kid-friendly explanations of every idea): https://robcox2910.github.io/pyllm/

Install

PyPI

pip install fromscratch-pyllm

Or get the whole series at once: pip install fromscratch-pystack.

Metadata

Release files for fromscratch-pyllm 0.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fromscratch-pyllm 0.5.1
File Size Uploaded Provenance Actions
fromscratch_pyllm-0.5.1.tar.gz 1.7 MB With provenance Details for fromscratch_pyllm-0.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fromscratch-pyllm 0.5.1
File Interpreter ABI Platform Actions
fromscratch_pyllm-0.5.1-py3-none-any.whl Python 3 none any Details for fromscratch_pyllm-0.5.1-py3-none-any.whl

Total release size: 3.1 MB

Release files / fromscratch_pyllm-0.5.1.tar.gz

Download URL fromscratch_pyllm-0.5.1.tar.gz
Size 1.7 MB
Tags Source
SHA-256 checksum
How to use checksums
8936ade8eb57759e320a9e2b30112c190cc6b347beea5f55450628f64e41b621
BLAKE2b-256 checksum
How to use checksums
6ae9ccad9800ab9a49bf1e2deccbe3fdcc83cd68bdd04c880a0d3a0f4807a48a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Release files / fromscratch_pyllm-0.5.1-py3-none-any.whl

Download URL fromscratch_pyllm-0.5.1-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
39740de948e802914d27c4ef67a833c75d2e7efbf844fa471a63e98ce8dbcfbc
BLAKE2b-256 checksum
How to use checksums
4e19d884a719955d57c2998359d98cf8687b620a48cefa443bbdd7a2cf3103db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

Security for fromscratch-pyllm 0.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for fromscratch_pyllm-0.5.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.5.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page