Learn
Architecture

What is SwiGLU in neural networks?

The short answer

SwiGLU is a gated feed-forward layer: one linear projection is passed through a SiLU activation, multiplied elementwise by a second projection, then projected back down. The gate lets the network scale features conditionally instead of applying a fixed nonlinearity. It costs three weight matrices instead of two and is used in Llama, Mistral, PaLM and most current open models.

On this page

The gating idea

A standard feed-forward layer computes activation(xW1)W2. Every feature passes through the same fixed nonlinearity, and the only way the network can suppress a feature is to push its pre-activation very negative. A gated linear unit adds a second path that acts as a valve: GLU(x) = (xW + b) * sigma(xV + c), where * is elementwise multiplication and sigma is a sigmoid.

The valve is the interesting part. The sigmoid branch outputs values between zero and one, so it decides how much of each feature in the first branch survives. That is conditional computation at the level of individual features and individual tokens: the same weights behave differently depending on the input, without any branching in the code.

Gated linear units were introduced for language modelling by Dauphin et al. in 2017, largely as a way to make convolutional sequence models easier to optimise. The observation that stuck was that the gate, not the convolution, was doing much of the work - which is why the idea migrated into transformers once people started replacing the plain feed-forward block.

What SwiGLU specifically does

SwiGLU, from Noam Shazeer's 2020 note "GLU Variants Improve Transformer", keeps the gate and swaps the sigmoid for SiLU, also called swish: SiLU(x) = x * sigma(x). The layer becomes FFN(x) = (SiLU(x * W_gate) * (x * W_up)) * W_down, with three weight matrices and no biases in modern implementations.

SiLU is smooth and non-monotonic: it dips slightly negative around x ~ -1.3 before approaching zero, and it is unbounded above. Unlike ReLU it has no dead zone where gradients are exactly zero, and unlike sigmoid it does not saturate for large positive inputs. That combination gives a gate that can be fully closed, partially open, or amplifying, with gradients flowing in all three regimes.

The naming is mechanical: SwiGLU = swish-gated linear unit. GeGLU is the same structure with GELU in place of SiLU, ReGLU with ReLU, and SeGLU with SELU. Shazeer's note compared several of these and found the gated variants consistently better than the plain ReLU or GELU feed-forward at matched parameter count, with SwiGLU and GeGLU usually at the top and hard to separate.

Why a gate helps

A multiplicative interaction is strictly more expressive than an additive one at the same width. The product of two linear functions of the input contains pairwise terms that a single nonlinearity applied to a linear function cannot represent. That is why gating shows up everywhere in modern architectures - in LSTMs, in attention, and in the feed-forward blocks of nearly every current language model.

The second effect is optimisation. The gate provides a shortcut path for gradients and lets the network turn features off without pushing weights to extremes. In practice this shows up as smoother loss curves and slightly better final loss for the same compute, which is exactly the kind of unglamorous improvement that gets adopted everywhere once it is measured.

There is a caveat that is often missed. Part of the reported gain comes from the extra parameters: three matrices instead of two is 50% more weights if you hold the hidden width fixed. Fair comparisons shrink the hidden width so parameter counts match, and the advantage largely survives that correction - but not entirely, and not always by much. If you read a benchmark claiming a large win, check whether the baseline had the same parameter count.

The 8/3 rule and why it exists

A classic feed-forward with expansion factor four has 2 * d * 4d = 8d^2 parameters. A SwiGLU layer with hidden width h has 3 * d * h parameters. Setting them equal gives h = 8d/3, which is where the familiar ratio comes from. In practice the width is rounded up to a multiple of 128 or 256 so tensor-core kernels stay efficient.

Llama's numbers show the rule in action: d_model 4,096 gives 8/3 x 4,096 = 10,922, rounded to 11,008. Per layer that is 3 x 4,096 x 11,008 ~ 135M parameters, against 2 x 4,096 x 16,384 ~ 134M for a four-times ReLU layer. Essentially identical capacity, different shape.

Across a 32-layer model the feed-forward accounts for about 4.3B of a 6.7B parameter budget - roughly 64%. That is why changes to the feed-forward block move total parameter count so much, and why mixture-of-experts, which multiplies experts inside exactly this block, can inflate a model from 7B to 47B without changing anything else.

Cost at training and inference

At matched parameters SwiGLU is compute-neutral: 3 * d * (8/3)d = 8d^2 multiply-adds, identical to 2 * d * 4d. What changes is the shape of the matrices and how well they map onto hardware. Three matrices of width 11,008 are slightly less convenient than two of width 16,384, which is why implementations concatenate the gate and up projections into a single matrix of 22,016 rows and do one matmul instead of two.

Memory is also matched at equal parameters, but the activation footprint differs. Both branches of the gate must be held in memory for the backward pass, and the elementwise product adds a temporary buffer. At long sequence lengths this is a real cost - activation memory scales with tokens x hidden width - and it is one reason training frameworks fuse the gate, activation and multiply into a single kernel.

At inference the difference is negligible. The layer is still two matmuls in sequence with an elementwise multiply between them, and decode is bandwidth-bound on weight reads rather than arithmetic. A SwiGLU model does not generate tokens more slowly than a ReLU model of the same size.

Where it sits in the block

The feed-forward block in a modern LLM is: normalise, project up to the gated hidden width, apply SiLU to the gate branch, multiply, project down, add to the residual stream. No bias terms, no dropout in most current models, and no activation on the output projection. The pattern is boringly consistent across Llama, Mistral, Qwen, DeepSeek and Gemma-family models.

The absence of biases is a deliberate simplification. Bias terms add parameters and a small amount of numerical surface for very little measured benefit in large models, and removing them makes the kernels simpler and the tensor-parallel split cleaner. Older architectures such as GPT-2 kept them; the trend since 2022 has been to drop them everywhere.

Width padding matters more than it should. A hidden width that is not a multiple of the tensor-core tile size leaves the last tile partially used, and at 135M parameters per layer that waste compounds. Padding to 256 or 1,024 is standard, which is why published widths look arbitrary: 11,008 = 43 x 256, and 14,336 = 56 x 256.

Tensor parallelism and the three matrices

Splitting a SwiGLU layer across GPUs is straightforward if you respect the dependency. The gate and up projections are column-parallel: each device computes a slice of the hidden dimension, applies SiLU and the multiply to its own slice, and then the down projection is row-parallel, summing partial results across devices with an all-reduce.

Getting this wrong is a classic bug. If the gate and up projections are sharded differently - one column-parallel and one row-parallel - the elementwise multiply pairs features that do not correspond, and the model produces fluent nonsense. The failure is quiet, which is what makes it dangerous: loss looks plausible, samples look like text, evaluations are just slightly bad.

Checkpoint conversion has the same hazard. Weight names differ across frameworks - gate_proj, up_proj, down_proj in Hugging Face, fused w1/w3 and w2 in some kernels - and the gate and up matrices are sometimes stored concatenated. Converting a checkpoint without checking which is which yields the same silent degradation.

The variants you will meet

  • GeGLU: GELU gate instead of SiLU; used by Gemma and several research models, roughly equivalent in quality.
  • ReGLU: ReLU gate; cheaper and historically common, slightly worse in most comparisons.
  • Bilinear GLU: no activation on the gate branch at all, which makes the layer a pure product of two linear maps.
  • Gated MLPs in state-space models: Mamba and its successors use a SwiGLU-like gate inside the block, borrowed directly from this lineage.
  • Mixture-of-experts: each expert is a SwiGLU feed-forward, so the same layer is replicated many times with a router in front.
  • Sparse or low-rank variants: factorising one of the three matrices to cut parameters, usually at some quality cost.

Precision and numerical behaviour

SiLU needs an exponential, and exponentials are where low-precision arithmetic gets uncomfortable. In bf16, x * sigma(x) is accurate for the range of pre-activations a trained model actually produces, typically within +/-20, but early in training or after a bad batch the gate branch can see much larger values. Good kernels compute the sigmoid in fp32 and cast back, which costs almost nothing because the operation is memory-bound anyway.

Quantisation is gentler than it looks. The gate branch is multiplied by a value between roughly -0.28 and unbounded above, so the product's dynamic range is dominated by the up branch. That means int8 weight quantisation of the three matrices behaves much like quantising any other linear layer, and the elementwise multiply itself is usually kept in higher precision.

One practical detail: the negative lobe of SiLU means a fully closed gate is never exactly zero. Values around -0.28 leak a small negative contribution even when the gate is saturated. This is harmless mathematically - the down projection learns to use it - but it confuses people who expect gating to produce exact sparsity. If you need true sparsity for a mixture-of-experts router, apply a threshold explicitly rather than relying on the activation.

Doing the arithmetic for your own model

Feed-forward parameters per layer = 3 * d_model * d_ff (plus 2 * d_ff for biases, if you keep them, which you should not). Total for the model = layers x that, plus attention and embeddings. To hit a target parameter budget, solve for d_ff and then round to the nearest multiple of 256.

Worked example: target 1B parameters, 24 layers, d_model 2,048, vocabulary 32,000, tied embeddings. Embeddings cost 65.5M. Attention with 16 heads, 4 key-value heads and head_dim 128 costs about 10.5M per layer, or 252M across 24 layers. That leaves about 683M for the feed-forward, or 28M per layer. Solving 3 * 2,048 * d_ff = 28M gives d_ff ~ 4,630, which rounds to 4,608.

Sanity-check the result against a known model. Llama-2-7B: 32 layers, d_model 4,096, d_ff 11,008, 32 query heads, 32 key-value heads, 32,000 vocabulary. Feed-forward 4.33B, attention 2.15B, embeddings 0.13B - 6.6B plus norms, against a published 6.74B. If your arithmetic lands within a few percent, you understand the architecture.

Common mistakes

The most common error is porting a configuration without the 2/3 adjustment. Take a model designed with d_ff = 4*d_model and swap in a SwiGLU layer at that same width and you have added 50% more parameters - the model still trains, which is why the mistake survives review, but the comparison against the baseline is meaningless and the memory budget is wrong.

The second is leaving biases in. A checkpoint with bias vectors will not load into a bias-free implementation without warnings, and naive conversion silently drops them, shifting every pre-activation by a constant. The third is applying the activation to both branches. Only the gate branch gets SiLU; the up branch stays linear, and applying SiLU twice changes the function being computed.

Finally, do not evaluate a SwiGLU change on loss alone. The gate changes the model's inductive bias, and small perplexity improvements do not always translate to better instruction following or reasoning. Run the downstream evaluation you actually care about before declaring victory.

Why it stuck

SwiGLU is a small, cheap, reliable improvement that costs nothing at inference and composes with everything else. It does not change the shape of the transformer, does not complicate serving and does not require new kernels once the fused version exists. That combination - free quality, no operational tax - is rare enough that an architecture idea spreads quickly when it has it.

It is also a good example of how modern LLM design actually works. The dramatic headlines are about attention and scale; the measured gains often come from unglamorous choices in the feed-forward block, the normalisation scheme and the data mixture. When you read a model card, the activation function is a useful signal: if it says SwiGLU and RMSNorm with pre-norm, the model is built from the current consensus stack, and the interesting differences are elsewhere.

Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.