页面简介
Discover how positional embeddings allow LLMs to understand word order. We explore learned, sinusoidal, and Rotary Position Embeddings (RoPE) in detail.
正文摘录
India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder d : h : m : s Get Details Interview PrepCareerGenAIPrompt EnggChatGPTLLMLangchainRAGAI AgentsMachine LearningDeep LearningGenAI ToolsLLMOpsPythonNLPSQLAIML Projects Reading list Introduction to NLPWhat is NLP?Applications of NLP Text Pre-processingUnderstanding Text Pre-processingTokenization in NLPByte Pair EncodingTokenizer Free Language Modeling with PixelsStopword RemovalStemming vs LemmatizationText Mining NLP LibrariesSpacy TutorialsGensim Tutorials Regular ExpressionsWhat are Regular Expressions?Regular Expressions String SimilarityString Similarity Spelling CorrectionSpelling Correction Topic ModelingIntroduction to Topic ModelingLatent Dirichlet Allocation (LDA)Implement Topic Modeling Text RepresentationIntroduction to Feature Engineering for Text DataImplement Text Feature Engineering TechniquesIntroduction to One Hot EncodingImplement One Hot EncodingLimitations of One Hot EncodingCount Vectorizer and TF-IDFSolving Text classification using TF-IDF Information Retrieval SystemInformation Retrieval System Explained in Simple terms!How does Google Rank Search Results?Knowledge Graph Word VectorsUnderstanding Word2VecUnderstanding Skip Gram and Continous Bag Of WordsWord2Vec Implementation in GensimVisualizing Word2Vec Word SensesWord Senses and Word Sense Ambiguity Dependency ParsingWhy Are We Interested in Syntatic Strucure?What is a Dependency Grammar?Neural Dependency Parsing Language ModelingIntroduction to Language ModelsN-Gram Language ModelsNeural Language models Getting Started with RNNWhy Sequence models?Usecases of Sequence modelsIntroduction to RNNImplement RNN Different Variants of RNNShortcomings of RNNWhat is Long Short Term Memory (LSTM)Implementing LSTMBuild Your Own Fake News Classification ModelWhat is Gated Recurrent Unit (GRU)?Implementing GRU Machine Translation and AttentionIntroduction to Machine TranslationMultilingualism in NLPDrawbacks of Seq2Seq modelMathematical Calculation of Attention Self Attention and TransformersUnderstand Positional EncodingIntroducing Transformers ModelKey Query Value Attention in Tranformer Encoder Transfomers and PretrainingPretrained Language Models in NLPGenerative Pre-training (GPT) for Natural Language Understanding(NLU)Finetuning GPT-2Understanding BERTFinetune Masked language Modeling in BERTImplement Text Classification using BERTFinetuning BERT for NERExtensions of BERT: Roberta, Spanbert, ALBERMobileBERTGPT-3Prompt Engineering in GPT-3BigbirdT5 and large language models Question AnsweringImplement Question Answering on SQUAD Text SummarizationText Summarization Named Entity RecognitionNamed Entity Recognition (NER) in Python with Spacy Coreference ResolutionCoreference Resolution Audio DataVisualizing Sounds Using Librosa Machine Learning Library!Audio ProcessingAudio AnalysisAudio Classification using Deep Learning ASRAutomatic Speech RecognitionImplement Automatic Speech RecognitionCan Voice Conversion Improve ASR in Low-Resource Settings? Audio SeparationAudio Separation ChatbotBuilding ChatbotsBuilding Chatbots using Rasa Auto NLPAutomate NLP Tasks using EvalML Library Positional Embeddings Explained: How LLMs Understand Word Order Riya Bansal Last Updated : 22 Nov, 2026 8 min read “The dog hunted the fox.” “The fox hunted the dog.” They are the same words, but the meanings are totally different. You can note the difference at once, but a transformer can’t. This is the problem which positional embeddings solve. They inform a language model about the position of each token in the sentence. Without them, one sees a prompt merely as a collection of words. We will explore these notions starting from basic facts. First, we will find out why transformers are unable to understand word order. Then we will look through three important types of positional embeddings: learned, sinusoidal, and RoPE. Table of contentsWhy Do Transformers Need Positional Embeddings?Approach 1: Learned Absolute Positional EmbeddingsApproach 2: Sinusoidal Positional EncodingApproach 3: Rotary Position Embeddings (RoPE)Mini Project: Build RoPE and Verify It WorksWhat Are Modern LLMs Doing Now?Positional Embeddings at a Glance:Common Misconceptions About Positional EmbeddingsConclusionFrequently Asked Questions Why Do Transformers Need Positional Embeddings? The central concept of a transformer is attention. Every token looks at all other tokens to figure out what is relevant. However, the way attention operates is through the dot product of the vectors. Since the dot product doesn’t depend on the origin of the vectors, it loses track of which vectors were processed first. For instance, think of a group chat without timestamps. You can see all the messages sent, but you have no idea about the order of sending. That is how attention works without a position. Let’s demonstrate this with some code. We will take two sentences and swap some words in them to perform self-attention. import numpy as np np.random.seed(0) emb = {w: np.random.randn(4) for w in ["the", "fox", "chased", "dog"]} def attention(x): scores = x @ x.T / np.sqrt(x.shape[1]) weights = np.exp(scores) / np.exp(scores).sum(axis=1, keepdims=True) return weights @ x s1 = np.stack([emb[w] for w in ["fox", "chased", "dog"]]) s2 = np.stack([emb[w] for w in ["dog", "chased", "fox"]]) out1, out2 = attention(s1), attention(s2) print(np.allclose(out1[0], out2[2])) # True The result is True. Fox shows the same representation in both sentences. The model does not know whether the fox is chasing or being chased. When positional embeddings are absent, the fox shows the same output. But doesn’t the causal mask help? Somewhat, yes. The GPT-style model employs a causal mask. Each token can see the preceding tokens only. This creates some order information. However, its signal is not clear. It cannot differentiate between a single-token gap and a ten-token gap. Therefore, many models add explicitly coded position data on top of that. Approach 1: Learned Absolute Positional Embeddings The simplest solution would be to use the idea from GPT-2, where every position is assigned a unique vector. These vectors would be learned during the training phase, not dissimilar to how the word embeddings are learned. Then the position vector gets added to the token vector. For example, “fox” at position 3: embedding("fox") + position_vector[3] Yet at position 7: embedding("fox") + position_vector[7] In this way both “fox”s token will look different for the attention. The analogy here would be the theater seats and their numbers. Unfortunately, there are only 1,024 position vectors learned in GPT-2. Thus position number 1,025 simply does not exist. Hence, you would have to select the context length before the very beginning of the training. The cost also grows very fast. The numbers observed for GPT-2 Medium: Context lengthPosition weights as a share of the model1,024 tokensAbout 0.3%Roughly 100,000 tokensMore than 22% That’s a lot of parameters to count and even remember. Approach 2: Sinusoidal Positional Encoding The initial paper on Transformers from 2017 embraced a unique approach. Rather than acquiring positional vectors, it created them through the combination of sine and cosine waves. There aren’t any learning parameters to be taken into consideration. Various pairs of characteristics oscillate with different speed, where some oscillate rapidly while others do not oscillate a lot. As an analogy, we can take that of a watch that has three hands. The hand that marks seconds oscillates quickly. Hand that marks minutes oscillates more slowly than the second hand. The hand that marks hours barely oscillate. Thus, when we read three hands, we know what time is. import numpy as np def sinusoidal_encoding(num_positions, d_model): pos = np.arange(num_positions)[:, None] i = np.arange(0, d_model, 2)[None, :] # even feature indices freqs = 1 / (10000 ** (i / d_model)) # fast to slow "clock hands" pe = np.zeros((num_positions, d_model)) pe[:, 0::2] = np.sin(pos * freqs) pe[:, 1::2] = np.cos(pos * freqs) return pe pe = sinusoidal_encoding(num_positions=50, d_model=8) print(np.round(pe[:3], 3)) Consider the output rows. In the first column, the value seems to randomly bounce from one position to another; however, the other columns remain almost unchanged. This combination of speed makes every position uniquely identifiable. The sinusoidal positional encoding can be represented using fast, moderate, and slow waves and a heatmap of values for 64 positions. The upper chart presents three properties consisting of waves. The lower heatmap makes a composite chart consisting of all 64 properties. In any column, you can read the individual fingerprint of a certain position from the top to the bottom. Two favorable effects can be observed: It is possible to compute positional vectors for any position (even in instances which are more extensive than one used for training); An invariable displacement related to different positions is transformed into a simple linear transformation. That position was intended to assist the models in understanding the relative distances; in point of fact, it was partially effective. Approach 3: Rotary Position Embeddings (RoPE) The RoPE (Rotary Position Embeddings) emerged in 2021 with the work on RoFormer and has since become the mainstream technique in modern LLMs. The concept itself is very simple. RoPE doesn’t introduce anything new to the token embeddings but instead simply rotates the query and key vectors in the attention mechanism according to the position of the token. This is where RoPE distinguishes itself from the previous methods. Earlier techniques introduced position once during the embedding of the tokens; RoPE is different in that it applies this technique every time there is an attention layer. Let’s illustrate this using an image. Consider each pair of dimensional features as arrows in a 2-dimensional space. The token at position 1 rotates