How does SwiGLU work?

Authors
How does SwiGLU work?

SwiGLU is a small building block inside modern LLMs that decides how much of each piece of information should pass through. It makes two copies of the input, turns one copy into a smooth "gate" using the Swish function, and multiplies it with the other copy, so the model can let some information through and hold some back.

In this blog, we will learn about how SwiGLU works. We will also see where it sits inside a Transformer, what an activation function is, how ReLU, Sigmoid, and Swish work, what a gate and a Gated Linear Unit are, how they join together to make SwiGLU, and why models like LLaMA use it.

We will cover the following:

  • Where does SwiGLU live inside an LLM?
  • What is a feed-forward network?
  • What is an activation function?
  • What is ReLU?
  • What is Sigmoid?
  • What is Swish?
  • What is a gate?
  • What is a Gated Linear Unit (GLU)?
  • Putting it together: SwiGLU = Swish + GLU
  • A step-by-step example with numbers
  • SwiGLU in code
  • Why does SwiGLU work better?
  • ReLU vs GELU vs SwiGLU

I am Amit Shekhar, Founder @ Outcome School, I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

I teach AI and Machine Learning at Outcome School.

Let's get started.

Where does SwiGLU live inside an LLM?

Before jumping into SwiGLU, we must know where it sits.

Most LLMs (Large Language Models) are built using an architecture called the Transformer.

A Transformer is made of many blocks stacked on top of each other. Every block has two main parts:

  • Attention: This part lets each word look at the other words and collect useful information from them.
  • Feed-forward network: This part takes what each word has collected and processes it further on its own.

Let's visualize one block as below:

   Input words (as numbers)
                   ↓
   +-------------------------------+
   |           Attention           |
   |  (words talk to each other)   |
   +-------------------------------+
                   ↓
   +-------------------------------+
   |     Feed-forward network      |
   | (each word thinks on its own) |
   |         (SwiGLU here)         |
   +-------------------------------+
                   ↓
   Output to the next block

Here, we can see that SwiGLU lives inside the feed-forward network part. So, to understand SwiGLU, we must first understand the feed-forward network.

What is a feed-forward network?

Inside the LLM, every word is stored as a list of numbers. This list is called a vector. For example, a word can be a list of 4096 numbers.

A feed-forward network is a small part of the model that takes this vector, makes it bigger, transforms it, and then makes it small again.

It works in three steps:

  • Step 1: We expand the vector. We multiply it with a table of learned numbers to make it bigger, for example from 4096 numbers to around 11,000 numbers. This table of learned numbers is called a weight matrix.
  • Step 2: We activate the numbers. We pass every number through a small function called an activation function. We will learn about this next.
  • Step 3: We shrink the vector. We multiply it with another weight matrix to bring it back to the original size.

Suppose we have a short note. First, we spread it out on a big table so we can see every detail. Then, we highlight the important parts and cross out the useless parts. Finally, we write a clean, short summary again. These are the expand, activate, and shrink steps.

SwiGLU changes the middle step, which is the "highlight and cross out" step.

What is an activation function?

An activation function is a simple rule that takes one number and gives back another number. It decides how much of a signal should pass through.

Why do we need it? Multiplying by weight matrices is a straight-line operation. If we only stack straight-line operations, the whole thing is still a straight line, no matter how many layers we use. A straight line cannot learn complex patterns like language.

The activation function adds a bend. With bends, the model can learn curves and complex patterns.

Now, let's see the three activation functions that lead us to SwiGLU.

What is ReLU?

ReLU (Rectified Linear Unit) is the simplest and most famous activation function. Its rule is:

  • If the number is positive, keep it as it is.
  • If the number is negative, make it 0.
   ReLU(x) = x   if x > 0
           = 0   if x <= 0

   ReLU(3)  = 3
   ReLU(-2) = 0

Here, we can see that ReLU works like an on-off switch. Positive numbers pass. Negative numbers get blocked fully.

The original Transformer used ReLU in its feed-forward network.

Problem: A value of -0.01 and a value of -100 both become exactly 0. All the information in the negative side is thrown away. Also, the sharp corner at 0 makes learning a bit rough.

What is Sigmoid?

Sigmoid is another activation function. It squeezes any number into a value between 0 and 1.

   Sigmoid(-5) = 0.007   (almost 0)
   Sigmoid(0)  = 0.5     (half)
   Sigmoid(5)  = 0.993   (almost 1)

Here, we can see that a very negative number becomes almost 0, a very positive number becomes almost 1, and the numbers in between become something in between.

Sigmoid works like a volume dial. 0 means fully off, 1 means fully on, and anything in between means partly on.

We will need this dial idea for gates.

Planning your move into AI?

No matter which tech domain you work in today, with your effort, you can transition to these roles:

  • AI Engineer
  • Forward Deployed Engineer
  • AI Agent Engineer
  • Harness Engineer
  • Voice AI Engineer
  • AI Architect
  • LLM Engineer
  • LLM Inference Engineer
  • Gen AI Engineer
  • MLOps Engineer
  • ML Engineer
  • Deep Learning Engineer

Our AI and Machine Learning Program at Outcome School takes you there.

What is Swish?

Now, here comes Swish into the picture.

Swish multiplies a number with its own sigmoid.

Swish(x) = x * Sigmoid(x)

Here, the number decides its own volume. A big positive number gets a dial close to 1, so it passes almost fully. A big negative number gets a dial close to 0, so it is mostly blocked. Numbers near 0 get partly through.

Let's see some values and compare them with ReLU:

xSigmoid(x)Swish(x) = x * Sigmoid(x)ReLU(x)
-50.007-0.0330
-20.119-0.2380
-10.269-0.2690
00.500
10.7310.7311
20.8811.7622
50.9934.9675

Here, we can notice two things:

  • For large positive numbers, Swish behaves almost like ReLU.
  • For negative numbers, Swish does not cut everything to 0. It lets a small negative value through, and it changes smoothly without any sharp corner.

Let's visualize the shapes as below:

   ReLU                           Swish

                  /                              /
                 /                              /
                /                              /
   ____________/                 _____       _/
                                      \_____/
               0                          0

   (sharp corner at 0)            (smooth, small dip below 0)

Here, we can see that Swish is a smooth version of ReLU with a small dip below zero.

Note: Swish with this exact form is also called SiLU (Sigmoid Linear Unit). In PyTorch, it is available as F.silu. The general Swish has an extra number beta inside, as x * Sigmoid(beta * x), and in SwiGLU, beta is usually just 1.

To learn Activation Functions, Feed Forward Neural Networks (FFNNs), and the rest of Deep Learning in depth, check out our AI and Machine Learning Program at Outcome School.

What is a gate?

Now, let's understand the second half of SwiGLU, which is the gate.

A gate is a set of numbers that decides how much of another set of numbers should pass through.

Think of a water tank with many taps. The water is the information. Each tap can be fully open, half open, or closed. The taps do not create water. They only control how much water flows out.

In a neural network, we have:

  • Information numbers: what we want to pass.
  • Gate numbers: how open each tap is.

We multiply them, one by one, position by position:

   Information:  [ 8,    5,    6  ]
   Gate:         [ 1.0,  0.0,  0.5 ]
   Multiply:     [ 8,    0,    3  ]

Here, we can see that the first value passed fully, the second was blocked, and the third passed half.

This position-by-position multiplication is called element-wise multiplication. Every gate works this way.

What is a Gated Linear Unit (GLU)?

A Gated Linear Unit (GLU) is a layer that makes two different versions of the same input. One version is the information, and the other version becomes the gate that controls it.

It was introduced in 2016 for language modeling. The steps are as below:

  • Step 1: Multiply the input with weight matrix W to make the information part.
  • Step 2: Multiply the same input with a different weight matrix V to make the gate part.
  • Step 3: Pass the gate part through Sigmoid, so every gate number is between 0 and 1.
  • Step 4: Multiply the information part and the gate part, element by element.

GLU(x) = (x W) * Sigmoid(x V)

Here, x W is the information part, and Sigmoid(x V) is the gate.

The best part is that the gate is learned and it depends on the input. For one word, the gate opens some taps. For another word, it opens different taps. So, the model learns to decide, for every input, which information is useful and which is not.

Compare this with ReLU. ReLU uses a fixed rule: "block anything negative". A GLU learns its own rule: "block what is not useful for this input".

A quick note for you

No matter which tech domain you work in, get familiar with these topics:

  • LLM
  • RAG
  • MCP
  • Agent
  • Fine-tuning
  • Quantization

We put it all together in one video:

AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, and Quantization

No need to stop reading - bookmark it and watch later when you get time. Future you will thank you.

Now, let's get back to the topic.

Putting it together: SwiGLU = Swish + GLU

Now, we have every piece. It's time to put them together.

SwiGLU = Swish + GLU.

SwiGLU is a GLU where the gate uses the Swish function instead of the Sigmoid function.

SwiGLU(x) = Swish(x W) * (x V)

Here, we have:

  • x W, which is passed through Swish to become the gate.
  • x V, which is the information part.
  • *, which is the element-wise multiplication.

Then, as in every feed-forward network, a third weight matrix shrinks the result back to the original size. So, the full feed-forward network with SwiGLU looks like below:

FFN(x) = (Swish(x W) * (x V)) W2

Let's visualize the full flow as below:

               Input vector x
                     ↓
           +---------+---------+
           ↓                   ↓
    x W (gate path)     x V (info path)
           ↓                   ↓
         Swish                 ↓
           ↓                   ↓
           +-------> * <-------+
                     ↓
          (element-wise multiply)
                     ↓
            x W2 (shrink back)
                     ↓
                  Output

Here, we can see that there are two paths from the same input. One path becomes the gate. The other path carries the information. They meet in the middle and are multiplied.

This was introduced by Noam Shazeer in 2020 in the paper "GLU Variants Improve Transformer". He tried many gate functions, and the ones using smooth functions like Swish and GELU did the best.

Note: In the LLaMA code, these three matrices are often named w1 (gate), w3 (up, which means the info path), and w2 (down, which means shrink back).

A step-by-step example with numbers

The best way to learn this is by taking an example.

For the sake of understanding, let's say that after the two multiplications, we have only three numbers in each path.

Step 1: We compute the two paths.

   Gate path  (x W):  [ 2,    -1,    0.5 ]
   Info path  (x V):  [ 3,     4,   -2   ]

Step 2: We apply Swish to the gate path. We use the values from our table.

   Swish(2)   = 2   * 0.881 =  1.762
   Swish(-1)  = -1  * 0.269 = -0.269
   Swish(0.5) = 0.5 * 0.622 =  0.311

   Gate after Swish: [ 1.762, -0.269, 0.311 ]

Step 3: We multiply the two paths element by element.

   1.762 *  3  =  5.286
  -0.269 *  4  = -1.076
   0.311 * -2  = -0.622

   Result: [ 5.286, -1.076, -0.622 ]

Step 4: We multiply this result with W2 to shrink it back to the original size.

Here, we can notice how the gate controlled the flow:

  • The first position had a strongly positive gate, so its information passed through strongly and became 5.286.
  • The second position had a negative gate value, so its information was mostly held back and even flipped to a small negative value.
  • The third position had a small gate, so only a small part of its information passed.

This is how SwiGLU decides, for every position, how much information should flow.

Stay updated: Subscribe to our newsletter to get our latest AI and Machine Learning blogs straight to your inbox.

SwiGLU in code

Now, let's see the code for a SwiGLU feed-forward network in PyTorch. We can write the code as below:

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

class SwiGLUFeedForward(nn.Module):
    def __init__(self, dim, hidden_dim):
        super().__init__()
        self.w1 = nn.Linear(dim, hidden_dim, bias=False)  # gate path
        self.w3 = nn.Linear(dim, hidden_dim, bias=False)  # info path
        self.w2 = nn.Linear(hidden_dim, dim, bias=False)  # shrink back

    def forward(self, x):
        gate = F.silu(self.w1(x))     # Swish on the gate path
        info = self.w3(x)             # info path
        return self.w2(gate * info)   # multiply, then shrink back

Here, we have:

  • self.w1, which makes the gate path.
  • self.w3, which makes the info path.
  • F.silu, which is the Swish function with beta equal to 1.
  • gate * info, which is the element-wise multiplication.
  • self.w2, which shrinks the result back to the original size dim.

This is the same structure used in LLaMA.

Note: A normal feed-forward network has two weight matrices. SwiGLU has three. To keep the total number of learned numbers about the same, the hidden size is made smaller, about two-thirds of the usual size. For example, a normal feed-forward network uses 4 x dim as the hidden size. With SwiGLU, people use about 2/3 x 4 x dim. In LLaMA 7B, dim is 4096 and hidden_dim is 11008.

Why does SwiGLU work better?

Now, the question is: why do so many modern LLMs like LLaMA, PaLM, and Mistral use SwiGLU?

Reason 1: Better results. In Shazeer's experiments, SwiGLU and other GLU variants gave better quality than ReLU at the same size and same compute. This is the main reason.

Reason 2: Input-based filtering. The gate learns which information to pass for each input. ReLU only uses a fixed rule.

Reason 3: Smooth learning. Swish has no sharp corner and does not fully kill negative values. So, even negative values still send a small learning signal back during training, and the model keeps learning from them.

Reason 4: Multiplication adds power. Multiplying two learned paths lets the model build richer combinations of features than a single path can.

The full reason is not completely understood. Shazeer himself wrote in the paper:

We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence.

It works very well in practice, and that is why many modern LLMs use it.

If we want to go deep into Transformer Architecture and LLM Internals, and build a Large Language Model (LLM) from scratch, we have a complete program - check out our AI and Machine Learning Program at Outcome School.

ReLU vs GELU vs SwiGLU

GELU (Gaussian Error Linear Unit) is another smooth activation, similar in shape to Swish. It was used in models like BERT and GPT-2.

Let me tabulate the differences between ReLU, GELU, and SwiGLU for your better understanding.

PointReLUGELUSwiGLU
ShapeSharp corner at 0SmoothSmooth gate times info
Negative valuesAll become 0Small values passControlled by a learned gate
Weight matrices in FFN223
GateNoNoYes, learned and input-based
Compute costLowestLowSlightly higher, balanced by a smaller hidden size
Used inOriginal TransformerBERT, GPT-2LLaMA, PaLM, Mistral, and many modern LLMs

Here, we can see that SwiGLU is the only one with a learned gate.

We have a detailed blog on the Evolution of LLM Architecture that covers how we got from the original Transformer to these modern LLMs end to end.

Now, we must have understood how SwiGLU works.

Frequently Asked Questions

Is SwiGLU the same as SiLU?

No. SiLU is another name for the Swish function, which multiplies a number with its own sigmoid, as x * Sigmoid(x). SwiGLU is a full Gated Linear Unit that uses Swish on its gate path and multiplies the result with a separate information path. In PyTorch, Swish is available as F.silu, and SwiGLU is built on top of it.

Does SwiGLU add more parameters to the model?

Not overall. SwiGLU uses three weight matrices instead of the usual two, so the hidden size is made smaller, about two-thirds of the usual size, to keep the total number of learned numbers about the same. For example, LLaMA 7B uses a dim of 4096 and a hidden_dim of 11008.

Who introduced SwiGLU?

SwiGLU was introduced by Noam Shazeer in 2020 in the paper "GLU Variants Improve Transformer". He tried many gate functions, and the ones using smooth functions like Swish and GELU did the best. The Gated Linear Unit it builds on was introduced earlier, in 2016, for language modeling.

What do w1, w2, and w3 mean in the LLaMA feed-forward code?

They are the three weight matrices of the SwiGLU feed-forward network. w1 makes the gate path, which goes through Swish. w3 is the up projection, which makes the information path. w2 is the down projection, which shrinks the multiplied result back to the original size.

That's it for now.

Thanks

Amit Shekhar
Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.