mathgpt / README.md
bhathri's picture
Upload README.md with huggingface_hub
f526422 verified
|
Raw History Blame Contribute Delete
2.29 kB
---
language: en
license: mit
tags:
- pytorch
- gpt
- transformer
- character-level
- arithmetic
---
# MathGPT
A tiny decoder-only GPT transformer built **from scratch in PyTorch** for integer arithmetic.
Built for the Machine Learning module (CS7CS4) of the M.Sc. in Computer Science (Intelligent Systems), Trinity College Dublin, 2025/26.
## Model details
| Property | Value |
|---|---|
| Parameters | 2.24 M |
| Architecture | 5-layer · 6-head · 192-dim · ReLU feed-forward |
| Context window | 40 characters |
| Vocab | 18 characters (digits 0–9 + operators `+` `−` `*` `/` `(` `)` `=` `\n`) |
| Tokeniser | Character-level |
| Exact-match accuracy | **78.2 %** on held-out test set |
## What it does
Given the left-hand side of an arithmetic expression (e.g. `95*36=`), the model generates the answer one character at a time using causal self-attention. Integer inputs only; supports `+`, `−`, `*`, `/` and brackets.
## Usage
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
# --- paste the model class definition here (see companion repo) ---
MATH_CHARS = ['\n','(',')', '*','+','-','/','0','1','2','3','4','5','6','7','8','9','=']
stoi = {c: i for i, c in enumerate(MATH_CHARS)}
itos = {i: c for i, c in enumerate(MATH_CHARS)}
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)
result = "".join([itos[i] for i in out[0].tolist()]).split("\n")[0]
print(result) # 95*36=3420
```
## Training
Trained for 7,000 iterations with AdamW (lr=3e-4) on 40,000 integer arithmetic expressions.
Validated every 500 steps. Accuracy evaluated by exact-match on 500 held-out test expressions.
## Companion
- **BooleanGPT:** [`bhathri/booleangpt`](https://huggingface.co/bhathri/booleangpt)
- **Code:** [github.com/Bhathrinaathan/mathgpt-booleangpt](https://github.com/Bhathrinaathan/mathgpt-booleangpt)
- **Developer:** Bhathrinaathan Muthuramalingam Bhanumathi · [bhathrinaathan.github.io](https://bhathrinaathan.github.io)