By Sagi Shaier · 12 November 2026 · 6 min read
What changed in transformers since the original: modern variants
What RoPE, relative positions, RMSNorm and SwiGLU each replace in a transformer block, with a worked example of each and short PyTorch code you can run.
Modern transformer variants are newer versions of the transformer block that keep the same parts as the original but compute some of those parts differently. Many large language models built today still have attention and a feed-forward network in each block. They also keep residual connections, normalization and position information. What often differs from the first transformer is how positions are encoded, which normalization formula is used and which activation the feed-forward network uses. The changes aim at more stable training, faster runs and lower memory use, which become important once models get large.
The parts that stay the same
A transformer layer, also called a block, updates a list of token vectors with two sublayers. Attention lets each token mix in information from other tokens, and the feed-forward network (FFN) is a small two-layer network applied to each token on its own. Each sublayer reads a normalized copy of its input and adds its output back onto the input. That add-back path is the residual connection, and it lets each sublayer make a small update instead of rewriting the vector.

The cache in the list is the KV cache, which stores past keys and values during text generation. It has its own post. The rest of this post covers three common swaps: the position method, the normalization and the FFN activation.
Absolute vs relative positions
Attention by itself does not know the order of the tokens. The original transformer fixed this with absolute positions. Each position $t$ gets a vector $p_t$, and that vector is added to the token's embedding $e_{token}$ once, before the first layer:
$$x_t = e_{token} + p_t$$
Relative position methods work differently. They change the attention scores inside each layer so that a score depends on how far apart the two tokens are. An attention score $s_{ij}$ compares a query vector $q_i$ from position $i$ with a key vector $k_j$ from position $j$:
$$s_{ij} = q_i \cdot k_j$$
A relative method makes $s_{ij}$ depend on the distance $i - j$. Because this happens inside every layer, the position information is refreshed at every layer instead of being added only once at the input.

RoPE: rotating queries and keys
Rotary position embedding (RoPE) is one way to get a relative-position effect. Instead of adding a position vector to the input, it rotates the query and key vectors inside attention by an angle that grows with position, right before their dot product.
A two-number example shows why this gives relative positions. Take a query $q = [1, 2]$ and a key $k = [3, -1]$. Rotate the query by $i \cdot 0.5$ radians when it sits at position $i$, rotate the key by $j \cdot 0.5$ radians when it sits at position $j$, then take the dot product:
1import math
2import torch
3
4def rotate(v, position, theta=0.5):
5 angle = position * theta
6 c, s = math.cos(angle), math.sin(angle)
7 return torch.tensor([c * v[0] - s * v[1], s * v[0] + c * v[1]])
8
9q = torch.tensor([1.0, 2.0])
10k = torch.tensor([3.0, -1.0])
11
12for i, j in [(3, 1), (7, 5), (7, 1)]:
13 score = rotate(q, i) @ rotate(k, j)
14 print(i, j, round(score.item(), 4))
15# 3 1 -5.35
16# 7 5 -5.35
17# 7 1 -1.9778Positions 3 and 1 give the same score as positions 7 and 5, because both pairs are 2 apart. Rotating both vectors by the same extra amount leaves the angle between them unchanged, and the dot product depends only on that angle and the vector lengths. Positions 7 and 1 are 6 apart, so the score is different.
A real head has more than two numbers per vector. RoPE splits each query and key into pairs of neighboring features, $(q_{2i}, q_{2i+1})$, and rotates each pair with a 2 by 2 rotation matrix. The angle for pair $i$ at position $p$ is
$$\theta_{i,p} = p \cdot \omega_i$$
where $\omega_i$ is a fixed speed for that pair. With $d_{head}$ features per head,
$$\omega_i = 10000^{-2i/d_{head}}$$
so the first pair rotates fastest and later pairs rotate more slowly. The same rotation is applied to $Q$ and $K$, and the values $V$ are not rotated.

The part to remember is where RoPE lives: inside the attention computation, applied to $Q$ and $K$ before the scores are computed.
RMSNorm
Normalization keeps the size of each token vector under control before a sublayer reads it. LayerNorm was the original choice. It does two things to a token vector: it subtracts the vector's mean and then divides by its standard deviation. RMSNorm (root mean square normalization) skips the mean subtraction and only divides by the root mean square of the entries.
For a token vector $x$ with $d$ entries:
$$\operatorname{RMS}(x)=\sqrt{\frac{1}{d}\sum_j x_j^2+\epsilon}$$
$$\operatorname{RMSNorm}(x)=\gamma\odot\frac{x}{\operatorname{RMS}(x)}$$
Here $\epsilon$ is a tiny constant that avoids division by zero, $\gamma$ is a learned scale with one entry per feature, and $\odot$ means entry-by-entry multiplication.
Here is RMSNorm by hand for $x = [1, 2, 3, 6]$ with $\gamma$ all ones. The squares are 1, 4, 9 and 36. Their mean is 12.5 and the RMS is $\sqrt{12.5} \approx 3.536$. Dividing each entry by 3.536 gives about $[0.283, 0.566, 0.849, 1.697]$. In code:
1import torch
2
3def rms_norm(x, gamma, eps=1e-6):
4 ms = x.pow(2).mean(-1, keepdim=True)
5 return x * torch.rsqrt(ms + eps) * gamma
6
7x = torch.tensor([1.0, 2.0, 3.0, 6.0])
8gamma = torch.ones(4)
9print(rms_norm(x, gamma))
10# tensor([0.2828, 0.5657, 0.8485, 1.6971])
11print(torch.nn.functional.layer_norm(x, (4,)))
12# tensor([-1.0690, -0.5345, 0.0000, 1.6036])torch.rsqrt computes one over the square root, so multiplying by it divides by the RMS. RMSNorm keeps every entry's sign and only rescales the vector, while LayerNorm first moves the mean to zero, which is why its output holds negative numbers and a zero.

SwiGLU
The original FFN is two linear layers with an activation function between them. SwiGLU replaces that with a gated version. One linear layer produces candidate features, a second linear layer produces a gate, and the two are multiplied entry by entry before the output layer:
$$\operatorname{SwiGLU}(x)=\left(xW_1\odot \operatorname{swish}(xW_{gate})\right)W_2$$
The gate goes through the swish function, which multiplies its input by the sigmoid of that input:
$$\operatorname{swish}(z)=z\cdot\sigma(z)$$
For example, $\sigma(2) \approx 0.881$, so $\operatorname{swish}(2) \approx 1.762$, and $\operatorname{swish}(-2) \approx -0.238$. A large positive gate lets a feature through nearly unchanged, and a gate near zero or below shuts it down. In PyTorch swish is called F.silu.

As a module:
1import torch
2import torch.nn.functional as F
3
4print(F.silu(torch.tensor([2.0, 0.0, -2.0])))
5# tensor([ 1.7616, 0.0000, -0.2384])
6
7class SwiGLU(torch.nn.Module):
8 def __init__(self, d_model, d_ff):
9 super().__init__()
10 self.w1 = torch.nn.Linear(d_model, d_ff, bias=False) # feature branch
11 self.w_gate = torch.nn.Linear(d_model, d_ff, bias=False) # gate branch
12 self.w2 = torch.nn.Linear(d_ff, d_model, bias=False) # back to d_model
13
14 def forward(self, x):
15 return self.w2(self.w1(x) * F.silu(self.w_gate(x)))
16
17ffn = SwiGLU(d_model=8, d_ff=16)
18x = torch.randn(2, 5, 8) # (B, T, d_model)
19print(ffn(x).shape) # torch.Size([2, 5, 8])The output has the same shape as the input, $(B, T, d_{model})$, so SwiGLU drops into the block wherever the old FFN sat. If the shapes do not match, check that w2 maps from d_ff back to d_model.
With both swaps in place, the block keeps its layout. Each sublayer still reads a normalized input and adds an update back onto the residual path.

Common mistakes
- Rotating the values with RoPE. RoPE rotates $Q$ and $K$ only, because the rotation is meant to change the scores. $V$ passes through unrotated.
- Adding RoPE at the input like a position embedding. RoPE is applied inside attention in every layer, after the $Q$ and $K$ projections.
- Normalizing over the wrong axis. RMSNorm averages over the feature axis of each token, which is
dim=-1for a tensor of shape $(B, T, d_{model})$, not over the batch or the tokens. - Swapping the two SwiGLU branches. The swish goes on the gate branch, and the other branch stays linear. Applying swish to both branches gives a different function.
- Mixing up which norm subtracts the mean. LayerNorm subtracts it and RMSNorm does not, so for $x = [1, 2, 3, 6]$ the two give $[-1.069, -0.535, 0, 1.604]$ and $[0.283, 0.566, 0.849, 1.697]$.
Related concepts
Positional encoding explained covers the sine and cosine position vectors, which use the same base of 10000 as RoPE's angle formula. How transformers work builds the original block with LayerNorm and a plain FFN, and build a small GPT from scratch puts that block into a working model. KV cache and grouped-query attention covers the generation-time cache from the list at the top.
QuiddityML teaches these swaps as the Modern Variants concept in the Intro to NLP track. The exercises include picking the line of code that computes RMSNorm from its equation, matching a SwiGLU line of code to its formula and filling in an RMSNorm forward pass.