# GELU and SwiGLU Activations

> How GELU and SwiGLU bend a transformer's numbers, why SwiGLU narrows its hidden layer, and what it costs, explained simply for your AI interview.

**In short:** GELU is a smooth bend: small values pass a little, and large values pass almost in full. SwiGLU is a gated version that Meta's LLaMA model uses. It needs three weight matrices, so its hidden layer is made narrower to keep the cost the same.

AI and LLM interview question Q060, Transformer architecture. Advanced, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/gelu-and-swiglu-activations

## Say it in 30 seconds

GELU and SwiGLU are the bends a transformer puts on numbers inside its feed-forward block. GELU is a smooth version of ReLU. Small negative values pass a little, instead of being cut to zero. SwiGLU splits the input into two paths, and one path gates the other. It adds a third weight matrix, so the hidden layer gets narrower to keep the cost the same.

## Say it in 2 minutes

Every transformer layer does a matrix multiply and then an activation function, which bends each number. Without the bend, stacked layers would act like one straight line, however many you add. The bend sits in the feed-forward block, which comes after attention in each layer.

GELU, from a 2016 paper by Hendrycks and Gimpel, weights each input by its value. ReLU makes a hard cut at zero, so a small negative number disappears entirely. GELU keeps a smooth curve there. BERT used GELU, following OpenAI's GPT.

Noam Shazeer's 2020 paper tests variants of the gated linear unit (GLU), which Dauphin and colleagues introduced in 2016. A GLU multiplies two projections of the input and passes one of them through a sigmoid bend first. SwiGLU replaces that sigmoid with Swish, a smooth bend. One path goes through Swish and acts as a smooth gate, and the other passes straight on. Shazeer tested versions of this in the feed-forward layer, and the paper says some of them improve on ReLU and GELU. It admits it gives no explanation for why they work.

The cost is a third weight matrix, so the hidden width shrinks to keep the total the same. In a made-up model 3,072 numbers wide, a classic layer and a SwiGLU layer both hold 75,497,472 weights. In an interview, say the paper reports quality gains for some variants in its tests, and that you would measure them on your own data.

## What are GELU and SwiGLU, in plain words?

A transformer layer does a matrix multiply, then an activation function. The activation bends each number. Without the bend, stacked layers would act like one straight line, however many you add. The bend sits in the feed-forward block, which comes after attention in each layer.

Picture a loan officer sorting applications. A hard rule passes a file only if it clears a fixed line, and rejects the rest at once. A softer officer weighs each file by how strong it is, so a borderline file still gets a fair look. GELU and SwiGLU are the softer kind. In the model, the file is a number, and the activation decides how much of it passes on. In a loan-file model, a raw score of -2.0 from one neuron comes out of GELU as -0.0455, almost zero, while ReLU would give exactly 0.

- **Activation function:** The bend applied to each number after a layer's matrix multiply.
- **Feed-forward block:** The part of each transformer layer that reworks each token's numbers, after attention.
- **Gate:** A signal that decides how much of another signal gets through: near 0 is off, near 1 is on.
- **Hidden width:** How many numbers the middle of the block holds for each token.
- **Weight matrix:** A grid of learned numbers that a layer multiplies its input by.

## How does GELU decide what to pass on?

GELU stands for Gaussian Error Linear Unit. For an input x, it multiplies x by the chance that a bell-curve (Gaussian) random number falls below x. Large positive inputs pass almost unchanged. Large negative inputs shrink to almost zero. Values near zero get a smooth share, with no sharp corner.

> "We propose the Gaussian Error Linear Unit (GELU), a high-performing neural network activation function." (Hendrycks and Gimpel, the GELU paper)
>
> "The GELU nonlinearity weights inputs by their value, rather than gates inputs by their sign as in ReLUs" (Hendrycks and Gimpel, the GELU paper)

- **ReLU: A hard cut at zero.** Any negative input becomes exactly 0. Simple and fast.
- **GELU: A smooth curve.** Small negative inputs pass a little, and the curve has no sharp corner at zero.

BERT, an early and influential language model, used GELU rather than the standard ReLU, following OpenAI's GPT.

## What is SwiGLU, and why do some models use it?

Noam Shazeer's 2020 paper tests variants of the gated linear unit (GLU). Dauphin and colleagues introduced GLU in 2016. A GLU multiplies two linear projections of the input, each one a matrix multiply, and passes one of them through a sigmoid first. A sigmoid is an S-shaped curve that squeezes any number between 0 and 1. SwiGLU swaps that sigmoid for Swish, a smooth bend that PyTorch also calls SiLU.

Shazeer tried many versions in the feed-forward layer of the Transformer. He reports that some of them improve on ReLU and GELU, and that the GEGLU and SwiGLU versions gave the best scores in his pre-training tests. Perplexity measures how surprised a model is by real text, so lower is better.

*Diagram, How a SwiGLU layer runs: One token's vector enters two paths. The gate path and the value path meet in a multiply, then a second matrix sends the result back to full width. There are three weight matrices in all.*
1. One copy of the vector feeds the gate path.
2. A second copy feeds the value path.
3. The gate path, after its smooth bend, reaches the multiply.
4. The value path reaches the multiply with no bend.
5. The product goes through a second weight matrix.
6. The result is back at full width, ready for the next layer.

Meta's LLaMA model is one example of a model built with SwiGLU. Its paper says so directly:

> "We replace the ReLU non-linearity by the SwiGLU activation function, introduced by Shazeer (2020) to improve the performance." (Meta AI, the LLaMA paper)
>
> "We offer no explanation as to why these architectures seem to work" (Shazeer, the SwiGLU paper)

> **Tip:** In an interview, describe SwiGLU as a gated layer with a third matrix, which is a bigger change than a new curve. Say the paper reports quality gains in its tests, and that the paper itself gives no explanation for why it works.

## What does the switch cost in weights?

SwiGLU adds a third matrix. If the hidden width stayed at 4 times the model width, the layer would grow by half. Shazeer keeps the weight count and the arithmetic per token the same by shrinking the hidden width.

Here is a worked example with made-up numbers. A bank's team is training a small model to read loan files, and its width is 3,072 numbers. A classic layer with a hidden width of 4 times 3,072, which is 12,288, holds two matrices and 75,497,472 weights. A SwiGLU layer with a hidden width of 8,192 holds three matrices and the same 75,497,472 weights. Biases are left out.

Here is the same arithmetic in plain Python. The first part compares three bends: ReLU, GELU and SiLU. The second part counts the weights.

```python
import math

def relu(x):
    return max(0.0, x)

def gelu(x):
    # Exact GELU: x times the chance that a Gaussian number is below x
    return x * 0.5 * (1 + math.erf(x / math.sqrt(2)))

def silu(x):
    # SiLU (Swish with beta 1): x times a sigmoid gate between 0 and 1
    return x / (1 + math.exp(-x))

print("   x     ReLU     GELU     SiLU")
for x in [-2.0, -0.5, 0.0, 0.5, 2.0]:  # raw scores from one neuron in a loan-file model
    print(f"{x:5.1f} {relu(x):8.4f} {gelu(x):8.4f} {silu(x):8.4f}")

d = 3072                      # made-up model width
classic = 2 * d * (4 * d)     # two matrices, hidden width 4d
hidden = 8 * d // 3           # SwiGLU hidden width
swiglu = 3 * d * hidden       # three matrices, same total
print(f"classic FFN weights: {classic:,}")
print(f"SwiGLU hidden width: {hidden:,}")
print(f"SwiGLU FFN weights:  {swiglu:,}")
```

Output:

```text
   x     ReLU     GELU     SiLU
 -2.0   0.0000  -0.0455  -0.2384
 -0.5   0.0000  -0.1543  -0.1888
  0.0   0.0000   0.0000   0.0000
  0.5   0.5000   0.3457   0.3112
  2.0   2.0000   1.9545   1.7616
classic FFN weights: 75,497,472
SwiGLU hidden width: 8,192
SwiGLU FFN weights:  75,497,472
```

> **Tip:** Changing the activation of a trained model breaks the weights it learned, so keep the one it was trained with.

### How would you choose an activation for a new in-house model?

First, check what the base model uses. Hugging Face models name the activation in their config file, under hidden_act. BERT's docs say hidden_act defaults to gelu. Match it, because a changed activation breaks the weights the model learned.

1. **Check the base model's config:** Look for hidden_act and match the name the checkpoint was trained with.
2. **Training from scratch? Match the budget:** Keep the weight count the same, and narrow the SwiGLU hidden width to do it.
3. **Test on your own data:** Compare error on a set of loan files the model never trained on. The paper's tests may not match your data, so measure yours.

The trade-off here is simpler GELU against gated SwiGLU, which costs a third matrix and reports quality gains in its tests.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] An activation bends each number, or stacked layers are one straight line.
- [ ] GELU is smooth and weights each input by its value.
- [ ] SwiGLU is gated: two paths, one gating the other, three matrices.
- [ ] The hidden width shrinks so the cost stays the same.
- [ ] A trained model's activation can't be swapped without breaking it.
- [ ] The paper reports gains in its tests, so test on your own data.

**Common traps**

- Trap: "GELU and ReLU are the same idea." Better: Both pass large positive values. GELU is smooth near zero, while ReLU has a hard corner there.
- Trap: "SwiGLU is a better curve, so swap it in." Better: It adds a gate and a third matrix. Swapping it changes the layer's shape, so the width has to change too.
- Trap: "The gain is big, so always use it." Better: The paper reports gains in its own tests. Test on your own data before you commit to the cost.

## Can you spot the problem?

**Spot the problem:** A bank's team loads a saved copy of a model trained with GELU (a checkpoint), but their code sets the activation to SiLU. What goes wrong?

A. The model runs out of memory, because SiLU stores every weight twice.
B. Each layer computes a different function than it learned, so the answers get worse.
C. The tokenizer splits the loan text in a different way.
D. The learning rate is applied twice during each step.

**Answer:** B. The weights were tuned for GELU. Swapping the bend changes what every layer computes. The code still runs without errors, which is why this failure is so easy to miss.

**Quick check:** A team keeps a feed-forward layer at 4 times the model width, then swaps in SwiGLU with three matrices and no narrowing. What changes?

A. Nothing, the weight count stays the same
B. Its feed-forward weights grow by about half
C. It loses its gate, so it gets fewer weights
D. Only the training speed changes

**Answer:** B. Three matrices where there were two is half again as many weights at the same width. That is why the hidden layer is narrowed.

## Can you answer these from memory?

**Flash cards**

- **What does an activation do?** It bends each number, so stacked layers can model curves.
- **GELU in one line?** A smooth bend that weights each input by its value, with no hard cut at zero.
- **SwiGLU in one line?** A gated layer: one path gates the other, using three weight matrices.
- **Why narrow SwiGLU's hidden layer?** To keep the weight count and compute about the same as the classic layer.
- **Can you swap a trained model's activation?** No. Its weights were learned with one activation, so swapping breaks them.
- **Does SwiGLU always win?** No. The paper reports gains in its tests. Measure on your own data.

## Likely follow-up questions

- Q064 Roughly how many parameters are in one transformer layer? https://designervenkat.online/interview/ai/parameters-in-one-transformer-layer
- Q058 Multi-query vs grouped-query attention? https://designervenkat.online/interview/ai/multi-query-vs-grouped-query-attention
- Q061 Dropout in transformers? https://designervenkat.online/interview/ai/dropout-in-transformers
- Q062 How does BERT differ from GPT? https://designervenkat.online/interview/ai/how-does-bert-differ-from-gpt
- Q067 What is weight tying? https://designervenkat.online/interview/ai/what-is-weight-tying
- Q054 What does the feed-forward block do? https://designervenkat.online/interview/ai/what-does-the-feed-forward-block-do

## Learn it in depth

- [Activation functions: the bends](https://designervenkat.online/learn/machine-learning/activation-functions)
