A decoder-only transformer is a useful way to study how language models turn a sequence of tokens into predictions. The most reliable implementation path is to keep each tensor shape and data dependency explicit.

Start with the contract

Token IDs have shape [batch, sequence]. Embeddings convert them to [batch, sequence, width]. Every transformer block should preserve that shape so the blocks can be stacked without special cases.

Query, key and value projections divide the width into attention heads. Attention scores then have shape [batch, heads, sequence, sequence]. Apply the causal mask before softmax so a position cannot read future tokens.

Keep the residual path clear

x = x + attention(normalize(x))
x = x + feed_forward(normalize(x))

This form makes the data flow easy to inspect and each sublayer easy to compare with a reference. Before scaling the model, overfit a tiny batch and check that changing a future token cannot alter an earlier output.