@Zen_with_AI: Outstanding Resource: A From-Scratch Tutorial on RoPE (Rotary Position Embeddings) — Transformers are inherently unaware of word order; positional encodings are the compass we install. Raschka just released a from-scratch RoPE tutorial: starting from GPT-2's absolute position vectors, to how RoPE rotates relative positions into…

X AI KOLs Timeline News

Summary

Recommendation for Sebastian Raschka's new from-scratch tutorial on RoPE (Rotary Position Embeddings), covering everything from GPT-2's absolute positional encodings to RoPE, NoPE, partial RoPE, and other modern architecture approaches — including a panoramic view of positional encoding choices across open-source models in 2026 and PyTorch code implementations.

Outstanding Resource: A From-Scratch Tutorial on RoPE (Rotary Position Embeddings) Transformers are inherently unaware of word order; positional encodings are the compass we install. Raschka just published a from-scratch RoPE tutorial: starting with GPT-2's absolute position vectors, then explaining how RoPE rotates relative positions into attention, and covering modern approaches like NoPE, partial RoPE, and hybrid architectures — all accompanied by visualizations and short snippets of PyTorch code. The article also includes a panoramic view of positional encoding choices across open-source models in 2026, comparing GPT-2 and MiniMax-M3 side by side. If you want to truly understand positional encodings in modern LLMs, this is a must-save resource. https://magazine.sebastianraschka.com/p/understanding-positional-embeddings…
Original Article
View Cached Full Text

Cached at: 11/16/26, 02:25 PM

God-Tier Resource: A From-Scratch Tutorial on RoPE (Rotary Positional Embeddings)

Transformers have no built-in notion of word order — positional encoding is the compass you give them.

Sebastian Raschka just published a from-scratch RoPE tutorial: starting from GPT-2’s absolute position vectors, moving on to how RoPE rotates relative positions into the attention mechanism, and covering newer architectural approaches like NoPE, partial RoPE, and hybrids — complete with visualizations and short PyTorch snippets.

The article also includes a panorama of positional encoding choices across 2026 open-weight models, with GPT-2 and MiniMax-M3 compared side by side. If you really want to understand positional encodings in modern LLMs, this one is worth bookmarking.

https://magazine.sebastianraschka.com/p/understanding-positional-embeddings…


Understanding Positional Embeddings in Modern LLMs

Source: https://magazine.sebastianraschka.com/p/understanding-positional-embeddings This article explains how LLMs encode and process token position information by covering classic and contemporary methods like RoPE. It’s essentially a comprehensive journey where we will work through the mechanisms with visual examples, a little math, and a small PyTorch implementation. And, of course, we will then also look at how modern architectures adapt or omit explicit positional encodings.

Below, you can find a preview of which positional embedding choices are used in 2026 open-weight models. We will discuss these choices later after covering the underlying mechanisms.

Figure 1 — gallery 2026 collage (https://substackcdn.com/image/fetch/$s_!8RKL!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb461a2cb-11ab-474a-affe-0ee99e5a8782_2850x2777.png)Figure 1: A preview of the gallery’s 2026 architectures, grouped by positional encoding. Architecture figures taken from myLLM gallery (https://sebastianraschka.com/llm-architecture-gallery/). But why spending so much time writing/reading about this rather minor building block? LLMs keep evolving, and as I was preparing a new article on the latest LLM architecture trends this year, I realized that I never covered the positional information methods used in LLMs in any article yet. So, instead of letting the other article get out of hand, I thought it might make sense to publish this as a standalone building block for the upcoming LLM architecture and trends analysis.

Also, over the years, many readers have asked me for a tutorial on relative positional embeddings (aka RoPE) to follow up on the learned absolute embeddings used in GPT. It’s been on my TODO list for a long time, so I finally revisited my old draft and put this walkthrough together, which will cover

  • different positional methods in LLMs;
  • (finally) how RoPE works;
  • what methods are used by recent open LLMs.

Note that this article assumes some familiarity with basic LLM architectures and works well as a follow-up to Build a Large Language Model (From Scratch) (https://sebastianraschka.com/books/#build-a-large-language-model-from-scratch). If the concepts and computation of the attention internals, particularly query, key, and value vectors, are a little fuzzy, I recommend checking my self-attention walkthrough (https://magazine.sebastianraschka.com/p/understanding-and-coding-self-attention) as a refresher:

Understanding and Coding Self-Attention, Multi-Head Attention, Causal-Attention, and Cross-Attention in LLMs (https://magazine.sebastianraschka.com/p/understanding-and-coding-self-attention) The article is also very technical and likely too detailed for some. However, I really wanted to have this foundation out there for future articles to reference. And no worries, the next one will return to a more comfortable style.

PS: I started experimenting with Substack’s new “perks” system. As a thank-you to supporters, I’ve added image exports and metadata (https://magazine.sebastianraschka.com/perks) from the architecture gallery for you to use in your own analyses.

PPS: If you are already familiar with how position embeddings work, feel free to fast-forward to Section 6, Positional choices in modern architectures.

Note that this article may be best read in a web browser than an email client. I recommend checking out the web view here (https://magazine.sebastianraschka.com/p/understanding-positional-embeddings), which also has a navigation bar on the left side.

Let’s start with the overall architecture. A tokenizer encodes the input text into token IDs. Next, the input token embedding layer of an LLM maps each of these IDs to a vector of numbers. We usually refer to these entries in that vector as “features” (similar to classic ML). The transformer blocks inside the LLM then modify these vectors using attention and feedforward layers. Lastly, the model’s output layer produces logit scores (converted into probabilities) for the next token.

The following shows this path in GPT-2 (a relatively classic LLM) and MiniMax-M3 (a more recent LLM released this year; a placeholder for most other recent LLMs). As we can see, the architectures are not too different from each other, but before we get to the positional information parts, let’s focus on the orange blocks for now (the token embedding layers) and the transformer blocks above them; the other architecture differences aren’t needed for this explanation.

Figure 2 — token embedding architectures (https://substackcdn.com/image/fetch/$s_!3vjo!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F4ab287c2-c3ba-46db-9ed0-1e6eacf78f43_2592x2521.png)Figure 2: Token embedding layers in GPT-2 and MiniMax-M3, highlighted in orange. (Side note: M3’s first three out of 60 feedforward layers are dense, not MoEs.) A token embedding layer, shown in the figure above, maps each token ID to a vector. Position information is then added afterward. Concretely, and as we will discuss in more detail later, GPT-2 adds a position vector to each token embedding before the modified embedding enters the first transformer block. On the other hand, MiniMax-M3 adds the positional information in each transformer block using a method called RoPE inside attention.

We will talk about these methods in more detail later, but first, let’s start with the big picture information explaining why explicit positional information is added or needed.

Consider the following two input sentences as a simple example:

  1. “The red fox jumps over the gray fox.”
  2. “The gray fox jumps over the red fox.”

Changing the word order changes which fox does the jumping, as illustrated in the following figure.

Figure 3 — word order (https://substackcdn.com/image/fetch/$s_!KoQ2!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb8ff5039-8ec8-447c-a444-0345619c8b7b_1846x1304.png)Figure 3: Changing the word order changes which fox jumps. For the examples in this article, we will treat each word as one token for simplicity. (As you know, real tokenizers can split words into smaller subword tokens.) The first sentence then has eight token positions, from 0 through 7.

Figure 4 — token ids and positions Figure 4: Token IDs and positions in the toy sentence. (If you are interested in how vocabularies are built, check out my tokenizer materials on GitHub (https://github.com/rasbt/LLMs-from-scratch/tree/main/ch02/05_bpe-from-scratch).)

Note that “fox”, which appears twice in the input sentence, gets the same token ID 2 in both cases. And since they both have the same token ID, irrespective of the position in the input sentence, they would get the same embedding vector from the embedding layer.

Now, let’s consider a regular self-attention mechanism with no positional encoding (and no causal mask), where every input token can attend to every other token in the input. In this scenario, swapping any two words, like “red” and “gray”, would still result in the same embeddings and attention scores between each token pair.

GPT-style models do use a causal (autoregressive) mask, which restricts each token to itself and earlier tokens. Interestingly, this causal mask gives the computation some implicit order information. In our example, “jumps” can attend to “red” in the first sentence and “gray” in the second. So, a causal LLM can theoretically already distinguish these sentences even without explicit positional embeddings. (We will return to this idea later when discussing the “NoPE” concept.)

Nonetheless, GPT-2 and most newer LLMs include explicit positional information because it gives attention a direct signal about positions. That’s because even though the causal mask determines which tokens are accessible and provides implicit order information, it doesn’t distinguish a separation of one position from a separation of ten, for example. So, explicit positional methods are still useful (or even essential), since they supply that information.

If this all sounded confusing, don’t worry, it was more meant as an overview, and we will step through these concepts a bit more slowly in the remaining article.

We briefly talked about implicit positional information through causal attention masks (and we will revisit this again in more detail later). However, we now switch gears and talk about the explicit ways to add positional information.

The perhaps simplest and most direct (but not “cheapest”) approach is to give each sequence position its own vector. We add that vector to the token embedding, so the resulting, modified embedding vector is then passed to the first transformer block. This exact procedure is discussed in the following subsections.

To illustrate the use of an explicit, learned positional vector added to the input embeddings, let’s consider GPT-2 as a concrete example. GPT-2 learns a table of position vectors during training. The following figure illustrates where these vectors are used in the architecture, that is, immediately after the token embedding lookup and before the first transformer block.

Figure 5 — gpt2 architecture (https://substackcdn.com/image/fetch/$s_!GDv8!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fda2b0f15-7f45-4aa4-8f1b-a0777a0da4fc_1710x2197.png)Figure 5: GPT-2 adds absolute position information before the transformer blocks, as highlighted in purple. The dimensions shown are for GPT-2 XL (https://huggingface.co/openai-community/gpt2-xl/blob/main/config.json). The positional embedding layer depicted in the figure above follows the same implementation as the token embedding layer, i.e., they have exactly the same output dimensions so that the resulting input vectors can be added to each other. The code below shows that with an excerpt of a GPT-2 code implementation:

And in mathematical terms, we can write it as follows. Let m be a position index and x_m the token ID at that position. The input to the first block is

Equation 1: h_m = E_{\text{token}}(x_m) + P_m.

Here,

  • Etoken is the embedding layer,
  • P_m is the position info vector selected by m,
  • and h_m is the resulting summed embedding and position vector.

The two vectors have the same width, so we add their entries element-wise. Figure 6 below shows this visually with a small numerical example.

Figure 6 — absolute embeddings (https://substackcdn.com/image/fetch/$s_!yuT0!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F546edc50-7b1a-40ba-a125-da3fbdaade26_2586x964.png)Figure 6: Token and position embeddings are added element-wise. (I am following the convention here that neural network diagrams are usually read from bottom to top.) In the figure above, at position 0, adding the token embedding [1, 1, 1] to the position embedding [1.1, 1.2, 1.3] gives [2.1, 2.2, 2.3]. By the way, the values in the figure are chosen to keep the illustration simple; in a real example, both embedding layers (tables) are initialized with small random values and learned during training.

So, what we covered in this section is a so-called absolute positional method because the positional embedding P_m depends on the token’s own position m. In the previous example sentence, the two “fox” tokens have initially the same token embeddings, but because we are adding different positional vectors P_2 and P_7, they have different values before they enter the first transformer block. And consequently, the query, key, and value vectors inside the attention mechanisms then also receive representations that already include position information.

Note that the original GPT-2 implementation (https://github.com/openai/gpt-2/blob/master/src/model.py) has 1,024 learned position vectors. This means it only works with inputs with 1024 or fewer tokens. If we want to extend the context window, we would have to extend this embedding table. And since the embedding table (layer) is updated like any other layer during training, the context length would have to be decided before the training starts.

Extending the context would be very expensive since the table can become very large. For example, in the case of GPT-2 Medium, the positional embedding layer weights only make up 0.30% of the total weights at 1,024 positions. However, if we increased the context length to a nowadays common 100k range, they would make up >22% of the total model weights, which would be very uneconomical.

The original “Attention Is All You Need” (https://arxiv.org/abs/1706.03762) transformer from 2017, which predates GPT, uses the same addition mechanism, but computes its position vectors with fixed sine and cosine functions. Figure 7 below shows this addition before both the encoder and decoder stacks. The encoder processes the input sequence, and the decoder generates the output sequence. (The reason why it’s introduced here is that the sine and cosine functions will become relevant again later when discussing RoPE.)

Figure 7 — original transformer architecture (https://substackcdn.com/image/fetch/$s_!dHH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5958afa7-673d-44df-a1af-112044196dde_2620x2800.png)Figure 7: Sinusoidal position encodings added to the token embeddings as highlighted in purple. The original transformer also scales its token embeddings by √(dmodel) before adding the position vectors, where dmodel is the embedding width.

So, while GPT-2 in the previous section had the formula

Equation 2: h_m = E_{\text{token}}(x_m) + P_m.

the formula used in the original transformer (depicted in Figure 7) is:

Equation 3: h_m = \sqrt{d_{\text{model}}} E_{\text{token}}(x_m) + P_m.

This scaling by √(dmodel) is a minor technical detail, but for those who are curious, the motivation behind this scaling factor is not explained in the transformer paper, but as I discussed with colleagues on a Twitter thread many years ago, it’s likely to put the token embeddings and sinusoidal positional encodings on comparable numerical magnitudes at initialization, so the position vectors don’t dominate the sum when we add them.

In the GPT-2 case, this scaling wasn’t necessary because the original GPT-2 code initialized the token embeddings to have an initial standard deviation of 0.02 and the position embeddings to have an initial standard deviation of 0.01 so that they were already roughly on the same scale.

Now, the more interesting point is how the position embeddings P_m are computed.

Concretely, each position vector has the following entries:

Equation 4: \begin{aligned} P_{m,2i} &= \sin\left(\frac{m}{10000^{2i/d_{\text{model}}}}\right), \ P_{m,2i+1} &= \cos\left(\frac{m}{10000^{2i/d_{\text{model}}}}\right). \end{aligned}

As before, m denotes the position. The index i indexes a pair of features within the vector.

Here, a feature is one number in the position vector. For example, let’s assume we have a small vector with 8 values (dmodel = 8) that has entries numbered 0 through 7. (In the original paper this was 512 for the small model and 1024 for the bigger model, instead of 8, but that would be hard to visualize.) We group these into four pairs s

Similar Articles

@NFTCPS: You keep talking about AI, but can't even explain what a Transformer is? There's a repo that goes all out — builds a GPT from scratch without using any high-level libraries. It lays out exactly how Attention, Multi-Head, Feed-Forward, Embedding, Residual connections, and Layer Norm are pieced together. And it's not just the model; the entire pipeline is covered…

X AI KOLs Timeline

A GitHub open-source project that implements the complete GPT training pipeline from scratch, including data preprocessing, pretraining, SFT, and RLHF post-training, all based on native PyTorch. Ideal for developers who want to deeply understand the Transformer architecture.

LayerRoPE: Dynamic Depth-wise Magnitude & Angular Superposition

arXiv cs.LG

提出 LayerRoPE,将 Transformer 中隐式的深度位置编码显式化:用单一共享 γ 向量与深度条件标量替代逐层 γ,在参数减少、FLOPs 几乎不变的情况下,在最高 512 层的深度上实现更稳定的训练与显著更高的计算效率(达到 Pre-Norm 1.3B 损失所需算力减少 3.4 倍)。

RoPE Distinguishes Neither Positions Nor Tokens in Long Contexts, Provably

arXiv cs.CL

This paper provides a theoretical proof that Rotary Positional Embeddings (RoPE) in Transformer-based language models lose their locality bias and ability to distinguish token order in long contexts, with attention scores becoming no better than random. The authors show that increasing the RoPE base trades off position vs. token distinction and that multi-head, multi-layer architectures cannot compensate for this fundamental limitation.

RoVE: Rotary Value Embeddings Attention for Relative Position-dependent Value Pathways

arXiv cs.LG

This paper proposes RoVE, a parameter-free modification to Rotary Position Embeddings that makes value pathways position-sensitive by rotating values simultaneously with keys, transforming RoPE attention into attentive convolution. Experiments on GPT-2 models show consistent gains in few-shot in-context learning, out-of-distribution perplexity, and long-context retrieval.