🤖 AI/ML

Feed Forward Network

Feed Forward Network

A neural network with only forward connections. Included in each Transformer block.

📖 Detailed Explanation

A Feed Forward Network (FFN) is a neural network in which signals flow in only one direction, from input to output. Because it has no recurrent connections, its structure is simple and training is stable. In the Transformer architecture, an FFN is placed after Self-Attention in each block and performs a nonlinear transformation.

The history of the FFN goes back to Frank Rosenblatt's perceptron in 1958. The multilayer perceptron (MLP) developed from it and became the foundation of modern deep learning. When the Transformer was proposed in the 2017 paper "Attention is All You Need," the FFN became established as a core component alongside attention.

The FFN in a Transformer consists of two linear transformations and an activation function. It is expressed by the formula FFN(x) = max(0, xW1 + b1)W2 + b2, and originally used ReLU. The GPT family uses GELU, and LLaMA uses the SwiGLU activation function. The hidden dimension is usually set to 4 times the input dimension (if d_model=768, then d_ff=3072).

In practice, the FFN accounts for about 2/3 of a Transformer's parameters, so it has a large impact on model size and computational cost. Mixture of Experts (MoE) is a technique that splits the FFN into several "experts" and activates them conditionally to improve efficiency. GPT-4, Mixtral, and others use MoE to reduce computation relative to the number of parameters.

💻 Code Example

import torch
import torch.nn as nn
import torch.nn.functional as F

# 1. 기본 Feed Forward Network (Transformer 스타일)
class FeedForward(nn.Module):
    def __init__(self, d_model=512, d_ff=2048, dropout=0.1):
        super().__init__()
        # 두 개의 선형 변환
        self.linear1 = nn.Linear(d_model, d_ff)
        self.linear2 = nn.Linear(d_ff, d_model)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        # ReLU 활성화 (원본 Transformer)
        x = self.linear1(x)
        x = F.relu(x)
        x = self.dropout(x)
        x = self.linear2(x)
        return x

# 2. GELU 활성화 (GPT 스타일)
class GPTFeedForward(nn.Module):
    def __init__(self, d_model=768, d_ff=3072, dropout=0.1):
        super().__init__()
        self.c_fc = nn.Linear(d_model, d_ff)
        self.c_proj = nn.Linear(d_ff, d_model)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        x = self.c_fc(x)
        x = F.gelu(x)  # GPT는 GELU 사용
        x = self.c_proj(x)
        x = self.dropout(x)
        return x

# 3. SwiGLU 활성화 (LLaMA 스타일) - 더 효율적
class SwiGLUFeedForward(nn.Module):
    def __init__(self, d_model=512, d_ff=1376):  # d_ff는 보통 2/3 * 4 * d_model
        super().__init__()
        self.w1 = nn.Linear(d_model, d_ff, bias=False)
        self.w2 = nn.Linear(d_ff, d_model, bias=False)
        self.w3 = nn.Linear(d_model, d_ff, bias=False)  # Gate

    def forward(self, x):
        # SwiGLU: Swish(x * W1) * (x * W3) * W2
        return self.w2(F.silu(self.w1(x)) * self.w3(x))

# 4. Transformer Block에서 FFN 사용
class TransformerBlock(nn.Module):
    def __init__(self, d_model=512, n_heads=8, d_ff=2048, dropout=0.1):
        super().__init__()
        self.attention = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
        self.ffn = FeedForward(d_model, d_ff, dropout)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x):
        # Self-Attention with residual
        attn_out, _ = self.attention(x, x, x)
        x = self.norm1(x + self.dropout(attn_out))

        # FFN with residual
        ffn_out = self.ffn(x)
        x = self.norm2(x + self.dropout(ffn_out))
        return x

# 사용 예시
batch_size, seq_len, d_model = 2, 10, 512
x = torch.randn(batch_size, seq_len, d_model)

ffn = FeedForward(d_model=512, d_ff=2048)
output = ffn(x)
print(f"입력: {x.shape}, 출력: {output.shape}")

# 파라미터 수 계산
total_params = sum(p.numel() for p in ffn.parameters())
print(f"FFN 파라미터 수: {total_params:,}")  # 512*2048 + 2048 + 2048*512 + 512

🗣️ Say It Like This in Practice

In a model architecture design meeting

"I set the FFN's hidden dimension to 3072, which is 4 times d_model, but we're running out of memory, so I'm thinking of reducing it to 2048. If you're worried about performance degradation, it might be better to switch to SwiGLU. According to the LLaMA paper, SwiGLU performs better at the same number of parameters."

In an LLM optimization discussion

"66% of the model's parameters are in the FFN. If you switch to MoE, you can increase the total number of parameters 8-fold while keeping the active parameters the same. Inference speed stays almost the same and only performance goes up. Mixtral achieved GPT-3.5-level performance this way."

In a deep learning technical interview

"The role of the FFN in a Transformer is to apply a nonlinear transformation to the information gathered by attention. Attention learns the relationships between tokens, and the FFN processes each token's representation independently. According to recent research, the FFN works like a kind of key-value memory and stores knowledge."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Setting the hidden dimension

The FFN's hidden dimension (d_ff) is usually set to 4 times d_model. If it is too small, expressiveness is insufficient, and if it is too large, memory and computational cost increase sharply. When using SwiGLU, a gate layer is added, so d_ff must be adjusted to (2/3) * 4 * d_model to keep the parameter count similar.

2
Choosing an activation function

ReLU is simple, but it has the dying ReLU problem, where the gradient becomes 0 for negative inputs. GELU has been validated through its use in GPT, and SwiGLU showed better performance in LLaMA. When designing a new model, try SwiGLU first.

3
Whether to use bias

Recent LLMs (LLaMA, Mistral, etc.) tend to remove the bias from the FFN. There is almost no performance difference without bias, and the number of parameters and the amount of computation are reduced. In large-scale models, this saving can be substantial.

🔗 Related Terms

📚 Learn More