liveBook · Manning

Feedforward network

As explained in Build a Large Language Model (From Scratch)

The transformer subcomponent that applies position-wise nonlinear transformations after attention.

FeedForward is the position-wise nonlinear subcomponent of a transformer block. It applies a linear expansion, GELU activation, and linear contraction independently to each token representation, preserving the input shape while enabling richer intermediate representations. section 4.3 section 4.5

The module’s data flow is:

  • Receive token embeddings with shape batch × tokens × embedding size. section 4.3
  • Expand each embedding from 768 to 3,072 values with a linear layer. section 4.3
  • Apply GELU, then contract the representation back to 768 dimensions. section 4.3
  • Return the same batch, token, and embedding dimensions for residual transformer-block processing. section 4.5

Shape-preserving execution

A FeedForward instance configured for the 124-million-parameter GPT model accepts a random tensor shaped [2, 3, 768] and produces torch.Size([2, 3, 768]). Internally, every token vector expands to 3,072 values before returning to 768. section 4.3

Listing 4.4 A feed forward neural network module
class FeedForward(nn.Module):
    def __init__(self, cfg):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(cfg["emb_dim"], 4 * cfg["emb_dim"]),
            GELU(),
            nn.Linear(4 * cfg["emb_dim"], cfg["emb_dim"]),
        )

    def forward(self, x):
        return self.layers(x)

Use the implementation listing to inspect the PyTorch Sequential module and its two Linear layers surrounding GELU. section 4.3

How Build a Large Language Model (From Scratch) covers it

How deep it goes
Defines the two-layer GELU module, including fourfold expansion and shape-preserving contraction, without deriving optimization behavior formally.
Examples
Demonstrates a 2×3×768 tensor flowing through 768→3,072→768 dimensions and returning shape [2, 3, 768].
What it assumes
Assumes token embeddings and configuration dictionaries while defining the module’s layers and tensor flow directly.
What you can do after
Build it from scratch in PyTorch using configurable Linear layers and a GELU activation.
How it connects
Connects FeedForward with multi-head attention, layer normalization, dropout, GELU, and shortcut connections inside transformer blocks.

Also explained in

Compare how 13 books explain feedforward network →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Large Language Model (From Scratch). The section links point to the parts of the book it draws on.