Building a GPT-1-Style Decoder-Only Transformer From Scratch on an AMD RX 6900 XT
A lot of people talk about GPT models as if they are magic. I wanted to understand one properly, not just use one through an API. So I built a small, from-scratch GPT lab in PyTorch, trained it locally on Tiny Shakespeare, and got it running on my AMD Radeon RX 6900 XT through ROCm, using the normal torch.cuda API surface. The result is not “GPT-1” in the historical sense, but it is absolutely a GPT-1-style decoder-only transformer: token embeddings, positional embeddings, masked self-attention, transformer blocks, next-token prediction, training loop, checkpointing, and text generation.
What I like about this project is that it is small enough to read end to end. The repo is deliberately built as a learning-oriented lab rather than a production stack. It implements a minimal decoder-only transformer, trains it as a char-level language model on data/tinyshakespeare.txt, saves checkpoints and history under runs/, and includes scripts for ROCm smoke testing, sample training, full training, and chatting with a trained checkpoint.
With the current full config, the model uses a context length of 256, embedding size 192, 6 attention heads, 6 transformer blocks, dropout 0.1, and ends up at 2,733,312 parameters. In one full run recorded in the repo, it trained for 6000 steps, finished with a train loss of 1.0716 and validation loss of 1.4822, and saved a checkpoint of roughly 10.7 MB
What “decoder-only transformer” actually means
The transformer architecture introduced in Attention Is All You Need is built around attention rather than recurrence, and scaled dot-product attention is the core mechanism: compare queries and keys, normalize with a softmax, and use the resulting weights to mix values. GPT-style models take the transformer idea and use the decoder side autoregressively, meaning the model predicts the next token using only tokens to the left.
That “only look left” rule is the whole reason GPT models can generate text one token at a time. If the token at position t could peek at t+1, training would be cheating. In my repo, this is enforced with a lower-triangular causal mask created with torch.tril(...), and attention scores for illegal future positions are filled with a very negative value before softmax. In the single-head attention implementation, the code computes
att = (q @ k.transpose(-2, -1)) * self.scale
then slices the mask to the active sequence length and applies
att = att.masked_fill(~m, torch.finfo(att.dtype).min)
before softmax. The multi-head version does the same idea across heads.
So in plain English, the model is doing this:
- Turn characters into vectors.
- Add position information so order matters.
- Repeatedly let each position look back over earlier positions and decide what matters.
- Refine those representations with feed-forward layers.
- Turn the final representation at each position into logits over the vocabulary.
-
Train the model so the logits at position
tpredict the real token att+1.
Why I used Tiny Shakespeare and character-level tokenization
I intentionally kept the data side simple. The repo builds a vocabulary directly from the unique characters in the text using sorted(set(text)), then constructs stoi and itos mappings for encoding and decoding. On this dataset, the resulting vocabulary size is 65, which is why the README’s parameter breakdown shows token embeddings of 65 x 192 and an LM head of 192 x 65.
Character-level modeling is not how modern large language models usually operate, but it is fantastic for learning. You avoid the complexity of BPE or SentencePiece tokenization. The model sees raw characters like:
"To be, or not to be"
and turns them into integer IDs one character at a time. That makes the data pipeline brutally simple and very transparent. The trade-off is that the sequence length has to be longer to represent the same amount of language, because a single word becomes several tokens instead of one or two subword pieces.
The data module then converts the full encoded corpus into a tensor, splits it 90/10 into train and validation streams, and samples random windows of length T+1. From each window it creates:
-
x = data[i : i + T] -
y = data[i + 1 : i + 1 + T]
So y is just x shifted one step to the left. That is the whole next-token prediction problem.
A tiny toy example makes this clearer. Imagine the text fragment:
ROMEO
and suppose the model samples a window of length 5.
Then:
-
x = [R, O, M, E] -
y = [O, M, E, O]
At position 0, the model sees R and tries to predict O.
At position 1, it sees R O and tries to predict M.
At position 2, it sees R O M and tries to predict E.
That is language modeling in its simplest form.
The embedding stage: how integers become useful signals
A transformer cannot do anything with raw token IDs. It needs dense vectors.
In this repo, the model uses two embedding tables:
-
a token embedding:
nn.Embedding(vocab_size, n_embd) -
a position embedding:
nn.Embedding(block_size, n_embd)
Then it adds them together and applies dropout. In code terms:
-
tok_emb = self.token_embedding(idx) -
pos_emb = self.position_embedding(pos) -
x = self.drop(tok_emb + pos_emb)
This matters because token embeddings answer what the symbol is, while positional embeddings answer where it is in the sequence. Without position embeddings, the model would know which characters are present but not their order. A model that cannot tell the difference between "dog bites man" and "man bites dog" is not going very far.
Self-attention with a worked example
Attention sounds complicated until you reduce it to a question:
For the current token, which earlier tokens matter most right now?
Each position creates three vectors:
- Query: what am I looking for?
- Key: what kind of information do I contain?
- Value: what information do I contribute if selected?
The repo does this with three linear layers for Q, K, and V. In the single-head version, the attention score matrix is computed by multiplying queries with transposed keys and scaling by 1 / sqrt(h). Then the causal mask is applied, then softmax, then the weighted sum of values is taken.
Here is a toy numerical example.
Suppose a sequence has four positions:
[R, O, M, E]
and we are computing attention for the last token E. Imagine its query compared against the four keys gives raw scores:
[1.2, 0.3, 2.0, 0.8]
After softmax, those might become something like:
[0.24, 0.10, 0.44, 0.22]
That means the representation for E is rebuilt as a weighted mixture of the value vectors for R, O, M, and E, with most weight landing on M.
Now imagine we are at token M instead. The model must not look into the future, so the score for E gets masked out before softmax:
[1.2, 0.3, 2.0, -inf]
Softmax then redistributes probability over the legal positions only. That is how causal attention preserves autoregressive generation.
Why multi-head attention is better than one big head
A single attention head can learn one pattern of retrieval, but language is messy. Sometimes the useful signal is syntax, sometimes speaker identity, sometimes rhyme, sometimes punctuation, sometimes long-range structure. Multi-head attention lets the model learn several different lookup patterns in parallel. That is exactly the motivation behind the original transformer’s multi-head design, and my repo follows the same basic idea.
In my full config:
-
n_embd = 192 -
n_head = 6
So each head gets:
-
head_size = 192 / 6 = 32
The multi-head module projects the input to Q, K, and V of width 192, reshapes them into [B, H, T, head_size], computes attention independently per head, and then recombines the heads back into [B, T, C] before a final projection.
Conceptually, you can think of it like this:
- Head 1 might learn short-range local continuation.
- Head 2 might track who is speaking.
- Head 3 might focus on punctuation boundaries.
- Head 4 might pick up repeated phrasing.
- Head 5 might care about meter or structure.
- Head 6 might do something more diffuse and semantic.
Those are illustrative examples, but that is the general reason multi-head attention works so well: it lets the model look at the same sequence through multiple lenses at once.
The transformer block: attention plus computation
Attention by itself is not the whole story. After the model mixes information across positions, it still needs to transform each position’s features nonlinearly. That is where the feed-forward network comes in.
Each transformer block in this repo uses:
- LayerNorm
- Multi-head causal self-attention
- Residual connection
- LayerNorm
- Feed-forward network
- Residual connection
The feed-forward network expands the embedding dimension by a factor of 4, applies GELU, then projects back down:
192 -> 768 -> 192 in the full model.
This is important. Attention is the communication mechanism between positions. The feed-forward network is the per-token computation mechanism. If attention answers “what context should I gather?”, the FFN answers “now that I have that context, how should I transform my internal representation?”
The residual connections are equally important. Instead of forcing every layer to completely rewrite the signal, the block learns a correction to the existing representation. That usually makes deep networks easier to optimize and more stable.
The full model path from input to logits
At the top level, the model is straightforward:
-
input token IDs of shape
[B, T] - token embedding
- position embedding
- dropout
- 6 transformer blocks
- final LayerNorm
- linear language-model head
-
logits of shape
[B, T, vocab_size]
The parameter breakdown in the README is one of the nicest parts of the repo because it makes the size of the network concrete rather than abstract:
-
token embedding:
12,480 -
position embedding:
49,152 -
six blocks together:
2,658,816 -
final LayerNorm:
384 -
LM head:
12,480
Total: 2,733,312 parameters.
That is tiny by modern standards, but large enough to teach the real mechanics of transformer training.
How training works
Training is next-token prediction with cross-entropy loss. In the model’s forward, once logits are produced, the code flattens [B, T, vocab_size] into [B*T, vocab_size], flattens targets into [B*T], and computes F.cross_entropy(...).
The training loop itself is refreshingly clean:
- move model to device
- create an AdamW optimizer
- sample a training batch
- forward pass
- zero gradients
- backward pass
- optionally clip gradients
- optimizer step
- every so often, estimate train/val loss and append to history
In the full config, the main training hyperparameters are:
-
batch size:
64 -
block size:
256 -
learning rate:
3e-4 -
weight decay:
0.01 -
max steps:
6000 -
eval interval:
100 -
eval steps:
20 -
grad clip:
1.0 -
device:
"cuda"
After training, scripts/train_full.py saves both a checkpoint and a JSON history file. The checkpoint includes model weights, config, vocab mappings, data path, and history, while history.json stores the recorded metrics over time.
That makes the repo feel like a real training workflow rather than just a notebook experiment.
How generation works
Generation is just repeated next-token prediction.
The model’s generate method:
-
crops the running sequence to the last
block_sizetokens - runs a forward pass
- takes the logits from the final position
- applies temperature
- optionally applies top-k filtering
- softmaxes into probabilities
-
samples the next token with
torch.multinomial - appends it to the running sequence
That loop is simple, but it captures the essence of autoregressive generation. The model is not writing an entire paragraph in one shot. It is repeatedly answering one question:
Given everything I have seen so far, what is the next most plausible token?
And then it feeds its own answer back in as part of the next context window.
Why the AMD / ROCm angle matters
One part of this project I particularly liked was proving that this kind of learning workflow does not have to be NVIDIA-only. The repo includes a ROCm smoke test that checks torch.cuda.is_available(), prints the GPU name and VRAM, runs an FP16 matmul benchmark, and verifies a backward pass. The requirements file is pinned to the ROCm wheel index with torch==2.8.0, torchvision==0.23.0, and torchaudio==2.8.0.
That matters because one of the easiest ways to make deep learning feel inaccessible is to imply that the only valid setup is a huge datacenter-grade NVIDIA workflow. This repo shows the opposite, you can absolutely learn the core ideas of GPT-style models on consumer AMD hardware, provided your ROCm stack is working.
What this project is, and what it is not
This repo is a strong educational implementation. It contains the real moving parts of a GPT-style model, masked self-attention, multi-head attention, transformer blocks, training and sampling. But it is also intentionally compact and non-production. It is char-level, small, and designed for clarity.
That is a feature, not a flaw.
A lot of people jump straight from “I know how to call a model” to “I understand transformers.” Usually they do not. Building one forces you to understand:
- why masking matters
- why embeddings and positions are separate
- why attention scores become probabilities
- why multi-head splitting and recombination work
- why the FFN exists
- why cross-entropy is the right loss for next-token prediction
- why generation is just iterative sampling from logits
Once you have built that once, the larger literature starts to make far more sense.
Final thoughts
For me, the point of this repo was not to chase benchmark glory. It was to take a model family that usually feels abstract and make it concrete. By the end, I had a working GPT-style decoder-only transformer that I could inspect, train, save, reload, and sample from locally on my RX 6900 XT. The model is small, but the lessons are not.
If you want to understand modern language models, there is enormous value in building one that fits in your head. Here is a link to the github repo.