Sign in

SwiGLU

Swish-Gated Linear Unit

A gated feed-forward block: one linear branch passes through SiLU and multiplies a second linear branch, then a third map projects back.

Overview

A classic feed-forward block widens the input, applies an activation, and narrows it again. A gated block widens the input twice, with two separate weight matrices. One copy, the gate branch, goes through SiLU. The other copy, the value branch, stays linear. The two are multiplied element by element, so each hidden unit's value is scaled by a factor the input itself chose. That product lets the block compute terms that depend on pairs of input features, which a single activation cannot do in one step.

A short history

Noam Shazeer introduced SwiGLU in the 2020 note 'GLU Variants Improve Transformer', which tested gated feed-forward layers with different activations on the gate. The variant gated by Swish was among the best at equal parameter count. Google's PaLM adopted it in 2022 and Meta's LLaMA in 2023, and it has since become the usual feed-forward block in large language models.

How it works

  1. Take an input xx of width dd (the config's dim).
  2. Compute the gate pre-activation g=xWgg = x W_g and the value v=xWvv = x W_v, each of width hh (hidden_dim). Biases are added when bias is on.
  3. Apply SiLU to the gate branch only.
  4. Multiply element by element: m=SiLU⁡(g)⊙vm = \operatorname{SiLU}(g) \odot v.
  5. Project back to width dd: y=m Woy = m\,W_o.
  6. In backward, send the gradient through WoW_o, split it between the two branches with the product rule, and store one gradient per parameter in grads.

Watch out for

  • The block has three weight matrices, not two. Keeping hidden_dim at 4d4d makes it 50 percent larger than the classic block, so use about 83d\tfrac{8}{3} d for a fair comparison.
  • The output is a product of two functions of xx, so it grows roughly quadratically with the input scale. Without normalisation before the block, activations can blow up.
  • The template is a small NumPy version with hand-written backpropagation and plain gradient descent in step. Real models run this block inside a framework with an adaptive optimiser.
  • backward must be given the same xx that forward saw. It recomputes both branches from it and overwrites grads on every call.

Use cases

When to use it

Transformer feed-forward layers in modern language models. LLaMA-style models use this block with no biases and a hidden width of about 83d\tfrac{8}{3} d.

In industry

Large language models
PaLM and the LLaMA family use SwiGLU as the feed-forward block in every transformer layer.
Code assistants
Open code generation models built on LLaMA style architectures inherit the SwiGLU feed-forward block.
Vision transformers
Some recent self-supervised vision transformers, such as the larger DINOv2 models, use a SwiGLU feed-forward layer in place of the plain GELU block.

Choosing it: what must hold

  • A transformer whose feed-forward block you control, typically a model trained from scratch.
  • A hidden width set to about two thirds of the usual four times expansion, to keep the parameter count equal.
  • If you load pretrained weights, a checkpoint that was trained with this block.

When to choose something else

IfUse instead
You must match a BERT, GPT-2 or ViT style checkpointGELU in a plain feed-forward block
You want the gated block with a GELU gate, as in T5 version 1.1GEGLU
The model is a small convolutional or fully connected networkReLU or SiLU

Math foundations

  1. The classic block it replaces

    y=σact(xW1) W2y = \sigma_{\text{act}}(x W_1)\, W_2

    Widen with W1W_1, apply one activation, narrow with W2W_2. Each hidden unit depends on the input through one linear map only.

  2. The gated block

    y=(SiLU⁡(xWg)⊙(xWv)) Woy = \big(\operatorname{SiLU}(x W_g) \odot (x W_v)\big)\, W_o

    Two linear maps of the same input, one activated and one not, multiplied element by element and then projected. This is what forward computes.

  3. The gate activation

    SiLU⁡(z)=z σ(z),σ(z)=11+e−z\operatorname{SiLU}(z) = z\,\sigma(z), \qquad \sigma(z) = \frac{1}{1 + e^{-z}}

    Each gate value is its input scaled by its own sigmoid. It is smooth and dips slightly below zero for negative inputs.

  4. Gradients of the two branches

    ∂L∂g=δ⊙v⊙SiLU⁡′(g),∂L∂v=δ⊙SiLU⁡(g),δ=∂L∂y Wo⊤\frac{\partial \mathcal{L}}{\partial g} = \delta \odot v \odot \operatorname{SiLU}'(g), \qquad \frac{\partial \mathcal{L}}{\partial v} = \delta \odot \operatorname{SiLU}(g), \qquad \delta = \frac{\partial \mathcal{L}}{\partial y}\, W_o^{\top}

    The product rule. Each branch receives the upstream gradient δ\delta scaled by the other branch. If one branch is near zero, the other learns slowly.

  5. Matching the parameter count

    3 d h=2⋅d⋅4d  ⟹  h=83 d3\,d\,h = 2 \cdot d \cdot 4d \;\Longrightarrow\; h = \tfrac{8}{3}\,d

    The gated block has three d×hd \times h matrices. The classic block with hidden width 4d4d has 8d28d^{2} weights. Setting them equal gives the usual hidden width.

Symbols

xx
the input row vector, width d
Wg,WvW_g, W_v
gate and value weight matrices, each d by h; w_gate and w_value in params
WoW_o
output weight matrix, h by d; w_out in params
g,vg, v
gate pre-activation and value, each of width h
⊙\odot
element by element multiplication
δ\delta
the gradient of the loss with respect to the hidden product
L\mathcal{L}
the loss being minimised
d,hd, h
input width dim and hidden width hidden_dim
σact\sigma_{\text{act}}
the activation of the classic block, for example ReLU or GELU
σ\sigma
the logistic sigmoid

Worked by hand

Take the smallest block: d=h=1d = h = 1, no bias, with Wg=1W_g = 1, Wv=2W_v = 2, Wo=0.5W_o = 0.5 and input x=1x = 1. The sigmoid gives σ(1)=0.7311\sigma(1) = 0.7311.

g=1×1=1,v=1×2=2g = 1 \times 1 = 1, \qquad v = 1 \times 2 = 2
SiLU⁡(1)=1×0.7311=0.7311\operatorname{SiLU}(1) = 1 \times 0.7311 = 0.7311
m=0.7311×2=1.4622m = 0.7311 \times 2 = 1.4622
y=1.4622×0.5=0.7311y = 1.4622 \times 0.5 = 0.7311

The output is 0.7311. Doubling xx would double both branches before the activation, so the output more than doubles: the block is not linear in its input.

Visual example

Loading the example.

Try this

  • Move across the curve and read the output and the slope together.
  • Find where the slope is close to zero: a unit there has stopped learning.

Code sample

import numpy as np
from impl import SwiGLU
from config import SwiGLUConfig

block = SwiGLU(SwiGLUConfig(dim=8, hidden_dim=16, bias=False, seed=0))
x = np.random.default_rng(0).normal(size=(2, 5, 8))   # (batch, tokens, dim)
y = block.forward(x)                                  # (2, 5, 8)
dx = block.backward(x, np.ones_like(y))               # gradient for x; block.grads holds the weight gradients
block.step(lr=0.01)
Read the implementation (104 lines)
"""SwiGLU: gated feed-forward block, y = (SiLU(x W_gate) * (x W_value)) W_out.

NumPy only, with manual backpropagation. `forward` runs the block, `backward` returns the gradient with respect to
the input and stores the gradient of every parameter, `step` applies plain gradient descent.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import SwiGLUConfig
except ImportError:  # run from the template's own folder
    from config import SwiGLUConfig

def _sigmoid(x: np.ndarray) -> np.ndarray:
    """Logistic function 1 / (1 + exp(-x)), written so that large |x| cannot overflow."""
    return np.exp(-np.logaddexp(0.0, -x))


def _silu(x: np.ndarray) -> np.ndarray:
    """SiLU / Swish: x * sigmoid(x)."""
    return x * _sigmoid(x)


def _silu_grad(x: np.ndarray) -> np.ndarray:
    """Derivative of SiLU: s + x * s * (1 - s) with s = sigmoid(x)."""
    s = _sigmoid(x)
    return s + x * s * (1.0 - s)


class SwiGLU:
    """Gated feed-forward block. Parameters live in `self.params`, their gradients in `self.grads`.

    params: "w_gate" (dim, hidden_dim), "w_value" (dim, hidden_dim), "w_out" (hidden_dim, dim), and with bias
    "b_gate" (hidden_dim,), "b_value" (hidden_dim,), "b_out" (dim,).
    """

    def __init__(self, config: SwiGLUConfig | None = None) -> None:
        self.config = config or SwiGLUConfig()
        c = self.config
        rng = np.random.default_rng(c.seed)
        lim_in, lim_hidden = 1.0 / math.sqrt(c.dim), 1.0 / math.sqrt(c.hidden_dim)
        self.params = {
            "w_gate": rng.uniform(-lim_in, lim_in, size=(c.dim, c.hidden_dim)),
            "w_value": rng.uniform(-lim_in, lim_in, size=(c.dim, c.hidden_dim)),
            "w_out": rng.uniform(-lim_hidden, lim_hidden, size=(c.hidden_dim, c.dim)),
        }
        if c.bias:
            self.params.update(b_gate=np.zeros(c.hidden_dim), b_value=np.zeros(c.hidden_dim), b_out=np.zeros(c.dim))
        self.grads = {name: np.zeros_like(value) for name, value in self.params.items()}

    def _branches(self, x: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Pre-activation of the gate branch and the value branch. x: (..., dim). Both: (..., hidden_dim)."""
        if x.shape[-1] != self.config.dim:
            raise ValueError(f"last axis must be {self.config.dim}, got input shape {x.shape}")
        gate, value = x @ self.params["w_gate"], x @ self.params["w_value"]
        if self.config.bias:
            gate, value = gate + self.params["b_gate"], value + self.params["b_value"]
        return gate, value

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: (..., dim). Returns (..., dim): (SiLU(x W_gate) * (x W_value)) W_out."""
        x = np.asarray(x, dtype=float)
        gate, value = self._branches(x)
        y = (_silu(gate) * value) @ self.params["w_out"]
        return y + self.params["b_out"] if self.config.bias else y

    def backward(self, x: np.ndarray, grad_output: np.ndarray) -> np.ndarray:
        """Backpropagate through the block.

        x: (..., dim), the input given to `forward`. grad_output: (..., dim), d loss / d output.
        Returns d loss / d x, shape (..., dim), and fills `self.grads` with d loss / d parameter for every
        entry of `self.params` (summed over all leading axes).
        """
        x = np.asarray(x, dtype=float)
        g_out = np.asarray(grad_output, dtype=float)
        gate, value = self._branches(x)
        act = _silu(gate)
        hidden = act * value
        g_hidden = g_out @ self.params["w_out"].T
        g_gate = g_hidden * value * _silu_grad(gate)
        g_value = g_hidden * act
        flat = lambda a: a.reshape(-1, a.shape[-1])  # noqa: E731  merge the leading axes into one
        self.grads["w_out"] = flat(hidden).T @ flat(g_out)
        self.grads["w_gate"] = flat(x).T @ flat(g_gate)
        self.grads["w_value"] = flat(x).T @ flat(g_value)
        if self.config.bias:
            self.grads["b_out"] = flat(g_out).sum(axis=0)
            self.grads["b_gate"] = flat(g_gate).sum(axis=0)
            self.grads["b_value"] = flat(g_value).sum(axis=0)
        return g_gate @ self.params["w_gate"].T + g_value @ self.params["w_value"].T

    def step(self, lr: float) -> None:
        """One plain gradient-descent update of every parameter with the gradients of the last `backward`."""
        for name in self.params:
            self.params[name] = self.params[name] - lr * self.grads[name]

    def num_parameters(self) -> int:
        """Total count of trainable numbers in the block."""
        return int(sum(p.size for p in self.params.values()))

    __call__ = forward
Repository
gitlab.com/designsbyduhart/solomon-templates/activation-swiglu
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Build SwiGLU(SwiGLUConfig(dim=8, hidden_dim=16)) and confirm num_parameters() returns 384 with the default bias of false. Run forward on a random batch, call backward with a gradient of ones, then check one entry of grads["w_gate"] against a finite difference. Finish with step(0.01).

Check on learning

  1. The gate branch and the value branch start as two random linear maps of the same input. What makes them take on different roles during training?
    A way to think about it

    Look at the two gradient formulas. Each branch is scaled by the other, and only one passes through a nonlinearity. Ask what each can represent that the other cannot.

  2. If you swapped a classic 4d4d block for this block with hidden_dim still at 4d4d, and quality improved, what could you conclude?
    A way to think about it

    Count parameters in both. An improvement that comes with 50 percent more weights does not show the gating helped. Design the comparison that would.

  3. Suppose every gate value is close to zero early in training. What happens to the gradient reaching WvW_v, and how does the block get out of that state?
    A way to think about it

    The value gradient is δ⊙SiLU⁡(g)\delta \odot \operatorname{SiLU}(g). Then look at the gate gradient, which depends on vv and on the activation's slope near zero.

  4. This block uses SiLU on the gate and GEGLU uses GELU. Would you expect a large difference between them? How would you test it?
    A way to think about it

    Plot both activations on the same axes. They are close everywhere. A fair test holds width, seed and optimiser fixed and compares over several seeds.