QuiddityML

By · 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.

A modern decoder block: block input, then tap 1 into Norm and Self-attention, added back at plus 1, then tap 2 into Norm and FFN, added back at plus 2, then block output. A modern decoder block usually keeps attention for token mixing, an FFN for per-token computation, residual paths, normalization, position information and a generation-time cache.

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.

Absolute positions: e_token + p_t = x_t feeds layer 1, and the position signal is added once, at the input. Relative positions: layers 1, 2 and 3 each feed a layer that computes s_ij = q_i · k_j using the distance i - j, and RoPE rotates q_i and k_j before the dot product. Position information can be refreshed at every layer.

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.9778

Positions 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.

Transformer block with RoPE: input hidden states go through linear projections to Q, K and V. RoPE is applied to Q and K to give Q_rot and K_rot, which feed scaled dot-product attention with V, then the output projection. Panels show RoPE applied per position to Q of shape B x T x d_head, an even-odd feature pair (q_2i, q_2i+1) rotated by a position-dependent angle theta_i,p, and the 2D rotation matrix with theta_i,p = p · omega_i and omega_i = 10000^(-2i/d_head).

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.

RMSNorm equation: for a token vector x in R^d, RMS(x) is the square root of the mean of x_j squared plus epsilon, and RMSNorm(x) = gamma ⊙ x / RMS(x). Table: LayerNorm subtracts the mean, RMSNorm does not. Both divide by a scale and both have a learned gain gamma.

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.

SwiGLU equation: SwiGLU(x) = (x W_1 ⊙ swish(x W_gate)) W_2 and swish(z) = z · sigma(z). Diagram: x splits into a feature branch x W_1 and a gate branch swish(x W_gate), their elementwise product goes through W_2 to give SwiGLU(x). The gate branch controls which feature-branch values pass through.

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.

RMSNorm and SwiGLU in a decoder block: block input, tap 1 into RMSNorm and Masked Multi-Head Attention, added back at plus 1 along the residual path, then tap 2 into RMSNorm and SwiGLU, added back at plus 2, then block output. RMSNorm scales a token vector by its root mean square with no mean subtraction. SwiGLU has one branch that computes candidate features and another that gates how much passes.

Common mistakes

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.