LeetLLM
My PlanLearnGlossaryTracksPracticeBlog
LeetLLM

Your go-to resource for mastering AI & LLM systems.

Product

  • Learn
  • Glossary
  • Tracks
  • Practice
  • Blog
  • RSS

Legal

  • Terms of Service
  • Privacy Policy

© 2026 LeetLLM. All rights reserved.

All Topics
Your Progress
0%

0 of 196 articles completed

🛠️Computing Foundations0/9
Git, Shell, Linux for AIDocker for Reproducible AIPython for AI EngineeringNumPy and Tensor ShapesCUDA for ML TrainingMPS & Metal for ML on MacData Structures for AISQL and Data ModelingAlgorithms for ML Engineers
📊Math & Statistics0/9
Gradients and BackpropVectors, Matrices & TensorsLinear Algebra for MLAdam, Momentum, SchedulersProbability for Machine LearningBayesian Inference from EvidenceStatistics and UncertaintyDistributions and SamplingHypothesis Tests, Intervals, and pass@k
📚Preparation & Prerequisites0/13
Neural Networks from ScratchCNNs from ScratchTraining & BackpropagationSoftmax, Cross-Entropy & OptimizationRNNs, LSTMs, GRUs, and Sequence ModelingAutoencoders and VAEsThe Transformer Architecture End-to-EndLanguage Modeling & Next TokensFrom GPT to Modern LLMsPrompt Engineering FundamentalsCalling LLM APIs in ProductionFirst AI App End-to-EndThe LLM Lifecycle
🧮ML Algorithms & Evaluation0/15
Linear Regression from ScratchLogistic Regression and MetricsDecision Trees, Forests, and BoostingReinforcement Learning BasicsValidation and LeakageStatistical Learning and GeneralizationConformal Prediction and UncertaintyClustering and PCAProbabilistic Generative ModelsCore Retrieval AlgorithmsDecoding AlgorithmsExperiment Design and A/B TestingCausal Inference and CounterfactualsPyTorch Training LoopsDataset Pipelines and Data Quality
📦Production ML Systems0/6
Feature Engineering for Production MLBatch and Streaming Feature PipelinesGradient Boosted Trees in ProductionRanking and Recommendation SystemsForecasting and Anomaly DetectionMonitoring Predictive Models
🧪Core LLM Foundations0/8
The Bitter Lesson & ComputeBPE, WordPiece, and SentencePieceStatic to Contextual EmbeddingsPerplexity & Model EvaluationFile Ingestion for AIChunking StrategiesLLM Benchmarks & LimitationsInstruction Tuning & Chat Templates
🧰Applied LLM Engineering0/25
Dimensionality Reduction for EmbeddingsCoT, ToT & Self-Consistency PromptingFunction Calling & Tool UseMCP & Tool Protocol StandardsContext EngineeringPrompt Injection DefenseResponsible AI GovernancePrivacy-Preserving Machine LearningData Labeling and Human FeedbackEvaluating AI AgentsProduction RAG PipelinesHybrid Search: Dense + SparseReranking and Cross-Encoders for RAGRAG Evaluation for Reliable AnswersLLM-as-a-Judge EvaluationBias & Fairness in LLMsHallucination Detection & MitigationLLM Observability & MonitoringExperiment Tracking with MLflow and W&BPrompt Optimization with DSPyModel Versioning & DeploymentSemantic Caching & Cost OptimizationLLM Cost Engineering & Token EconomicsModel Gateways, Routing, and FallbacksDesign an Automated Support Agent
🎓Portfolio Capstones0/9
Capstone: Delivery ETA PredictionCapstone: Product RankingCapstone: Demand ForecastingCapstone: Image Damage ClassifierCapstone: Production ML PipelineCapstone: Document QACapstone: Eval DashboardCapstone: Fine-Tuned ClassifierCapstone: Reproducible ML Study
🧠Transformer Deep Dives0/8
Sentence Embeddings & Contrastive LossEmbedding Similarity & QuantizationScaled Dot-Product AttentionVision Transformers and Image EncodersPositional Encoding: RoPE & ALiBiLayer Normalization: Pre-LN vs Post-LNMechanistic InterpretabilityDecoding Strategies: Greedy to Nucleus
🧬Advanced Training & Adaptation0/17
Scaling Laws & Compute-Optimal TrainingPre-training Data at ScaleBuild GPT from Scratch LabJAX for PyTorch ResearchersContinued Pretraining for Domain ShiftSynthetic Data PipelinesSupervised Fine-Tuning PipelineMixed Precision TrainingDistributed Training: FSDP & ZeROLoRA & Parameter-Efficient TuningTraining Run OperationsReward Modeling from Preference DataRLHF & DPO AlignmentConstitutional AI & Red TeamingRLVR & Verifiable RewardsKnowledge Distillation for LLMsModel Merging and Weight Interpolation
🤖Advanced Agents & Retrieval0/16
Vector DB Internals: HNSW & IVFAdvanced RAG: HyDE & Self-RAGGraphRAG & Knowledge GraphsRAG Security & Access ControlStructured Output GenerationReAct & Plan-and-ExecuteGuardrails & Safety FiltersCode Generation & SandboxingComputer-Use / GUI / Browser AgentsHuman-in-the-Loop Agent ArchitectureAI Coding Workflow with AgentsAgent Memory & PersistenceAgent Failure & RecoveryRecursive Language Models (RLM)Multi-Agent OrchestrationCapstone: Production Agent
⚡Inference & Production Scale0/31
Inference: TTFT, TPS & KV CacheMulti-Query & Grouped-Query AttentionKV Cache & PagedAttentionPrefix Caching and Prompt CachingFlashAttention & Memory EfficiencyContinuous Batching & SchedulingScaling LLM InferenceModel Parallelism for LLM InferenceAccelerator Architecture Field GuideCorrect GPU Profiling and BenchmarkingGPU Kernel Performance Engineering LabGPU Parallel Primitives LabGPU Compilers and Kernel LanguagesGEMM From Naive CUDA to Tensor CoresLow-Precision GPU ProgrammingGPU Runtime Execution LabAI-Generated Kernel EngineeringModel Quantization: GPTQ, AWQ & GGUFLocal LLM DeploymentSLM Specialization & Edge DeploymentSpeculative DecodingLong Context Window ManagementMixture of Experts ArchitectureMamba & State Space ModelsReasoning & Test-Time ComputeAdvanced MLOps & DevOps for AIGPU Serving & AutoscalingGPU Failure OperationsDistributed Inference Data PlaneServing Benchmark EngineeringA/B Testing for LLMs
🏗️System Design Capstones0/9
Content Moderation SystemCode Completion SystemMulti-Tenant LLM PlatformLLM-Powered Search EngineVision-Language Models & CLIPMultimodal LLM ArchitectureDiffusion Models: Images & TextReal-Time Voice AI AgentReasoning Agent System Design
🎤AI Lab Interviewing0/4
AI Lab Coding Interview: Python SystemsAI Lab System Design InterviewAI Lab Behavioral InterviewAI Lab Technical Presentation
🔬Project Deep Dives0/17
Deep Dive - vLLMDeep Dive - SkyRLDeep Dive - FlashAttentionDeep Dive - FlashInferDeep Dive - DeepGEMMDeep Dive - NCCLDeep Dive - MegatronDeep Dive - DeepSpeedDeep Dive - RayDeep Dive - MLflowDeep Dive - PyTorchDeep Dive - TransformersDeep Dive - SGLangDeep Dive - slimeDeep Dive - DeepEPDeep Dive - TinkerDeep Dive - Light-PEFT
Back to Topics
LearnTransformer Deep DivesPositional Encoding: RoPE & ALiBi
🧠HardTransformer Architecture

Positional Encoding: RoPE & ALiBi

Understand why transformers need position information, how sinusoidal encodings work, how RoPE and ALiBi encode relative position, and why long-context extrapolation needs careful evaluation.

30 min read
Learning path
Step 99 of 196 in the full curriculum
Vision Transformers and Image EncodersLayer Normalization: Pre-LN vs Post-LN

Personalize this lesson

Adapt explanations and teaching visuals to your background and preferred voice.

Put two lines from a deployment log on a screen: “The model loaded the checkpoint” and “The checkpoint loaded the model.” They reuse the same words, but report opposite events. A model that only compares token content has no slot index to tell those commands apart.

Vision transformers expose that gap with image patches, and text has it too. The self-attention mechanism compares content, not position. Predict what happens when the token rows for “model,” “loaded,” and “ckpt” are shuffled.

The answer gives us our first diagnostic: unmasked attention shuffles its outputs along with its inputs. That’s permutation equivariance, and it explains why transformers need a position signal. We’ll follow the signal through three insertion points: vectors added to embeddings, RoPE rotations on queries and keys, and ALiBi’s linear distance bias on attention logits.

Then we’ll stress the same idea at long length. A formula can produce a value at position 32,000 even when training stopped at 4,096. That calculation is useful, but it isn’t evidence that the model can find a buried instruction there.

One boundary stays fixed throughout: a position method can rank permitted keys, while a causal mask must still hide future keys. A useful test changes order, checks the permitted scores, and confirms that forbidden positions remain forbidden.


First, watch attention lose the order

Before adding any position feature, make one prediction. If every token vector stays the same but the rows move, should content-only attention preserve the original row order, or should its outputs move with them?

Self-attention computes:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) VAttention(Q,K,V)=softmax(dk​​QKT​)V

The product compares every query with every key (QKTQK^TQKT), scales by dk\sqrt{d_k}dk​​ (the key width), turns scores into softmax weights, and mixes value rows VVV. No term reads “first,” “second,” or “third.” The weights depend on content, not index.[1]Reference 1Attention Is All You Need.https://arxiv.org/abs/1706.03762

So a row permutation has a predictable effect: it also permutes Q, K, and V. Every query sees the same collection of content vectors, only in a new order, and each output row follows its query.

Use a three-token slice of our running example, with one 2D vector per token. Predict the shuffled output before checking the table:

TokenVector
model[1,0][1, 0][1,0]
loaded[0,1][0, 1][0,1]
ckpt[1,1][1, 1][1,1]

Permutation P=[2,0,1]P = [2, 0, 1]P=[2,0,1] rewrites the sequence as ckpt, model, loaded. Unmasked attention on the shuffled rows is exactly the shuffled original output: Y′=P YY' = P\,YY′=PY. The block has preserved content relationships, not command order.

Two attention traces compare token order before and after permutation P=[2,0,1]. Token rows and attention-weight matrices reorder together, producing Y' = P Y and showing permutation equivariance without a position signal.
Unmasked self-attention is content-based. The weight matrix reorders with the tokens. Position encodings supply the missing index, direction, and distance signal.

The small check below recomputes attention after the permutation. Read True as a diagnosis: no hidden slot number entered the calculation.

permutation-equivariance.py
1import math 2 3tokens = { 4 "model": [1.0, 0.0], 5 "loaded": [0.0, 1.0], 6 "ckpt": [1.0, 1.0], 7} 8order = ["model", "loaded", "ckpt"] 9permutation = [2, 0, 1] 10 11def attention(rows: list[list[float]]) -> list[list[float]]: 12 scores = [ 13 [sum(q_i * k_i for q_i, k_i in zip(q, k)) / math.sqrt(2) for k in rows] 14 for q in rows 15 ] 16 outputs = [] 17 for row in scores: 18 normalizer = sum(math.exp(value) for value in row) 19 weights = [math.exp(value) / normalizer for value in row] 20 outputs.append([ 21 sum(weight * value[column] for weight, value in zip(weights, rows)) 22 for column in range(2) 23 ]) 24 return outputs 25 26baseline = attention([tokens[name] for name in order]) 27shuffled = attention([tokens[order[index]] for index in permutation]) 28expected = [baseline[index] for index in permutation] 29 30same_output_up_to_permutation = all( 31 abs(actual - target) < 1e-12 32 for actual_row, target_row in zip(shuffled, expected) 33 for actual, target in zip(actual_row, target_row) 34) 35print(same_output_up_to_permutation) 36print([round(row[0], 3) for row in baseline]) 37print([round(row[0], 3) for row in shuffled])
Output
1True 2[0.802, 0.599, 0.752] 3[0.752, 0.802, 0.599]

A causal mask changes this result by removing future keys. A decoder-only model can then infer some order from which positions are visible, and Haviv et al. found NoPos runs competitive with sinusoidal and learned embeddings for causal language modeling.[2]Reference 2Transformer Language Models without Positional Encodings Still Learn Positional Information.https://arxiv.org/abs/2203.16634 Their bidirectional masked models failed to converge without an explicit position signal. Visibility gives a direction, but it still doesn’t provide a numeric coordinate or distance feature.

That distinction tells us where to look next. Absolute encodings, RoPE, and ALiBi answer the same ordering gap at different points in the block. They’re alternatives, not stacked stages.

The table is a map of those insertion points. For each row, ask what downstream quantity can first “feel” position.

ApproachHow it worksWhat it modifiesExamples
Absolute (additive)Add a position vector to the token embeddingEmbeddingsOriginal Transformer, BERT, GPT-2[1]Reference 1Attention Is All You Need.https://arxiv.org/abs/1706.03762[3]Reference 3BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.https://arxiv.org/abs/1810.04805[4]Reference 4GPT-2 Source Implementation.https://github.com/openai/gpt-2/blob/master/src/model.py
Relative (multiplicative)Rotate Q and K by a position-dependent angleQ/K projectionsRoFormer, Llama family[5]Reference 5RoFormer: Enhanced Transformer with Rotary Position Embedding.https://arxiv.org/abs/2104.09864[6]Reference 6The Llama 3 Herd of Models.https://arxiv.org/abs/2407.21783
Relative (additive bias)Add a distance penalty to attention logitsAttention scoresALiBi[7]Reference 7Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.https://arxiv.org/abs/2108.12409
Diagram showing Token embedding, Absolute: add p_i, Project Q, K, V, and Projected Q, K.
Token embedding, Absolute: add p_i, Project Q, K, V, and Projected Q, K.
Three compact attention paths show where each positional method enters. Absolute encoding adds p_i to x_i before Q and K projections, RoPE rotates projected q_i and k_j, and ALiBi subtracts m_h times causal distance from the attention logit.
Absolute encodings change the input vector, RoPE changes Q/K geometry, and ALiBi changes the pre-softmax score. One block, three insertion points.

When debugging a position mismatch, inspect the first tensor that changed: the embedding, projected Q/K, or attention score matrix. That check also catches accidental stacking of methods meant to be alternatives.

The first map entry adds position before any Q, K, or V projection. Start there, then we’ll move the signal deeper into attention.


Absolute position: give every slot a multi-speed fingerprint

Nearby slots need distinguishable labels, while far slots need a slower signal that tracks broad location. The original Transformer meets both needs with several paired waves added to each token embedding.[1]Reference 1Attention Is All You Need.https://arxiv.org/abs/1706.03762

At position 0, every sine starts at 0 and every cosine at 1. Move to position 2 and the fastest pair has moved two radians, while slower pairs barely move. The combined phases form a position fingerprint before the network sees Q, K, or V.

For position pos\text{pos}pos and dimension iii, with dmodeld_{\text{model}}dmodel​ the embedding width:

PE(pos,2i)=sin⁡(pos100002i/dmodel)PE_{(\text{pos}, 2i)} = \sin\left(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\right)PE(pos,2i)​=sin(100002i/dmodel​pos​)

PE(pos,2i+1)=cos⁡(pos100002i/dmodel)PE_{(\text{pos}, 2i+1)} = \cos\left(\frac{\text{pos}}{10000^{2i/d_{\text{model}}}}\right)PE(pos,2i+1)​=cos(100002i/dmodel​pos​)

The paired waves carry one useful algebraic property. A fixed offset is a linear transform, PEpos+k=Rk⋅PEposPE_{\text{pos}+k} = R_k \cdot PE_{\text{pos}}PEpos+k​=Rk​⋅PEpos​, where the rotation RkR_kRk​ depends only on kkk. In principle, later layers can learn relative attention from that structure.

The generator below makes the dial picture concrete with an 8-by-8 table. Before running it, predict row 0 and the first pair at row 2.

sinusoidal-positional-encoding.py
1import math 2 3def sinusoidal_positional_encoding(max_len: int, d_model: int) -> list[list[float]]: 4 assert d_model % 2 == 0 5 table: list[list[float]] = [] 6 for pos in range(max_len): 7 row = [0.0] * d_model 8 for i in range(0, d_model, 2): 9 frequency = math.exp(-(math.log(10000.0) * i) / d_model) 10 angle = pos * frequency 11 row[i] = math.sin(angle) 12 row[i + 1] = math.cos(angle) 13 table.append(row) 14 return table 15 16pe = sinusoidal_positional_encoding(max_len=8, d_model=8) 17print(len(pe), len(pe[0])) 18print([round(x, 3) for x in pe[0]]) 19print(round(pe[2][0], 3), round(pe[2][1], 3))
Output
18 8 2[0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0] 30.909 -0.416

The dials have different wavelengths. With dmodel=512d_{\text{model}}=512dmodel​=512, the table below samples one fast, one middle, and one slow pair using λ=2π⋅10000i/dmodel\lambda = 2\pi \cdot 10000^{i/d_{\text{model}}}λ=2π⋅10000i/dmodel​ for each pair’s first dimension. Use it to predict which lane changes most between neighboring tokens.

Dimension pairWavelengthWhat it tracks
(0,1)(0, 1)(0,1)∼6\sim 6∼6 tokensFine local position
(64,65)(64, 65)(64,65)∼20\sim 20∼20 tokensMedium-scale structure
(510,511)(510, 511)(510,511)∼60,000\sim 60{,}000∼60,000 tokensCoarse global position
sinusoidal-wavelengths.py
1import math 2 3d_model = 512 4for first_dimension in [0, 64, 510]: 5 angular_frequency = 10000 ** (-first_dimension / d_model) 6 wavelength = 2 * math.pi / angular_frequency 7 print(first_dimension, round(wavelength))
Output
10 6 264 20 3510 60611

The waves are easier to read as lanes than as a matrix:

Three sinusoidal positional-encoding lanes at d_model=512 show fast, medium, and slow frequency pairs. A shared p=12 marker samples each sine/cosine pair and forms a multi-scale position fingerprint.
The figure samples position 12 so the fast pair has already wound almost twice around, while the slow pair has barely left (0, 1). One index, three timescales.

Sinusoids are fixed. BERT (Bidirectional Encoder Representations from Transformers) and GPT-2 instead learn a table P∈RLmax⁡×dP \in \mathbb{R}^{L_{\max} \times d}P∈RLmax​×d: one trainable vector per slot, hard-limited at Lmax⁡L_{\max}Lmax​.[3]Reference 3BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.https://arxiv.org/abs/1810.04805[4]Reference 4GPT-2 Source Implementation.https://github.com/openai/gpt-2/blob/master/src/model.py Predict the consequence first: what happens at a position beyond the last row?

PropertySinusoidalLearned
Parameters0 (fixed formula)Lmax⁡×dL_{\max} \times dLmax​×d
FlexibilityFixed inductive biasAdapts during training
Past Lmax⁡L_{\max}Lmax​Formula is definedNo row exists
Original Transformer ablationStrong baselineNearly identical result

Vaswani et al. tested both and reported “nearly identical results” (Table 3, row E). Sinusoids were attractive because their formula can be evaluated at unseen indices. That’s a definition, not a quality guarantee: Press et al. measured sharp perplexity degradation when sinusoidal models ran far past their training length on WikiText-103.[7]Reference 7Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.https://arxiv.org/abs/2108.12409

Why add instead of concatenate? Put two ddd-wide vectors side by side and the next layer sees width 2d2d2d. Unless you project back down, square matrices such as WQW_QWQ​, WKW_KWK​, and WVW_VWV​ then grow about 4x. Addition keeps width ddd, but it also gives later projections one mixed vector rather than separate content and position channels.

Why do absolute positional encodings get added to token embeddings instead of concatenated?

Answer

Concatenation would double the hidden width from ddd to 2d2d2d unless the model projected back down. If the transformer stayed at width 2d2d2d, square projections such as WQW_QWQ​, WKW_KWK​, and WVW_VWV​ would become roughly 4x larger. Addition keeps width ddd and gives later layers one combined vector. Whether those layers use the mixture well is empirical.

Absolute methods leave us with three questions. Does quality hold beyond the trained length? Can the model infer an offset from two absolute vectors? Is mixing content and position in one stream a good trade? Relative methods move the distance signal into attention itself, which is the next experiment.


RoPE: make a shared offset visible inside QK

Now move the position signal past the embedding. Keep one query and one key fixed, then place both at positions (m,n)(m,n)(m,n). If both positions shift by 100, should their relative score change?

RoPE (Rotary Position Embeddings) answers by rotating each query and key in 2D subspaces. It comes from RoFormer and is used in Llama-family models, including Llama 3 with RoPE base θ=500,000\theta = 500{,}000θ=500,000.[5]Reference 5RoFormer: Enhanced Transformer with Rotary Position Embedding.https://arxiv.org/abs/2104.09864[6]Reference 6The Llama 3 Herd of Models.https://arxiv.org/abs/2407.21783 Hold the unrotated vectors fixed, and the dot product depends on the offset between them rather than on their shared absolute shift.

The picture below makes that prediction visible. The absolute angles move, but the phase gap doesn’t.

Two RoPE unit-circle pairs compare positions (m=2,n=1) and (m=102,n=101) at theta=0.5. Both have relative phase delta=-0.5 and the same q-prime dot k-prime score of 0.877583 after shifting both positions by 100.
Shift both tokens by 100. Absolute angles change. The relative phase stays $-0.5$, so the positional part of $q'^{\top}k'$ stays $0.878$.

For one 2D pair (q2i,q2i+1)(q_{2i}, q_{2i+1})(q2i​,q2i+1​) at position mmm, RoPE applies this rotation:

(q2i(m)q2i+1(m))=(cos⁡(mθi)−sin⁡(mθi)sin⁡(mθi)cos⁡(mθi))(q2iq2i+1)\begin{pmatrix} q_{2i}^{(m)} \\ q_{2i+1}^{(m)} \end{pmatrix} = \begin{pmatrix} \cos(m\theta_i) & -\sin(m\theta_i) \\ \sin(m\theta_i) & \cos(m\theta_i) \end{pmatrix} \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}(q2i(m)​q2i+1(m)​​)=(cos(mθi​)sin(mθi​)​−sin(mθi​)cos(mθi​)​)(q2i​q2i+1​​)

Each consecutive pair spins like one clock hand. Its angle depends on the token index mmm and the pair frequency θi\theta_iθi​. Production RoPE usually sets those frequencies from the per-head rotary width, not the full hidden size:

θi=10000−2i/drotary\theta_i = 10000^{-2i/d_{\text{rotary}}}θi​=10000−2i/drotary​

If every head dimension is rotated, drotary=dkd_{\text{rotary}} = d_kdrotary​=dk​. Some stacks rotate only part of each head, so use the configured rotary dimension when reproducing a checkpoint.

The cancellation comes from composing rotations. For one pair,

q(m)⊤k(n)=q⊤R((n−m)θi) kq^{(m)\top} k^{(n)} = q^{\top} R((n-m)\theta_i)\, kq(m)⊤k(n)=q⊤R((n−m)θi​)k

The same unrotated vectors at (m,n)=(5,2)(m,n)=(5,2)(m,n)=(5,2) and (105,102)(105,102)(105,102) therefore get the same positional score. The absolute coordinates differ; the offset doesn’t.

rope-relative-offset.py
1import math 2 3def rotate_2d(vec: list[float], pos: int, theta: float) -> list[float]: 4 cosine, sine = math.cos(pos * theta), math.sin(pos * theta) 5 x, y = vec 6 return [x * cosine - y * sine, x * sine + y * cosine] 7 8def dot(left: list[float], right: list[float]) -> float: 9 return sum(x * y for x, y in zip(left, right)) 10 11query = [0.8, 0.6] 12key = [0.7, 0.5] 13theta = 0.5 14score_a = dot(rotate_2d(query, 5, theta), rotate_2d(key, 2, theta)) 15score_b = dot(rotate_2d(query, 105, theta), rotate_2d(key, 102, theta)) 16print(round(score_a, 6), round(score_b, 6))
Output
10.040884 0.040884

The output confirms the shared-shift prediction. It also marks the limit of this toy proof: a trained model’s context window depends on content-dependent Q and K vectors across many layers, not on this identity alone.

Use a unit-vector walk-through to isolate the phase term. Let q=k=[1,0]q = k = [1, 0]q=k=[1,0] and θ=0.5\theta = 0.5θ=0.5.

  • Query at m=2m=2m=2, key at n=1n=1n=1: offset d=n−m=−1d = n-m = -1d=n−m=−1, score cos⁡(−0.5)≈0.878\cos(-0.5) \approx 0.878cos(−0.5)≈0.878.
  • Query at m=102m=102m=102, key at n=101n=101n=101: same offset, same score.

At offset −2-2−2, the same pair scores cos⁡(−1.0)≈0.540\cos(-1.0) \approx 0.540cos(−1.0)≈0.540. Don’t turn that comparison into “farther is always weaker.” Cosine phases can rise again, and a real head sums many frequencies.

One head with drotary=8d_{\text{rotary}}=8drotary​=8 contains four such pairs. With the standard base-100001000010000 schedule, their frequencies are 111, 0.10.10.1, 0.010.010.01, and 0.0010.0010.001. For q=k=[1,0]q=k=[1,0]q=k=[1,0] in every pair and positions m=4m=4m=4, n=2n=2n=2, predict which lane turns negative before looking at the figure. The pair scores are cos⁡(−2θi)\cos(-2\theta_i)cos(−2θi​):

RoPE pair mechanics for d_rotary=8. Query position m=4 and key position n=2 split into four 2D lanes with frequencies 1, 0.1, 0.01, and 0.001. Pair scores are -0.416, 0.980, 1.000, and 1.000, which sum to 2.564.
The fast pair has already gone negative at offset $-2$. The slow pairs still look almost aligned. The attention logit is the sum, not any single cosine.

Complex multiplication is the same 2D rotation: (x+iy) eimθ(x + iy)\,e^{i m \theta}(x+iy)eimθ. The next helper rotates a whole head, then checks the shared-shift property across all its pairs.

rope-complex-rotation.py
1import cmath 2 3def rope_freqs(dim: int, base: float = 10000.0) -> list[float]: 4 return [1.0 / (base ** (index / dim)) for index in range(0, dim, 2)] 5 6def rotate(vec: list[float], pos: int, freqs: list[float]) -> list[float]: 7 rotated: list[float] = [] 8 for pair, freq in enumerate(freqs): 9 x, y = vec[2 * pair], vec[2 * pair + 1] 10 spun = complex(x, y) * cmath.rect(1.0, pos * freq) 11 rotated.extend([spun.real, spun.imag]) 12 return rotated 13 14def dot(left: list[float], right: list[float]) -> float: 15 return sum(x * y for x, y in zip(left, right)) 16 17freqs = rope_freqs(dim=4) 18vec = [1.0, 0.0, 1.0, 0.0] 19score_a = dot(rotate(vec, 0, freqs), rotate(vec, 2, freqs)) 20score_b = dot(rotate(vec, 1, freqs), rotate(vec, 3, freqs)) 21print(round(score_a, 6), round(score_b, 6))
Output
10.583653 0.583653

RoPE rotates Q and K, not V. Q and K route attention, so their relative geometry decides which value rows get weight. V supplies the rows being mixed and isn’t directly rotated in that attention step, though earlier layers can already have put position-dependent context into it.

Why does RoPE rotate Q and K without directly rotating V?

Answer

Q and K decide which values receive attention weight, so rotating them makes the routing score depend on relative offset. V supplies the information being mixed and isn't rotated in that attention step. After earlier layers, V can still carry position-dependent context.

Keep routing and aggregation separate when comparing the three methods:

PropertySinusoidalLearnedRoPE
Position infoAdded to embeddingsAdded to embeddingsApplied to Q, K only
Relative positionImplicitImplicitExplicit in the dot product
Direct transform on VNot applicableNot applicableNone
Extra parameters0Lmax⁡×dL_{\max} \times dLmax​×d0

RoFormer analyzes a long-term decay bound aggregated over frequencies, not a guarantee that one pair’s cosine falls forever.[5]Reference 5RoFormer: Enhanced Transformer with Rotary Position Embedding.https://arxiv.org/abs/2104.09864 For identical unit vectors in one pair, SΔ=cos⁡(Δθ)S_{\Delta} = \cos(\Delta\theta)SΔ​=cos(Δθ), which oscillates.

That distinction is worth testing directly. If distance itself must always lower the positional term, what should happen when a cosine comes back up?

rope-offset-is-not-monotonic.py
1import math 2 3theta = 0.5 4distances = [1, 2, 4, 6, 8] 5scores = [math.cos(distance * theta) for distance in distances] 6print(distances) 7print([round(score, 3) for score in scores]) 8print(scores[-1] > scores[-2])
Output
1[1, 2, 4, 6, 8] 2[0.878, 0.54, -0.416, -0.99, -0.654] 3True
Two distance-response plots compare one RoPE pair S_delta=cos(0.5 delta) with an ALiBi slope B_delta=-0.1 delta. RoPE rises from -0.990 at distance 6 to -0.654 at distance 8, while ALiBi keeps decreasing.
One RoPE frequency oscillates. ALiBi's logit bias keeps dropping. A full RoPE head is a sum over frequencies plus content, so you still have to measure it.

The non-monotonic example is not just a toy warning. Men et al. show a production trap in Llama-2 experiments: perplexity can look acceptable while retrieval collapses. They saw this with a RoPE base below their derived lower bound, including a small base such as 500, and in some larger-base settings where next-token loss stayed low.[8]Reference 8Base of RoPE Bounds Context Length.https://arxiv.org/abs/2405.14591 A changed RoPE config still needs retrieval and task evaluation at the deployed length.

RoPE exposes offset through phase. ALiBi makes a different choice: it writes “farther is weaker” directly into the score.


ALiBi: make recency a score bias

Suppose two visible keys have the same raw QK score, but one sits four positions behind the query. Should a head be allowed to prefer the newer key by a fixed amount? ALiBi (Attention with Linear Biases) answers yes without changing the embedding or rotating Q and K. After the query-key product, it adds a head-specific linear bias:[7]Reference 7Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.https://arxiv.org/abs/2108.12409

Attention(Q,K,V)=softmax(QKTdk+B(h))V,Bij(h)=−mh(i−j) for j≤i\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}} + B^{(h)}\right) V,\quad B^{(h)}_{ij} = -m_h(i-j)\ \text{for}\ j \le iAttention(Q,K,V)=softmax(dk​​QKT​+B(h))V,Bij(h)​=−mh​(i−j) for j≤i

In a causal decoder, the current token gets zero penalty, one step back gets −mh-m_h−mh​, two steps back gets −2mh-2m_h−2mh​, and so on. Future keys stay at −∞-\infty−∞ from the causal mask. Press et al. note that this bias is not multiplied by dk\sqrt{d_k}dk​​; it’s added to the already-scaled (or, in their presentation, unscaled) scores.

The head slopes supply different recency strengths. For nnn heads, the paper starts at 2−8/n2^{-8/n}2−8/n and uses that value as the geometric ratio. For 8 heads that’s m=12,14,…,1256m = \tfrac12, \tfrac14, \ldots, \tfrac1{256}m=21​,41​,…,2561​: Head 1 is short-sighted, while Head 8 barely penalizes distance. For a non-power-of-two head count, the reference implementation keeps the power-of-two schedule for the largest p<np < np<n, then appends every other slope from the 2p2p2p schedule until it has nnn slopes.

ALiBi visual with the eight-head slope spectrum from 1/2 to 1/256, a four-token causal bias matrix for the steepest head, and a raw-logit to softmax trace showing finite past penalties and hard future masking.
Steep slopes stay local. Gentle slopes stay long-range. Past keys get a finite penalty. Future keys are masked, not ALiBi-penalized.

Read the slope table as a prediction tool: which head should hold onto an older key more strongly?

HeadSlope mmmEffect
Head 11/21/21/2Strong local attention
Head 41/161/161/16Moderate range
Head 81/2561/2561/256Very long-range

Run that rule on our checkpoint example. “Loaded” at position 3 attends to “model” at position 1 with raw score 2.52.52.5. Head 4 has m=1/16=0.0625m = 1/16 = 0.0625m=1/16=0.0625, so distance 2 contributes −0.125-0.125−0.125 and the logit becomes 2.3752.3752.375. “The” at position 0 is distance 3, so its logit becomes 2.31252.31252.3125. Head 1 would subtract 1.01.01.0 and 1.51.51.5 instead.

The helper below applies one slope to one visible key. Predict the two outputs for distance 4 and raw score 4.0 before comparing the steep and gentle heads.

alibi-one-score.py
1def alibi_score(raw_score: float, query_pos: int, key_pos: int, slope: float) -> float: 2 distance = max(query_pos - key_pos, 0) 3 return raw_score - slope * distance 4 5raw = 4.0 6query_pos = 10 7key_pos = 6 8head_1 = alibi_score(raw, query_pos, key_pos, slope=1 / 2) 9head_8 = alibi_score(raw, query_pos, key_pos, slope=1 / 256) 10print(head_1, round(head_8, 3))
Output
12.0 3.984

One score hides an important boundary, so the next snippet builds the full causal bias tensor. It includes the non-power-of-two slope helper from the reference implementation and writes −∞-\infty−∞ only for future keys.

alibi-bias-matrix.py
1import math 2 3def alibi_slopes_power_of_two(n_heads: int) -> list[float]: 4 start = 2 ** (-(2 ** -(math.log2(n_heads) - 3))) 5 return [start * (start ** head) for head in range(n_heads)] 6 7def alibi_slopes(n_heads: int) -> list[float]: 8 assert n_heads > 0 9 if math.log2(n_heads).is_integer(): 10 return alibi_slopes_power_of_two(n_heads) 11 closest = 2 ** math.floor(math.log2(n_heads)) 12 extra = alibi_slopes(2 * closest)[0::2][: n_heads - closest] 13 return alibi_slopes_power_of_two(closest) + extra 14 15def build_alibi_bias(n_heads: int, seq_len: int) -> list[list[list[float]]]: 16 slopes = alibi_slopes(n_heads) 17 bias: list[list[list[float]]] = [] 18 for slope in slopes: 19 head = [] 20 for query in range(seq_len): 21 row = [] 22 for key in range(seq_len): 23 if key > query: 24 row.append(float("-inf")) 25 else: 26 row.append(-slope * (query - key)) 27 head.append(row) 28 bias.append(head) 29 return bias 30 31bias = build_alibi_bias(n_heads=4, seq_len=4) 32print(len(bias), len(bias[0]), len(bias[0][0])) 33print([round(value, 4) if math.isfinite(value) else value for value in bias[0][3]]) 34print([round(value, 4) if math.isfinite(value) else value for value in bias[-1][3]])
Output
14 4 4 2[-0.75, -0.5, -0.25, -0.0] 3[-0.0117, -0.0078, -0.0039, -0.0]

In one original-paper experiment, a 1.3 billion parameter ALiBi model trained at length 1024 and evaluated at 2048 matched the perplexity of a sinusoidal model trained at 2048, while using about 11% less training time and memory in that setup.[7]Reference 7Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.https://arxiv.org/abs/2108.12409 That result comes with three mechanism-level properties worth separating:

  • The bias is monotonic: a farther visible key always gets a more negative penalty.
  • The rule is defined for any distance, so there's no learned table to run out of.
  • Fixed slopes give a spectrum from local heads to longer-range heads.

The finite entries in that matrix are a soft recency bias. Very negative logits can underflow to zero in finite precision after the softmax max-shift, but mathematically a distant visible key keeps a nonzero weight. Only the causal mask hard-zeros the future.

The final snippet tests that distinction with equal raw scores. A farther visible key should lose weight, not disappear.

alibi-bias-is-not-a-mask.py
1import math 2 3def softmax(logits: list[float]) -> list[float]: 4 maximum = max(logits) 5 shifted = [math.exp(value - maximum) for value in logits] 6 total = sum(shifted) 7 return [value / total for value in shifted] 8 9raw_scores = [2.0, 2.0, 2.0] 10distances = [2, 1, 0] 11biased_scores = [ 12 score - 0.5 * distance 13 for score, distance in zip(raw_scores, distances) 14] 15weights = softmax(biased_scores) 16print([round(weight, 3) for weight in weights]) 17print(weights[0] > 0)
Output
1[0.186, 0.307, 0.506] 2True

Two past tokens have equal raw attention scores, but one is four positions farther from the query under ALiBi. Does ALiBi mask the farther token?

Answer

No. ALiBi subtracts a larger linear bias from the farther token before softmax, so its weight usually falls but stays nonzero. Only the separate causal mask removes future positions outright.

A closed-form bias can be evaluated at offsets the model never trained on. Whether the checkpoint still retrieves buried evidence is a different question, and long-context evaluation makes that question concrete.


Long context: a defined formula still needs evidence

Here’s the operational handoff: a checkpoint trained at 4K now has a 32K serving target, and a passkey may sit near token 30,000. You can write down PE32000PE_{32000}PE32000​ or R32000R_{32000}R32000​, but that only proves the position rule is defined. It doesn’t prove the model can route attention to the passkey.

Use the table as an experiment map. Each row separates what arithmetic does past the training length from what a paper actually measured.

MethodWhat happens past training lengthWhat the papers actually measured
SinusoidalFormula can compute unseen indicesPress et al.: sharp WikiText-103 perplexity drop past train LLL
Learned absoluteNo row exists past Lmax⁡L_{\max}Lmax​Extend or replace the table, then train and evaluate
RoPE (unchanged)Rotations continue at unseen offsetsChen et al.: poor direct extension in their Llama runs
ALiBiSame linear bias at new distancesPress et al.: 1024 → 2048 perplexity match in their 1.3B setup
RoPE with PI or YaRNGeometry is rescaled, usually with adaptationChen et al.: PI up to 32K; Peng et al.: YaRN up to 128K on evaluated Llama-family models

Use two evidence gates for an extension: short-context behavior must survive, then retrieval and target tasks must work at the new length. A clean perplexity curve clears neither gate by itself.

These are different experiments, not a universal ranking. Treat context length as a model-and-eval claim, not a config value.[7]Reference 7Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.https://arxiv.org/abs/2108.12409[9]Reference 9Extending Context Window of Large Language Models via Positional Interpolation.https://arxiv.org/abs/2306.15595[10]Reference 10YaRN: Efficient Context Window Extension of Large Language Models.https://arxiv.org/abs/2309.00071

PI: compress coordinates into the trained range

Position Interpolation (PI) scales position indices down so they land inside the trained range:[9]Reference 9Extending Context Window of Large Language Models via Positional Interpolation.https://arxiv.org/abs/2306.15595

f′(x,m)=f ⁣(x, m⋅LL′)f'(x, m) = f\!\left(x,\ m \cdot \frac{L}{L'}\right)f′(x,m)=f(x, m⋅L′L​)

Chen et al. started from LLaMA checkpoints trained at 2048 and, with up to 1,000 fine-tuning steps, reported windows up to 32,768. The frequencies stay put; only the index that multiplies θ\thetaθ is compressed. In a scale-4 toy (4096 → 16384), the last target position, 16383, maps to 4095.75. Predict that endpoint before running the code.

position-interpolation-map.py
1train_length = 4096 2target_length = 16384 3scale = train_length / target_length 4 5for target_position in [0, 4096, 8192, 16383]: 6 effective_position = target_position * scale 7 print(target_position, round(effective_position, 2))
Output
10 0.0 24096 1024.0 38192 2048.0 416383 4095.75

NTK-aware scaling: stretch frequencies unevenly

PI compresses every index equally. NTK-aware scaling instead changes the frequency base, stretching low-frequency bands more than high-frequency ones:[10]Reference 10YaRN: Efficient Context Window Extension of Large Language Models.https://arxiv.org/abs/2309.00071

θbase′=θbase⋅sd/(d−2)\theta'_{\text{base}} = \theta_{\text{base}} \cdot s^{d/(d-2)}θbase′​=θbase​⋅sd/(d−2)

Here s=Ltarget/Ltrains = L_{\text{target}} / L_{\text{train}}s=Ltarget​/Ltrain​ and ddd is the per-head rotary dimension. The first pair keeps θ0=1\theta_0 = 1θ0​=1 for any base; later pairs slow down. Peng et al. document this as earlier NTK-aware work while developing YaRN. Quality still depends on model, target length, adaptation data, and evaluation. Code Llama uses the same base-scaling idea at an extreme, setting its base to 10610^6106.[11]Reference 11Code Llama: Open Foundation Models for Codehttps://arxiv.org/abs/2308.12950

YaRN: treat frequency bands differently

YaRN (Yet another RoPE extensioN) combines NTK-by-parts interpolation with an attention temperature.[10]Reference 10YaRN: Efficient Context Window Extension of Large Language Models.https://arxiv.org/abs/2309.00071 Its bands make a deliberate trade: high-frequency bands stay closer to their original wavelengths for local detail, low-frequency bands interpolate for global span, and middle bands ramp between the two. Peng et al. report Llama-2 variants evaluated through 128K, including passkey retrieval inside that window for their 7B and 13B YaRN runs.

The paper’s recommended temperature fit on its Llama experiments is 1/t=0.1ln⁡(s)+1\sqrt{1/t} = 0.1 \ln(s) + 11/t​=0.1ln(s)+1. They implement it by scaling the complex RoPE embeddings by that factor, equivalent to scaling qqq and kkk without touching the attention kernel. Treat ttt as a hyperparameter to validate on the deployed model.

The figure compares the three choices on the same 4K-to-16K target. Look for what stays local, what stretches, and where the attention factor enters:

Three RoPE extension panels use a 4K-to-16K example. Position Interpolation maps target positions into 0-to-4K, NTK-aware scaling changes the base from 10,000 to about 40,890 and slows later frequency pairs, and YaRN combines band treatment with an attention factor of 1.139.
PI compresses indices. NTK-aware scaling changes the base, leaving the fastest pair at frequency 1 and slowing later pairs. YaRN adds band-wise treatment plus an attention factor.

Llama 3 takes a related production path without PI: it raises the RoPE base to 500,000 during pretraining to support longer contexts.[6]Reference 6The Llama 3 Herd of Models.https://arxiv.org/abs/2407.21783 That’s trained geometry, not a config flag to copy onto an arbitrary checkpoint.


Choose by mechanism, then earn the window

Choose the insertion point that matches the behavior you want. Then test short-context quality, long-range retrieval, generation, and target tasks at the length you plan to advertise.

GoalCandidateWhat you still have to measure
Reproduce the original TransformerSinusoidal absolute encodingQuality at trained lengths and any longer lengths you serve
Finite learned slotsLearned absolute embeddingsHow new rows are initialized and adapted
Relative offset inside QK scoresRoPETarget-length retrieval and generation, especially after scaling
Explicit monotonic recency biasALiBiWhether the recency prior hides evidence long tasks need
Extend an existing RoPE checkpointPI or YaRN-style adaptationShort-context regression and long-context behavior after adaptation

The implementation choice decides where position enters attention. The checkpoint still has to earn the window you advertise.

Check the three insertion points

  • Explain why unmasked self-attention without a position signal is permutation equivariant.
  • Point to where sinusoids, RoPE, and ALiBi insert position: embeddings, Q/K geometry, or logits.
  • Compute a RoPE relative phase and an ALiBi distance penalty on a tiny example.
  • Treat configured context length as a claim that needs retrieval and task evidence at the deployed length.

Common misconceptions

  • Order seems implicit: Symptom: you say unmasked attention already knows sequence order. Cause: you skipped the permutation-equivariance check. Fix: start from content-only attention, then account separately for position signals and masking.
  • All methods sound the same: Symptom: sinusoids, learned tables, RoPE, and ALiBi blur together. Cause: you aren't tracking the insertion point. Fix: embeddings vs Q/K geometry vs logit bias.
  • RoPE rotates the wrong tensor: Symptom: you apply RoPE to embeddings or V. Cause: routing and aggregation got merged. Fix: rotate Q and K after projection; leave V without a direct RoPE rotation.
  • Long context looks solved on paper: Symptom: perplexity improves but retrieval still fails. Cause: you treated mathematical validity as behavioral proof. Fix: run passkey, retrieval, summarization, and target-task evals at the deployed length.
  • Any base change is enough: Symptom: the config advertises a larger window but distant facts disappear. Cause: a new θ\thetaθ doesn't teach the model to use long-range evidence. Fix: pair geometry changes with an adaptation method, long-context data, and task-level checks.
  • Concatenate by default: Symptom: width and projection cost balloon. Cause: you tried to keep content and position in separate channels at all costs. Fix: add position vectors unless you have a reason and a budget for a wider stack.
Complete the lesson

Mastery Check

Answer every question, then check your score. Score 75% or higher to mark this lesson complete.

1.An unmasked self-attention block receives token embeddings with no positional signal. If the input rows are permuted before computing Q, K, and V, what should happen to the block output?

Correct answer: The output rows permute in the same way, because attention is content-based and has no built-in slot index.

Without a positional signal, unmasked self-attention is permutation equivariant: shuffling the input rows shuffles the outputs the same way. A causal mask breaks that symmetry and can support implicit position inference, but this question explicitly removes both masking and position features.

2.An engineer wants to combine a d-dimensional token embedding with a d-dimensional absolute position vector. If the model concatenates them and keeps the transformer at width 2d instead of adding them, what's the main cost?

Correct answer: Square projections such as W_Q, W_K, and W_V become roughly 4x larger, while addition keeps the hidden width at d.

Concatenating a d-dimensional content vector with a d-dimensional position vector doubles the hidden width unless an extra projection reduces it. If the transformer runs at width 2d, square projection matrices scale roughly with the square of width, so Q, K, and V projections become much larger. Addition keeps width fixed, though it doesn't guarantee that content and position remain neatly separated.

3.In sinusoidal positional encoding with d_model = 8, dimensions 0 and 1 use angle equal to the position. At position 2, what are those two values, and why are sine and cosine paired at each frequency?

Correct answer: sin(2) ~= 0.909 and cos(2) ~= -0.416; a fixed offset acts like a rotation, so PE_pos+k can be a linear function of PE_pos.

For the first sinusoidal pair, the angular frequency is 1, so position 2 gives angle 2 radians. The sine and cosine pair at a shared frequency behaves like a 2D rotation: moving by a fixed offset k can be expressed by a rotation matrix that depends on k rather than on the absolute position. Higher dimension pairs use smaller frequencies, so they change more slowly and provide coarser position signals.

4.A RoPE attention head rotates only Q and K. In one 2D pair, fixed q = k = [1, 0] and theta = 0.5. What happens to the query-key dot product for positions (m=5, n=3) versus (m=105, n=103), and what role does V play in this RoPE step?

Correct answer: Both scores are cos(-1.0) ~= 0.540; the shared shift cancels because Q and K rotations depend on relative offset, and V isn't directly rotated.

For fixed q and k in a 2D RoPE pair, the position-dependent part of the dot product depends on (n - m) theta. Both position pairs have n - m = -2, so the angle is -1.0 radians and the dot product is cos(-1.0) ~= 0.540. RoPE affects attention routing by rotating Q and K; V isn't directly rotated in that attention operation.

5.A developer says RoPE behaves like ALiBi because larger offsets always reduce the positional term. In one 2D RoPE pair with fixed q = k = [1, 0] and theta = 1.0, what do offsets Delta = 3 and Delta = 6 show?

Correct answer: They give cos(3) ~= -0.990 and cos(6) ~= 0.960, so the farther offset can have a larger RoPE term.

For a single RoPE pair with identical unit vectors, the positional contribution is cos(Delta * theta). With theta = 1.0, Delta = 3 gives about -0.990, while Delta = 6 gives about 0.960. This shows that RoPE exposes relative offset through rotations, but it isn't an explicit monotonic distance penalty. ALiBi is the method here that subtracts a linear distance bias from attention logits.

6.In an 8-head causal decoder using ALiBi slopes 1/2 through 1/256, a query at position 10 has raw logit 4.0 for a visible key at position 6. What logits enter softmax for Head 1 and Head 8?

Correct answer: Head 1: 2.0; Head 8: about 3.984. The gentle-slope head penalizes this distant visible key much less.

The distance is 10 - 6 = 4. ALiBi adds -m_h times distance to the raw attention logit. Head 1 has m = 1/2, so the penalty is -2.0 and the logit becomes 2.0. Head 8 has m = 1/256, so the penalty is -4/256 = -0.015625 and the logit is about 3.984. These are finite visible-key logits; future keys are handled by the causal mask separately.

7.One model uses a learned absolute position table with L_max = 4096. Another uses ALiBi biases. You want to run 8192-token inputs without changing the position mechanism. What's the key difference, and what caveat remains?

Correct answer: The learned table has no rows beyond 4096, while ALiBi's fixed distance-bias rule can be computed for longer distances; quality at 8192 still needs evaluation.

Learned absolute embeddings are a finite table, so positions beyond L_max require extending, replacing, or adapting that table. ALiBi has no learned position table; it adds a fixed linear distance bias to logits, and that rule is defined for any distance. That doesn't prove task quality at the new length, so evaluation remains necessary.

8.Your 4096-token RoPE checkpoint is being adapted for 16384-token inputs. Which option correctly pairs each extension method with the part of RoPE or attention it changes?

Correct answer: Position Interpolation maps position m to m * 4096 / 16384 while keeping the original RoPE frequencies; NTK-aware scaling changes the RoPE base; YaRN combines NTK-by-parts interpolation with attention temperature adjustment.

Position Interpolation compresses position indices into the range seen during training, so target positions are multiplied by 4096 / 16384. The RoPE frequencies themselves stay unchanged. NTK-aware scaling changes the RoPE frequency base using the per-head RoPE dimension. YaRN combines NTK-by-parts interpolation with attention temperature adjustment. Each change still needs target-length validation.

9.A 4K-trained RoPE model is configured for 64K by changing the RoPE base. Long-document perplexity barely changes, but passkey retrieval at 64K gets worse. What should you conclude?

Correct answer: The new base and stable perplexity aren't enough proof; retrieval and target-task behavior must be evaluated at the deployed length.

A positional rule can be defined at longer offsets without guaranteeing that the trained model uses long-range evidence well. Men et al. show cases where perplexity stays acceptable while retrieval collapses, including some RoPE-base settings. A production claim needs retrieval and task evaluation at the deployed context length, and may require an adaptation method such as PI or YaRN plus validation.

9 questions remaining.

Next Step
Continue to Layer Normalization: Pre-LN vs Post-LN

Position methods decide how attention scores depend on index and distance. <span data-glossary="layernorm">Layer normalization</span> decides whether the residual updates that follow those scores stay well scaled as the stack gets deeper.

PreviousVision Transformers and Image Encoders
Share this article
XFacebookLinkedInBlueskyRedditHacker NewsEmail
References

Attention Is All You Need.

Vaswani, A., et al. · 2017

https://arxiv.org/abs/1706.03762

Transformer Language Models without Positional Encodings Still Learn Positional Information.

Haviv, A., Ram, O., Press, O., Izsak, P., & Levy, O. · 2022 · Findings of EMNLP 2022

https://arxiv.org/abs/2203.16634

BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding.

Devlin, J., et al. · 2019 · NAACL 2019

https://arxiv.org/abs/1810.04805

GPT-2 Source Implementation.

OpenAI · 2019

https://github.com/openai/gpt-2/blob/master/src/model.py

RoFormer: Enhanced Transformer with Rotary Position Embedding.

Su, J., et al. · 2021

https://arxiv.org/abs/2104.09864

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Train Short, Test Long: Attention with Linear Biases Enables Input Length Generalization.

Press, O., Smith, N. A., & Lewis, M. · 2022 · ICLR 2022

https://arxiv.org/abs/2108.12409

Base of RoPE Bounds Context Length.

Men, X., et al. · 2024 · NeurIPS 2024

https://arxiv.org/abs/2405.14591

Extending Context Window of Large Language Models via Positional Interpolation.

Chen, S., et al. · 2023

https://arxiv.org/abs/2306.15595

YaRN: Efficient Context Window Extension of Large Language Models.

Peng, B., et al. · 2023

https://arxiv.org/abs/2309.00071

Code Llama: Open Foundation Models for Code

Rozière, M., et al. · 2023

https://arxiv.org/abs/2308.12950

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.