This site is version 0.0.1. Most of the code on this site is drafted by an agent and needs review. I apologize for the AI-speak, we are working on rewriting it!
viv-lang.org

Notebooks · lib/gpt/gpt

A small GPT, written to be read while it runs

A GPT in the shape of nanoGPT and the modded-nanogpt speedrun, small enough that training it for a few dozen steps takes seconds in the interpreter: token and position embeddings, a stack of blocks (RMSNorm, causal self-attention with several heads, a residual; RMSNorm, a ReLU-squared MLP, a residual), a final RMSNorm and a linear map to one logit per token of the vocabulary. Training minimizes the cross-entropy of the next token with Muon on the blocks' matrices and Adam on the embeddings and the output map, as the speedrun does.

The model is a record of its matrices: a Gpt holds the two embeddings, an array of Blocks and the output map; a block holds its Attention (one Head of query, key and value matrices per head, and the output projection) and its Mlp. A matrix is read where it is, model.blocks[l].attn.Wo. A training step runs the whole batch at once: the tokens are a batch by positions matrix, the stream a stack of one matrix per sequence, and @ and the reductions work on each matrix of the stack, as PyTorch's do. The gradient is value_and_grad of the batch's loss with respect to the model: a Gpt of the same shape, which the backward pass the compiler writes from the forward pass fills, and a test checks against central differences. The optimizers update the model in place, matrix by matrix (for_leaves).

The sizes live in a GptConfig record, which builds the model and sets the batch; the model itself reads its sizes from its matrices. lib/gpt/story_gpt trains one on a sentence and asks it to continue a prompt.

Used with import gpt.gpt.

Look inside this program

  • Atlas

    The program’s map: every function and which calls which.

  • There’s no recorded run of this program yet.

This program declares a record type (GptConfig), and records run only in compiled C for now, so the Run buttons here are off. Open it in the workbench and use its C tab to compile it.

Shift+Enter in a cell runs it and moves to the next. Running a cell runs every cell above it too, as one program.

[1]lines 34–223