liveBook · Manning

Linear layer

As explained in Transformers in Action

nn.Linear is a PyTorch module that applies an affine linear transformation to its input.

A linear layer is a fully connected transformation that maps a fixed-length input vector to an output vector. Every output unit connects to every input unit, allowing the layer to learn combinations of the input features. section 2.2.4

A position-wise feed-forward network uses one linear layer to expand the vector into a higher-dimensional space, applies a nonlinear activation, and uses another linear layer to restore the original dimension. The same transformation operates independently at each sequence position. section 2.2.4

Two linear layers in a position-wise FFN

class PositionwiseFeedforward(nn.Module): def __init__(self, input_dim, hidden_dim, dropout=0.1): super().__init__() self.dropout = nn.Dropout(dropout) self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, input_dim) def forward(self, x): x = self.dropout(torch.relu(self.fc1(x))) return self.fc2(x) Here, fc1 increases representational capacity, while fc2 returns the result to the model's original width. section 2.2.4

Figure 6.4 Linear projection W maps patch vectors from an input space ℝdto an embedding space ℝk. Dashed arrows indicate the mapping of example patches through W.
figure

Visualizes a linear projection mapping flattened image-patch vectors from the input space into the transformer's embedding space. section 6.3.1

How Transformers in Action covers it

How deep it goes
Explains full connectivity, dimensional expansion and contraction, nonlinear placement, and independent reuse across sequence positions.
Examples
Uses a position-wise FFN, a vision-transformer patch projection, and a masked-token prediction head.
What it assumes
Assumes fixed-length vectors and basic neural-network layers while explaining connectivity and dimensional reshaping through examples.
What you can do after
Build it from scratch as a PyTorch module inside an FFN or as a projection from patches or hidden states.
How it connects
Connects linear layers to fully connected networks, nonlinear activation, transformer hidden size, patch embeddings, and masked language modeling.

Also explained in

Compare how 13 books explain linear layer →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Transformers in Action. The section links point to the parts of the book it draws on.