A from-scratch, tiny Shakespeare-trained language model, built with GoMLX to learn how LLMs work under the hood.
It contains two models that share the same tokenizer, data pipeline, loss function and training loop, so you can compare them directly:
cmd/ngram— a neural N-gram model (internal/ngram): predicts the next character from a small, fixed window of preceding characters.cmd/transformer— a tiny decoder-only Transformer, a miniature GPT (internal/transformer): predicts the next character using one causal self-attention over all preceding characters in its context window.
Only the model function differs between the two; everything else
(internal/tokenizer, internal/dataset, internal/trainutil) is identical.
That's on purpose — the N-gram model is the natural stepping stone to
understanding what a Transformer actually adds (content-based attention over a
variable amount of context, instead of a fixed small window).
# Train the N-gram model (fast, runs happily on CPU in seconds).
go run ./cmd/ngram
# Train the tiny Transformer (slower, but still fine on CPU for a demo).
go run ./cmd/transformerBoth commands download nothing at run time — the corpus is already checked
into data/input.txt (the classic ~1MB "tiny Shakespeare"
text). Run go run ./cmd/ngram -h or go run ./cmd/transformer -h to see all
the tunable hyperparameters (context/block size, embedding size, number of
layers, learning rate, steps, etc) — every one of them is explained in
docs/knobs-and-levers.md.
See docs/reading-list.md for recommended tutorials,
papers, and books on LLM theory to go along with this code.
1. Tokenization — internal/tokenizer
We use the simplest possible tokenizer: character-level. The vocabulary is
just "every unique character that appears in the corpus" (65 of them for tiny
Shakespeare — letters, punctuation, whitespace). Encode turns a string into a
slice of integer token IDs; Decode reverses it.
This is not how production LLMs tokenize (they use sub-word schemes like BPE, which balance vocabulary size against sequence length), but it's the easiest to reason about: there's a 1:1 mapping between characters and tokens, encoding is a map lookup, and there's no "unknown token" problem. It's also exactly the starting point used in Karpathy's makemore/nanoGPT lectures.
2. Train/validation split — internal/dataset
dataset.Split holds out the last valFraction (default 10%) of the
tokenized corpus as a validation set that the model never trains on. Both
cmd/ngram and cmd/transformer print train loss and validation loss side
by side every -eval_every steps — watch for training loss dropping while
validation loss stalls or rises, which is the signature of overfitting
(memorizing training text instead of learning generalizable structure).
dataset.WindowSampler implements GoMLX's train.Dataset interface. It
samples random blockSize-token windows from the corpus; for a window of
tokens [t0, t1, ..., tn], the input is [t0, ..., t(n-1)] and the label is
the same window shifted by one: [t1, ..., tn]. Every position in the window
becomes one (context → next token) training example, computed in a single
forward/backward pass.
3. Cross-entropy loss — internal/trainutil
Both models are trained with
loss.SparseCategoricalCrossEntropyLogits.
For every position, the model outputs a logit vector over the vocabulary; the
loss is -log(softmax(logits)[correct token]). A model that puts high
probability on the right answer pays a small loss; one that's confidently
wrong pays a very large loss. This is the training signal for a language
model — everything else (optimizer, learning rate, architecture) exists to
make this number small on data the model hasn't memorized.
4. Perplexity — also in internal/trainutil
Perplexity is simply exp(cross-entropy loss). It has an intuitive reading:
roughly "how many equally-likely choices is the model choosing between, on
average, at each position". A model guessing uniformly at random over the
65-character vocabulary has a perplexity of ~65; a model that has genuinely
learned the structure of English/Shakespeare gets it down into the
single-to-low-double digits. It's reported next to the loss in the training
output so you don't have to do the mental math.
5. N-gram model — internal/ngram
A generalization of a bigram model (see Bengio et al., 2003, "A Neural
Probabilistic Language Model"): embed each of the Context preceding tokens,
concatenate their embeddings, and project to vocabulary logits with a single
dense layer. -context 2 is a plain bigram model (next token depends only on
the current one); increasing -context gives it more history, but the window
size is fixed and hardcoded into the model's weights.
6. Single-head self-attention — internal/transformer
A GPT-2-style, pre-norm decoder stack: token + learned positional embeddings,
then NumLayers blocks of (LayerNorm → causal self-attention → residual add →
LayerNorm → feed-forward MLP → residual add), then a final LayerNorm and a
projection to vocabulary logits. Each attention block explicitly learns three
projections of the normalized residual stream: queries
Here i can only attend to positions <= i.
For a query token, dot products with all key tokens give its scores. Softmax
turns the permitted scores into a probability distribution, and that row of
weights selects a weighted mixture of value vectors.
Pass -attention to print the first layer's attention matrix before every
sampled character. Rows are query tokens, columns are key tokens, and each row
sums to 1. Keep this experiment small so the matrices are readable:
go run ./cmd/transformer -block_size 8 -embed_dim 32 -num_layers 1 -steps 500 -generate 4 -attentionThe left-padded prompt context appears in the first matrix. Future columns are
exactly 0.000; after training, non-zero entries show where the model chose to
look for each query token.
Both models already use learned token embeddings (layers.Embedding) rather
than one-hot vectors directly:
- N-gram token embedding variable:
/token_embed/embeddings - Transformer token embedding variable:
/token_embed/embeddings
To inspect what the model learned after training, run either command with
-embedding_report:
# N-gram embedding similarity report.
go run ./cmd/ngram -steps 1500 -embedding_report
# Transformer embedding similarity report + export vectors for plotting.
go run ./cmd/transformer -steps 1500 -embedding_report -embedding_csv embeddings.csv
# Also export a 2D PCA projection you can scatter plot directly.
go run ./cmd/transformer -steps 1500 -embedding_report -embedding_pca2d_csv embeddings-2d.csvThe report prints:
- group cohesion (
mean pairwise cosine) for vowels and punctuation, - nearest-neighbor tokens in embedding space for each vowel/punctuation token.
That gives you a direct way to test questions like:
- "Do vowels cluster together?"
- "Do punctuation marks get similar vectors?"
The CSV contains one row per token (token_id, token, group, dim_*) so
you can project it to 2D with your plotting tool of choice.
If you pass -embedding_pca2d_csv, you also get a ready-to-plot CSV with
pc1 and pc2 columns for each token.
After training, both commands autoregressively sample new text from the model
(trainutil.Generate): starting from a prompt, repeatedly feed the last
blockSize tokens through the model, take the logits for the next token,
apply a temperature-scaled softmax, and sample. Try -temperature values
below 1.0 for more conservative (repetitive) output, or above 1.0 for more
random output.
See docs/knobs-and-levers.md for the full
reference on every flag and how they trade off against each other (model size
vs. training steps vs. data volume, overfitting, etc). A few to start with:
- Compare
cmd/ngram -context 2(bigram) vs-context 8vscmd/transformerat similar parameter counts — watch how validation perplexity improves as the model can use more context, and how much further self-attention gets you versus just a bigger fixed window. - Increase
-block_sizeon the transformer and watch training slow down (attention cost grows quadratically with context length) while perplexity improves. - Set
-val_fractionvery small vs. very large and watch how much noisier the validation loss curve gets with less validation data.