Building a Transformer

David I. Inouye

Dynamic Content · Last Updated: October 30, 2026

A transformer combines context mixing and feature transformation

Transform features → preserve a residual path → normalize → stack blocks.

Keep the same task: use an email prefix to predict its next token.

Attention mixes positions; a shared MLP transforms each row

Three token positions are drawn side by side with inputs below and outputs above. Three token rows enter the same MLP independently. Each expands from d to m features, applies ReLU, and returns to d; there are no cross-position arrows.

\[\operatorname{MLP}(H)=\operatorname{ReLU}(HW_1^{\mathsf T}+\boldsymbol{1}\boldsymbol{b}_1^{\mathsf T})W_2^{\mathsf T}+\boldsymbol{1}\boldsymbol{b}_2^{\mathsf T}\]

\[H\in\mathbb{R}^{L\times d},\quad W_1\in\mathbb{R}^{m\times d},\quad W_2\in\mathbb{R}^{d\times m}\]

Same parameters at every position; separate parameters in each block.

A residual path adds a learned update without changing the shape

Reading upward, an L by d state branches into an unchanged bypass and a learned update F, also L by d. Elementwise addition returns L by d.

\[H_{\mathrm{out}}=H+F(H)\]

The attention output projection and the MLP’s last layer both return \(d\) features.

LayerNorm normalizes one token’s features at a time

Like BatchNorm: subtract a mean, divide by a standard deviation, then learn a scale and shift.

\[\mu_\ell=\frac1d\sum_{j=1}^{d}h_{\ell j},\qquad \sigma_\ell^2=\frac1d\sum_{j=1}^{d}(h_{\ell j}-\mu_\ell)^2\]

\[\operatorname{LN}(\boldsymbol{h}_\ell)=\boldsymbol{\gamma}\odot \frac{\boldsymbol{h}_\ell-\mu_\ell\boldsymbol{1}} {\sqrt{\sigma_\ell^2+\epsilon}}+\boldsymbol{\beta}\]

  • BatchNorm (CNN): one channel across batch examples and spatial locations.
  • LayerNorm: one token across its \(d\) features—the last axis of [B,L,d].

At evaluation, LayerNorm still uses that token’s statistics; BatchNorm usually uses running statistics.

A pre-norm block adds two shape-preserving updates

From bottom to top, H passes through LayerNorm, causal MHA and residual addition, then LayerNorm, a row MLP and residual addition. Both stages preserve L by d shape.

\[U=H+\operatorname{MHA}_{\mathrm{causal}}(\operatorname{LN}_1(H))\] \[H_{\mathrm{out}}=U+\operatorname{MLP}(\operatorname{LN}_2(U))\]

Pre-norm is the usual modern LLM default. The original Transformer used post-norm.

Pre-norm Post-norm
\(H+F(\operatorname{LN}(H))\) \(\operatorname{LN}(H+F(H))\)
Normalize before the branch. Normalize after addition.

Pre-norm leaves the bypass untouched.

Stacked blocks turn token features into next-token logits

Token IDs at the bottom enter learned embeddings plus additive positions, then N distinct pre-norm blocks, final LayerNorm, and a vocabulary head producing L by V logits. An alternative replaces additive positions with RoPE in every block's queries and keys.

\[H^{(0)}=E[w_{0:L},:]+P,\qquad Y=\operatorname{LN}_{\mathrm{final}}(H^{(N)})W_{\mathrm{vocab}}^{\mathsf T}+\boldsymbol{1}\boldsymbol{c}^{\mathsf T}\]

\[H^{(N)}\in\mathbb{R}^{L\times d},\qquad W_{\mathrm{vocab}}\in\mathbb{R}^{v\times d},\qquad Y\in\mathbb{R}^{L\times v}\]

One length-\(L\) input solves \(L\) prefix-prediction problems

Along the bottom, five inputs BOS, please, send, the, report feed causal output rows. Targets at the top are shifted one position: please, send, the, report, EOS. Every output reads only its prefix and contributes one loss.

\[\mathcal{L}(\theta)=-\frac{1}{L}\sum_{\ell=0}^{L-1}\log p_\theta(w_{\ell+1}\mid w_0,\ldots,w_\ell).\]

Known inputs allow parallel work; the mask preserves each allowed prefix.

Backpropagation follows different dependency graphs

The same five inputs and targets are used for both models. The RNN has a left-to-right hidden-state chain with reverse gradient arrows. A simplified transformer layer has causal connections between two rows of token states; the last row's reverse paths fan back to all allowed earlier positions. All losses contribute gradients.

Transformer benefit: parallel work across positions in forward and backward computation.

Can one forward pass score all shifted targets?

The training batch contains each full email.

Which model change would let an early prediction read its future target?

A. Compute all causal output rows together

B. Normalize each token over its own features

C. Remove the causal attention mask

C. Parallel computation is valid when every path respects the allowed prefix.

A causal decoder is the common decoder-only LLM architecture

Three upward architecture diagrams. Encoder-only uses Q/K/V from all input embeddings and a task head, with ViT as an example. Our causal decoder uses Q/K/V from the prefix with causal self-attention. The original 2017 encoder–decoder has source self-attention, target causal self-attention, and cross-attention with Q from target and K/V from source. Residual and normalization paths are omitted.

Our email model is a causal decoder. Other tasks can use different information paths and heads.