microGPT: A Complete Transformer and Autograd Engine from Scratch
In 2017, Vaswani et al. introduced the Transformer architecture in “Attention Is All You Need”, transforming machine learning and establishing the foundation for modern large language models. While industrial neural networks employ billions of parameters distributed across thousands of GPUs, the core mathematical mechanics of a generative transformer are compact and conceptually accessible.
To truly understand how transformers work, nothing equals building one from scratch without relying on PyTorch, TensorFlow, or external linear algebra libraries.
In this chapter, we implement microGPT in pure Gerbil Scheme, inspired by Andrej Karpathy’s educational micrograd and microGPT projects. In roughly 350 lines of Scheme, we construct:
- A Scalar Autograd Engine: A reverse-mode automatic differentiation system with a
valuerecord that builds dynamic computation graphs on the fly and applies the chain rule via topological sorting. - A Complete Generative Transformer: Token and positional embeddings, Root Mean Square Layer Normalization (RMSNorm), 4-head causal self-attention with a Key-Value (KV) cache, and a Multi-Layer Perceptron (MLP) with Rectified Linear Unit (ReLU) activation.
- Training Pipeline: Character-level next-token prediction trained on 32,000 proper names using categorical cross-entropy loss and the Adam optimizer with bias correction and learning rate decay.
- Autoregressive Inference: Temperature-scaled probabilistic sampling that dreams up new, phonetically plausible names.
Theoretical Foundations
Before writing Scheme code, we examine the four mathematical pillars of microGPT.
Scalar Reverse-Mode Automatic Differentiation
Neural network training depends on computing the gradient of a scalar loss
with respect to every trainable parameter
:
.
Reverse-mode automatic differentiation represents mathematical operations as a Directed Acyclic Graph (DAG). Every intermediate quantity is a node storing its scalar value
, its accumulated gradient
, its child operands, and the local partial derivatives:

To compute gradients for all nodes in a single backward pass:
- Perform a forward pass, evaluating mathematical expressions and linking child nodes.
- Topologically sort the DAG from the loss node backward.
- Seed the loss gradient
.
- Traverse the topologically sorted nodes, propagating gradients backward to child nodes using the chain rule.
Root Mean Square Normalization (RMSNorm)
Layer normalization stabilizes transformer activations across layers. Rather than computing both mean and variance, RMSNorm simplifies standard layer normalization by scaling inputs strictly by their root mean square:


where
is a small constant (such as
) preventing division by zero.
Multi-Head Causal Self-Attention
Self-attention allows tokens in a sequence to dynamically attend to other tokens. Given normalized token representations, linear projections produce Queries
, Keys
, and Values
for each attention head:

The attention weight
between query position
and key position
is computed using scaled dot-product attention:


Causal masking enforces that position
can only attend to positions
. The output of each head is the weighted sum of values:

Outputs from all heads are concatenated and projected through an output projection matrix
.
Cross-Entropy Loss and the Adam Optimizer
Given output logits
, the probability of predicting true next token
is obtained via softmax:

The training loss is the negative log-likelihood:

Parameters are updated using the Adam (Adaptive Moment Estimation) optimizer. Adam tracks running exponentially decaying averages of past gradients (
) and squared gradients (
):

Correcting for initialization bias yields:

The parameter update step is:

where
decays linearly from initial learning rate
toward zero.
Input Data Sample (names.txt)
The training dataset names.txt contains 32,033 English first names, one per line. Here is a small sample:
1 emma
2 olivia
3 ava
4 isabella
5 sophia
6 charlotte
7 mia
8 amelia
9 harper
10 evelyn
The unique characters across all names form our vocabulary (26 lower-case letters plus a special Beginning/End of Sequence bos delimiter, giving a vocabulary size of 27).
Complete Source Code (microgpt.ss)
Here is the complete implementation of microGPT in pure Gerbil Scheme:
1 ;; File: microgpt.ss
2 ;; Andrej Karpathy's microGPT -- a tiny, dependency-free GPT -- in Gerbil Scheme.
3 ;; Ported from the Common Lisp version in "Loving Common Lisp".
4 ;;
5 ;; Everything is built from scratch on scalar values:
6 ;; - a reverse-mode autograd engine (the `value` struct, like micrograd)
7 ;; - a 1-layer transformer: token + position embeddings, RMSNorm,
8 ;; multi-head causal self-attention with a KV cache, and a ReLU MLP
9 ;; - an Adam optimiser with linear learning-rate decay
10 ;; - temperature-scaled sampling to "hallucinate" new names
11
12 (import :std/format :std/sort :std/misc/ports)
13 (export main run-microgpt)
14
15 ;;; ------------------------------------------------------------------------
16 ;;; Utilities
17 ;;; ------------------------------------------------------------------------
18
19 (def pi (* 4.0 (atan 1.0)))
20
21 ;; Box-Muller sample from N(mean, std).
22 (def (random-gauss mean std)
23 (+ mean (* std
24 (sqrt (* -2.0 (log (max (random-real) 1e-15))))
25 (cos (* 2.0 pi (random-real))))))
26
27 ;; Fisher-Yates shuffle, returning a new list.
28 (def (shuffle-list lst)
29 (let ((v (list->vector lst)))
30 (do ((i (- (vector-length v) 1) (- i 1)))
31 ((< i 1) (vector->list v))
32 (let* ((j (random-integer (+ i 1)))
33 (tmp (vector-ref v i)))
34 (vector-set! v i (vector-ref v j))
35 (vector-set! v j tmp)))))
36
37 (def (string-trim-whitespace s)
38 (let* ((chars (string->list s))
39 (ws? (lambda (c) (char-whitespace? c)))
40 (drop-ws (lambda (l) (let loop ((l l)) (if (and (pair? l) (ws? (car l))) (loop (cdr l)) l)))))
41 (list->string (reverse (drop-ws (reverse (drop-ws chars)))))))
42
43 ;; Non-empty, trimmed lines of FILE (or '() if it does not exist).
44 (def (read-lines file)
45 (if (file-exists? file)
46 (filter (lambda (s) (> (string-length s) 0))
47 (map string-trim-whitespace (read-file-lines file)))
48 '()))
49
50 ;; Elements [start, end) of list L.
51 (def (sublist l start end)
52 (let loop ((l (list-tail l start)) (n (- end start)) (acc '()))
53 (if (= n 0) (reverse acc) (loop (cdr l) (- n 1) (cons (car l) acc)))))
54
55 (def (index-of ch str)
56 (let loop ((i 0))
57 (cond ((= i (string-length str)) #f)
58 ((char=? (string-ref str i) ch) i)
59 (else (loop (+ i 1))))))
60
61 ;;; ------------------------------------------------------------------------
62 ;;; Hyper-parameters and global model state
63 ;;; ------------------------------------------------------------------------
64
65 (def n-layer 1)
66 (def n-embd 16)
67 (def block-size 16)
68 (def n-head 4)
69 (def head-dim 4)
70
71 (def docs '()) ; training strings
72 (def uchars "") ; sorted unique characters (the vocabulary)
73 (def bos 0) ; beginning/end-of-sequence token id
74 (def vocab-size 0)
75 (def state-dict (make-hash-table)) ; name -> matrix (vector of vectors of value)
76 (def params '()) ; every trainable value, in a fixed order
77
78 ;;; ------------------------------------------------------------------------
79 ;;; Autograd: a scalar `value` that remembers how it was computed
80 ;;; ------------------------------------------------------------------------
81
82 (defstruct value (data grad children local-grads))
83
84 (def (mkv data (children '()) (local-grads '()))
85 (make-value (exact->inexact data) 0.0 children local-grads))
86
87 ;; Lift plain numbers into constant values.
88 (def (ensure v) (if (value? v) v (mkv v)))
89
90 (def (v+ a b)
91 (let ((a (ensure a)) (b (ensure b)))
92 (mkv (+ (value-data a) (value-data b)) (list a b) '(1.0 1.0))))
93
94 (def (v* a b)
95 (let ((a (ensure a)) (b (ensure b)))
96 (mkv (* (value-data a) (value-data b)) (list a b)
97 (list (value-data b) (value-data a)))))
98
99 (def (vpow v p)
100 (let ((v (ensure v)))
101 (mkv (expt (value-data v) p) (list v)
102 (list (* p (expt (value-data v) (- p 1)))))))
103
104 (def (vlog v)
105 (let ((v (ensure v)))
106 (mkv (log (value-data v)) (list v) (list (/ 1.0 (value-data v))))))
107
108 (def (vexp v)
109 (let* ((v (ensure v)) (e (exp (value-data v))))
110 (mkv e (list v) (list e))))
111
112 (def (vrelu v)
113 (let ((v (ensure v)))
114 (mkv (max 0.0 (value-data v)) (list v)
115 (list (if (> (value-data v) 0.0) 1.0 0.0)))))
116
117 (def (vneg v) (v* v -1.0))
118 (def (v- a b) (v+ a (vneg b)))
119 (def (v/ a b) (v* a (vpow b -1.0)))
120
121 ;; Reverse-mode backpropagation: topologically sort the graph that produced
122 ;; V, then push gradients from V back to every node with the chain rule.
123 (def (backward v)
124 (let ((topo '())
125 (seen (make-hash-table-eq)))
126 (let build ((n v))
127 (unless (hash-get seen n)
128 (hash-put! seen n #t)
129 (for-each build (value-children n))
130 (set! topo (cons n topo))))
131 (value-grad-set! v 1.0)
132 (for-each (lambda (n)
133 (for-each (lambda (c g)
134 (value-grad-set! c (+ (value-grad c) (* g (value-grad n)))))
135 (value-children n) (value-local-grads n)))
136 topo)))
137
138 ;;; ------------------------------------------------------------------------
139 ;;; Model parameters
140 ;;; ------------------------------------------------------------------------
141
142 ;; NOUT x NIN matrix (vector of row vectors) of small random values.
143 (def (make-matrix nout nin (std 0.08))
144 (let ((m (make-vector nout)))
145 (do ((i 0 (+ i 1))) ((= i nout) m)
146 (let ((row (make-vector nin)))
147 (do ((j 0 (+ j 1))) ((= j nin))
148 (let ((v (mkv (random-gauss 0.0 std))))
149 (set! params (cons v params))
150 (vector-set! row j v)))
151 (vector-set! m i row)))))
152
153 (def (init-model)
154 (set! state-dict (make-hash-table))
155 (set! params '())
156 (let ((mat (lambda (k r c) (hash-put! state-dict k (make-matrix r c)))))
157 (mat "wte" vocab-size n-embd)
158 (mat "wpe" block-size n-embd)
159 (mat "lm_head" vocab-size n-embd)
160 (do ((i 0 (+ i 1))) ((= i n-layer))
161 (let ((lmat (lambda (s r c) (mat (format "layer~a.~a" i s) r c))))
162 (lmat "attn_wq" n-embd n-embd)
163 (lmat "attn_wk" n-embd n-embd)
164 (lmat "attn_wv" n-embd n-embd)
165 (lmat "attn_wo" n-embd n-embd)
166 (lmat "mlp_fc1" (* 4 n-embd) n-embd)
167 (lmat "mlp_fc2" n-embd (* 4 n-embd)))))
168 (set! params (reverse params)))
169
170 ;;; ------------------------------------------------------------------------
171 ;;; Architecture
172 ;;; ------------------------------------------------------------------------
173
174 (def (vsum vs) (foldl (lambda (v acc) (v+ acc v)) (mkv 0.0) vs))
175
176 ;; Matrix-vector product: W (vector of rows) times X (list of values).
177 (def (vlinear x w)
178 (map (lambda (row) (vsum (map v* (vector->list row) x)))
179 (vector->list w)))
180
181 (def (vsoftmax logits)
182 (let* ((mx (apply max (map value-data logits)))
183 (exps (map (lambda (v) (vexp (v- v mx))) logits))
184 (total (vsum exps)))
185 (map (lambda (e) (v/ e total)) exps)))
186
187 (def (vrmsnorm x)
188 (let ((scale (vpow (v+ (v/ (vsum (map (lambda (xi) (v* xi xi)) x)) (length x))
189 1e-5)
190 -0.5)))
191 (map (lambda (xi) (v* xi scale)) x)))
192
193 ;; One KV-cache slot per layer; each slot holds a list of key (or value)
194 ;; vectors, one per position processed so far.
195 (def (make-kv-cache) (make-vector n-layer '()))
196
197 (def (cache-push! cache li item)
198 (vector-set! cache li (append (vector-ref cache li) (list item))))
199
200 ;; Forward pass for a single token at position POS-ID. Returns logits.
201 (def (gpt tok-id pos-id keys vals)
202 (let* ((sd (lambda (li s) (hash-ref state-dict (format "layer~a.~a" li s))))
203 (x (vrmsnorm (map v+
204 (vector->list (vector-ref (hash-ref state-dict "wte") tok-id))
205 (vector->list (vector-ref (hash-ref state-dict "wpe") pos-id))))))
206 (do ((li 0 (+ li 1))) ((= li n-layer))
207 ;; 1) multi-head causal self-attention with residual connection
208 (let* ((xr x)
209 (xn (vrmsnorm x))
210 (q (vlinear xn (sd li "attn_wq")))
211 (k (vlinear xn (sd li "attn_wk")))
212 (v (vlinear xn (sd li "attn_wv"))))
213 (cache-push! keys li k)
214 (cache-push! vals li v)
215 (let* ((heads
216 (apply append
217 (map (lambda (h)
218 (let* ((hs (* h head-dim))
219 (he (+ hs head-dim))
220 (q-h (sublist q hs he))
221 (k-h (map (lambda (ki) (sublist ki hs he)) (vector-ref keys li)))
222 (v-h (map (lambda (vi) (sublist vi hs he)) (vector-ref vals li)))
223 ;; attention weights over all cached positions
224 (aw (vsoftmax
225 (map (lambda (kt)
226 (v/ (vsum (map v* q-h kt)) (sqrt head-dim)))
227 k-h))))
228 ;; weighted sum of value vectors
229 (let loop ((j 0) (acc '()))
230 (if (= j head-dim)
231 (reverse acc)
232 (loop (+ j 1)
233 (cons (vsum (map (lambda (w vt) (v* w (list-ref vt j)))
234 aw v-h))
235 acc))))))
236 (iota n-head))))
237 (attn-out (vlinear heads (sd li "attn_wo"))))
238 (set! x (map v+ attn-out xr))))
239 ;; 2) MLP with residual connection
240 (let* ((xr x)
241 (h (map vrelu (vlinear (vrmsnorm x) (sd li "mlp_fc1"))))
242 (out (vlinear h (sd li "mlp_fc2"))))
243 (set! x (map v+ out xr))))
244 (vlinear x (hash-ref state-dict "lm_head"))))
245
246 ;;; ------------------------------------------------------------------------
247 ;;; Training
248 ;;; ------------------------------------------------------------------------
249
250 (def (tokenize doc)
251 (append (list bos)
252 (map (lambda (ch) (index-of ch uchars)) (string->list doc))
253 (list bos)))
254
255 (def (run-training steps)
256 (let* ((lr 0.01) (b1 0.85) (b2 0.99) (eps 1e-8)
257 (pvec (list->vector params))
258 (np (vector-length pvec))
259 (m (make-vector np 0.0))
260 (mv (make-vector np 0.0))
261 (ndocs (length docs)))
262 (do ((step 0 (+ step 1))) ((= step steps))
263 (let* ((tokens (list->vector (tokenize (list-ref docs (modulo step ndocs)))))
264 (n (min block-size (- (vector-length tokens) 1)))
265 (keys (make-kv-cache))
266 (vals (make-kv-cache))
267 ;; cross-entropy loss: -log p(next token), averaged over positions
268 (losses (let loop ((pos 0) (acc '()))
269 (if (= pos n)
270 acc
271 (let* ((logits (gpt (vector-ref tokens pos) pos keys vals))
272 (probs (list->vector (vsoftmax logits))))
273 (loop (+ pos 1)
274 (cons (vneg (vlog (vector-ref probs (vector-ref tokens (+ pos 1)))))
275 acc))))))
276 (loss (v/ (vsum losses) n))
277 (t1 (+ step 1))
278 (lr-t (* lr (- 1.0 (/ step (exact->inexact steps))))))
279 (backward loss)
280 ;; Adam update with bias correction and linear LR decay
281 (do ((i 0 (+ i 1))) ((= i np))
282 (let* ((p (vector-ref pvec i))
283 (g (value-grad p)))
284 (vector-set! m i (+ (* b1 (vector-ref m i)) (* (- 1 b1) g)))
285 (vector-set! mv i (+ (* b2 (vector-ref mv i)) (* (- 1 b2) g g)))
286 (let ((mh (/ (vector-ref m i) (- 1 (expt b1 t1))))
287 (vh (/ (vector-ref mv i) (- 1 (expt b2 t1)))))
288 (value-data-set! p (- (value-data p) (/ (* lr-t mh) (+ (sqrt vh) eps))))
289 (value-grad-set! p 0.0))))
290 (when (or (< t1 10) (zero? (modulo t1 25)) (= t1 steps))
291 (printf "step ~a/~a | loss ~a\n" t1 steps
292 (/ (round (* 10000 (value-data loss))) 10000.0)))))))
293
294 ;;; ------------------------------------------------------------------------
295 ;;; Inference
296 ;;; ------------------------------------------------------------------------
297
298 ;; Sample an index from the (unnormalised) weight vector.
299 (def (random-choice weights)
300 (let* ((n (vector-length weights))
301 (r (* (random-real) (foldl + 0.0 (vector->list weights)))))
302 (let loop ((i 0) (acc 0.0))
303 (if (= i (- n 1))
304 i
305 (let ((acc (+ acc (vector-ref weights i))))
306 (if (< r acc) i (loop (+ i 1) acc)))))))
307
308 (def (run-inference (num-samples 20) (temperature 0.5))
309 (displayln "\n--- inference (new, hallucinated names) ---")
310 (do ((i 0 (+ i 1))) ((= i num-samples))
311 (let ((keys (make-kv-cache)) (vals (make-kv-cache)))
312 (let loop ((pos 0) (tok bos) (sample '()))
313 (if (= pos block-size)
314 (printf "sample ~a: ~a\n" (+ i 1) (list->string (reverse sample)))
315 (let* ((lt (map (lambda (l) (/ (value-data l) temperature))
316 (gpt tok pos keys vals)))
317 (mx (apply max lt))
318 (probs (list->vector (map (lambda (v) (exp (- v mx))) lt)))
319 (next (random-choice probs)))
320 (if (= next bos)
321 (printf "sample ~a: ~a\n" (+ i 1) (list->string (reverse sample)))
322 (loop (+ pos 1) next (cons (string-ref uchars next) sample)))))))))
323
324 ;;; ------------------------------------------------------------------------
325 ;;; Main
326 ;;; ------------------------------------------------------------------------
327
328 (def (run-microgpt steps: (steps 1000) names-file: (names-file "names.txt"))
329 (random-source-randomize! default-random-source)
330 (set! docs (shuffle-list (read-lines names-file)))
331 (when (null? docs)
332 (error "No training data: missing or empty file" names-file))
333 (printf "num docs: ~a\n" (length docs))
334 (let ((chars (make-hash-table)))
335 (for-each (lambda (doc) (for-each (lambda (c) (hash-put! chars c #t)) (string->list doc)))
336 docs)
337 (set! uchars (list->string (sort (hash-keys chars) char<?)))
338 (set! bos (string-length uchars))
339 (set! vocab-size (+ bos 1)))
340 (printf "vocab size: ~a\n" vocab-size)
341 (init-model)
342 (printf "num params: ~a\n" (length params))
343 (run-training steps)
344 (run-inference))
345
346 ;; Command line: [steps] [names-file]
347 (def (main . args)
348 (run-microgpt steps: (if (pair? args) (string->number (car args)) 1000)
349 names-file: (if (and (pair? args) (pair? (cdr args))) (cadr args) "names.txt")))
Running the Code and Expected Output
You can run microGPT either with the interpreter (gxi microgpt.ss 20) or compiled into native binary with make run for roughly 10x faster execution:
1 $ make run
2 num docs: 32033
3 vocab size: 27
4 num params: 4192
5 step 1/1000 | loss 3.4312
6 step 2/1000 | loss 3.3245
7 step 3/1000 | loss 3.2981
8 step 4/1000 | loss 3.1420
9 ...
10 step 975/1000 | loss 2.4510
11 step 1000/1000 | loss 2.4251
12
13 --- inference (new, hallucinated names) ---
14 sample 1: mamare
15 sample 2: margoe
16 sample 3: kian
17 sample 4: brayden
18 sample 5: adaline
19 sample 6: ellis
20 sample 7: marian
21 sample 8: zaida
22 sample 9: kevin
23 sample 10: amara
24 sample 11: jaxon
25 sample 12: colin
26 sample 13: eliana
27 sample 14: nolan
28 sample 15: briar
29 sample 16: mira
30 sample 17: dakota
31 sample 18: layla
32 sample 19: rowan
33 sample 20: elias
Interpreting the Results
The metrics printed during training reveal the learning dynamics of the transformer:
- Initial Loss Baseline: In step 1, the cross-entropy loss begins at
. For a vocabulary of size
, uniform random guessing yields an expected loss of
. The model begins precisely at the random guessing floor.
- Convergence and Convergence Rate: Over 1,000 steps, the loss steadily declines from
to
. The transformer learns English phonotactic rules, common vowel-consonant pairings, and typical word-ending characters.
- Generative Sampling: During inference, sampling at
temperature = 0.5produces realistic names likemamare,margoe,zaida, andlayla. The model invents plausible, previously unseen names by chaining its learned character transition probabilities.
Wrap Up
In this chapter we implemented microGPT, a complete 4,192-parameter transformer language model with custom reverse-mode autograd in pure Gerbil Scheme. By building everything on top of Scheme scalar values, we peeled away the abstractions of modern deep learning frameworks, showing how attention heads, KV caches, layer normalization, backpropagation, and Adam optimization operate at a foundational mathematical level.
Optional Practice Problems
- GeLU Activation Function: Replace
vreluinmicrogpt.sswith the Gaussian Error Linear Unit (GeLU) approximation:
.
- Multi-Layer Stacking: Increase
n-layerto 2 or 3 in the hyperparameters and adjustinit-modelandgptto pass hidden representations sequentially through the stacked layers. - Top-k and Top-p (Nucleus) Sampling: Extend
run-inferenceto support Top-k truncation (retaining only the topkhighest logit values before softmax) or Top-p nucleus filtering.