ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Advanced Transformer Architecture
Chapter 1: Revisiting Sequence Modeling Limitations
Sequential Computation in Recurrent Networks
The Vanishing and Exploding Gradient Problems
Long Short-Term Memory (LSTM) Gating Mechanisms
Gated Recurrent Units (GRUs) Architecture
Challenges with Long-Range Dependencies
Parallelization Constraints in Recurrent Models
Chapter 2: The Attention Mechanism: Core Concepts
Motivation: Overcoming Fixed-Length Context Vectors
General Framework: Query, Value Abstraction
Mathematical Formulation of Dot-Product Attention
Scaled Dot-Product Attention
The Softmax Function for Attention Weights
Computational Aspects and Matrix Operations
Practice: Implementing Scaled Dot-Product Attention
Chapter 3: Multi-Head Self-Attention
Self-Attention: Queries, Keys, Values from the Same Source
Limitations of Single Attention Head
Introducing Multiple Attention Heads
Linear Projections for Q, K, V per Head
Parallel Attention Computations
Concatenation and Final Linear Projection
Analysis of What Different Heads Learn
Hands-on Practical: Building a Multi-Head Attention Layer
Chapter 4: Positional Encoding and Embedding Layer
The Need for Positional Information
Input Embedding Layer Transformation
Sinusoidal Positional Encoding: Formulation
Properties of Sinusoidal Encodings
Combining Embeddings and Positional Encodings
Alternative: Learned Positional Embeddings
Comparison: Sinusoidal vs. Learned Embeddings
Practice: Generating and Visualizing Positional Encodings
Chapter 5: Encoder and Decoder Stacks
Overall Transformer Architecture Overview
Encoder Layer Structure
Decoder Layer Structure
Masked Self-Attention in Decoders
Encoder-Decoder Cross-Attention
Position-wise Feed-Forward Networks (FFN)
Residual Connections (Add)
Layer Normalization (Norm)
Stacking Multiple Layers
Final Linear Layer and Softmax Output
Hands-on Practical: Constructing an Encoder Block
Chapter 6: Advanced Architectural Variants and Analysis
Computational Complexity of Self-Attention
Sparse Attention Mechanisms
Approximating Attention: Linear Transformers
Kernel-Based Attention Approximation (Performers)
Low-Rank Projection Methods (Linformer)
Transformer-XL: Segment-Level Recurrence
Relative Positional Encodings
Pre-Normalization vs Post-Normalization (Pre-LN vs Post-LN)
Scaling Laws for Neural Language Models
Parameter Efficiency and Sharing Techniques
Chapter 7: Implementation Details and Optimization
Choosing a Framework (PyTorch, TensorFlow, JAX)
Weight Initialization Strategies
Optimizers for Transformers (Adam, AdamW)
Learning Rate Scheduling (Warmup, Decay)
Regularization Techniques (Dropout, Label Smoothing)
Gradient Clipping
Mixed-Precision Training
Efficient Attention Implementations (FlashAttention)
Model Parallelism and Data Parallelism Strategies
Practice: Analyzing Attention Weight Distributions

Relative Positional Encodings

Absolute positional encodings provide a mechanism for Transformers to understand sequence order, but they treat each position independently. The sinusoidal encoding offers nice properties for modeling relative distances implicitly, but it's added before the attention mechanism operates. Learned absolute embeddings might struggle to generalize to sequence lengths longer than those seen during training. An alternative approach directly incorporates the relative distance between tokens into the attention calculation itself. This is the core idea behind Relative Positional Encodings (RPE).

The intuition is that the relationship between two words often depends more on how far apart they are rather than their absolute positions in the sequence. For instance, knowing that a verb follows its subject by one position might be a more generalizable pattern than knowing the subject is at position 5 and the verb is at position 6. RPE aims to make the model directly aware of these relative distances.

Modifying the Attention Score

Instead of adding positional information to the input embeddings, RPE modifies the self-attention scoring mechanism. The standard scaled dot-product attention calculates scores between a query qiq_iqi​ for position iii and a key kjk_jkj​ for position jjj as:

score(qi,kj)=qiTkjdk\text{score}(q_i, k_j) = \frac{q_i^T k_j}{\sqrt{d_k}}score(qi​,kj​)=dk​​qiT​kj​​

Where qi=xiWQq_i = x_i W^Qqi​=xi​WQ and kj=xjWKk_j = x_j W^Kkj​=xj​WK, with xi,xjx_i, x_jxi​,xj​ being input embeddings and WQ,WKW^Q, W^KWQ,WK being projection matrices.

Relative positioning schemes inject information about the relationship between iii and jjj directly into this calculation. Several variations exist, but they generally involve adding terms that depend on the relative distance i−ji-ji−j.

Shaw et al. (2018) Formulation

One of the earlier influential approaches proposed adding learned relative position embeddings directly to the keys (and sometimes values) before the dot product. Let aijKa_{ij}^KaijK​ and aijVa_{ij}^VaijV​ represent learnable embedding vectors corresponding to the relative position between query iii and key/value jjj. The attention score calculation is modified as:

eij=(xiWQ)T(xjWK+aijK)dke_{ij} = \frac{(x_i W^Q)^T (x_j W^K + a_{ij}^K)}{\sqrt{d_k}}eij​=dk​​(xi​WQ)T(xj​WK+aijK​)​

The output value ziz_izi​ is then computed using a similar modification for the value vectors:

zi=∑jsoftmax(eij)(xjWV+aijV)z_i = \sum_j \text{softmax}(e_{ij}) (x_j W^V + a_{ij}^V)zi​=j∑​softmax(eij​)(xj​WV+aijV​)

Here, aijKa_{ij}^KaijK​ and aijVa_{ij}^VaijV​ are typically retrieved from embedding lookup tables indexed by the relative distance j−ij-ij−i. To keep the number of embeddings manageable, the relative distance is often clipped to a maximum value kkk. That is, all distances j−i>kj-i > kj−i>k map to the same embedding ai,i+kKa_{i, i+k}^Kai,i+kK​, and distances j−i<−kj-i < -kj−i<−k map to ai,i−kKa_{i, i-k}^Kai,i−kK​.

This approach directly injects relative spatial biases into the attention score. However, it requires computing and storing these relative embeddings for each query-key pair within the attention matrix computation, which can be computationally intensive.

Transformer-XL / Dai et al. (2019) Formulation

A more efficient and widely adopted approach, introduced with Transformer-XL, reformulates the attention calculation to elegantly incorporate relative positions. Recall the standard attention score involving absolute positional embeddings Pi,PjP_i, P_jPi​,Pj​:

Ai,jabs=(Exi+Pi)TWQTWK(Exj+Pj)A_{i,j}^{\text{abs}} = (E_{x_i} + P_i)^T W^{Q T} W^K (E_{x_j} + P_j)Ai,jabs​=(Exi​​+Pi​)TWQTWK(Exj​​+Pj​)

Expanding this gives four terms: content-content (ExiT…ExjE_{x_i}^T \dots E_{x_j}Exi​T​…Exj​​), content-position (ExiT…PjE_{x_i}^T \dots P_jExi​T​…Pj​), position-content (PiT…ExjP_i^T \dots E_{x_j}PiT​…Exj​​), and position-position (PiT…PjP_i^T \dots P_jPiT​…Pj​).

The relative formulation modifies this expansion:

  1. Replace absolute position PjP_jPj​ in the key projection: In terms involving the key's position, replace the absolute position PjP_jPj​ with a relative position encoding Ri−jR_{i-j}Ri−j​ that represents the offset between iii and jjj. RRR can be a fixed sinusoidal encoding matrix (similar to the original Transformer's PE, but used differently) or learned embeddings.
  2. Introduce trainable position biases: Replace the query's absolute position term PiTWQTP_i^T W^{Q T}PiT​WQT with two trainable vectors, uuu and vvv. These vectors represent global "positional biases" for content and relative position, respectively.

This leads to the following decomposed attention score calculation:

Ai,jrel=ExiTWQTWKExj⏟(a) content-based+ExiTWQTWKRi−j⏟(b) content-relative position+uTWKExj⏟(c) global content bias+vTWKRi−j⏟(d) global positional biasA_{i,j}^{\text{rel}} = \underbrace{E_{x_i}^T W^{Q T} W^K E_{x_j}}_{\text{(a) content-based}} + \underbrace{E_{x_i}^T W^{Q T} W^K R_{i-j}}_{\text{(b) content-relative position}} + \underbrace{u^T W^K E_{x_j}}_{\text{(c) global content bias}} + \underbrace{v^T W^K R_{i-j}}_{\text{(d) global positional bias}}Ai,jrel​=(a) content-basedExi​T​WQTWKExj​​​​+(b) content-relative positionExi​T​WQTWKRi−j​​​+(c) global content biasuTWKExj​​​​+(d) global positional biasvTWKRi−j​​​
  • Term (a) is identical to the content interaction in standard attention.
  • Term (b) captures how the query content at iii relates to the relative position i−ji-ji−j.
  • Term (c) provides a bias based purely on the key content at jjj.
  • Term (d) provides a bias based purely on the relative position i−ji-ji−j.

Crucially, this formulation can be implemented efficiently. The terms involving Ri−jR_{i-j}Ri−j​ can be computed without explicitly constructing pairwise relative embeddings for all (i,j)(i, j)(i,j) pairs. Instead, clever tensor manipulations allow computing terms (b) and (d) efficiently across all positions simultaneously.

Implementation Aspects

  • Clipping Distance: As with the Shaw et al. approach, a maximum relative distance kkk is often used when indexing relative position embeddings (Ri−jR_{i-j}Ri−j​). This assumes that very long-range interactions might not need precise distance information.
  • Embedding Type: The relative position representation RRR can be based on sinusoidal functions (providing generalization capabilities) or learned embeddings (potentially more expressive but requiring more data and parameters).
  • Sharing: Relative position embeddings (whether sinusoidal or learned) are often shared across different attention heads and sometimes across layers to reduce the parameter count.

Advantages of Relative Positional Encoding

  • Improved Generalization: RPEs, especially sinusoidal ones or those with clipping, may generalize better to sequence lengths not seen during training compared to learned absolute PEs. The model learns patterns based on distance rather than specific locations.
  • Direct Distance Modeling: The attention mechanism becomes directly aware of the relative positioning between tokens, which can be beneficial for tasks where local syntax or relative order is important.
  • Empirical Success: RPEs form a component of several high-performing models, including Transformer-XL, T5, and DeBERTa, demonstrating their practical effectiveness.

Disadvantages of Relative Positional Encoding

  • Increased Complexity: The attention calculation becomes more involved compared to the baseline Transformer, although efficient implementations like the Transformer-XL formulation mitigate the computational overhead significantly compared to naive approaches.
  • Hyperparameters: Introduces choices like the clipping distance kkk and the type of relative encoding (sinusoidal vs. learned), which may require tuning.

In summary, relative positional encodings offer a compelling alternative to absolute positional encodings by embedding sequence order information directly into the attention mechanism's score calculation. By focusing on pairwise distances rather than absolute locations, they can provide better generalization and capture distance-sensitive relationships more effectively, proving valuable in various modern Transformer architectures.

  • Self-Attention with Relative Position Representations, Peter Shaw, Jakob Uszkoreit, Ashish Vaswani, 2018 Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 2 (Short Papers) (Association for Computational Linguistics) DOI: 10.18653/v1/N18-2074 - This paper introduces one of the earliest explicit formulations for incorporating relative positional information into the self-attention mechanism by adding learned relative position embeddings to keys and values.
  • Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context, Zihang Dai, Zhilin Yang, Yiming Yang, Jaime Carbonell, Quoc Le, Ruslan Salakhutdinov, 2019 Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics (Association for Computational Linguistics) DOI: 10.18653/v1/P19-1285 - This work presents an efficient relative positional encoding scheme that reformulates the attention score calculation to decompose it into content and relative position terms, which helps with better handling of longer sequences.
  • Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer, Colin Raffel, Noam Shazeer, Adam Roberts, Katherine Lee, Sharan Narang, Michael Matena, Yanqi Zhou, Wei Li, Peter J. Liu, 2020 JMLR, Vol. 21 (JMLR) - This paper describes the T5 model, which employs a simplified variant of relative positional encodings, showcasing their effectiveness in large-scale pre-training for various natural language processing tasks.
  • DeBERTa: Decoding-enhanced BERT with Disentangled Attention, Pengcheng He, Xiaodong Liu, Jianfeng Gao, Weizhu Chen, 2021 International Conference on Learning Representations (ICLR) DOI: 10.48550/arXiv.2006.03654 - This research introduces a disentangled attention mechanism that refines relative positional encoding by treating content and relative position embeddings as separate vectors, leading to strong performance in many NLP benchmarks.

© 2026 ApX Machine Learning