MathGPT
A compact GPT model for arithmetic
1 min readupdated
MathGPT is a small language model (2.24 million parameters) built from scratch in PyTorch to solve integer arithmetic problems. The model takes expressions like 95*36= and generates the result token by token using causal self-attention. Developed as part of a machine learning course at Trinity College Dublin, it supports basic operations including parentheses. This project is ideal for anyone studying the inner workings of transformers.
Key features
- 78.2% exact match accuracy on the test set
- Architecture featuring 5 layers and 6 attention heads
- Character-level tokenization
- Context window of 40 characters
What you can do
- Run inference locally using a PyTorch script
- Explore a mini-transformer implementation for educational purposes
- Test the generation of mathematical expressions with parentheses
Example
import torch
model = GPTLanguageModel(vocab_size=18, n_embd=192, n_head=6, n_layer=5, block_size=40, dropout=0.05)
model.load_state_dict(torch.load("mathgpt.pth", map_location="cpu"))
model.eval()
expression = "95*36="
ctx = torch.tensor([[stoi[c] for c in expression]], dtype=torch.long)
with torch.no_grad():
out = model.generate(ctx, max_new_tokens=15, temperature=0.1)
Read more
DetailsParameters: 2.24 M
Training: 7,000 iterations with AdamW
Dataset: 40,000 arithmetic expressions










Comments