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

Sinusoidal Positional Encoding: Formulation

The self-attention mechanism operates on input elements without an inherent understanding of their order in the sequence. This permutation invariance is powerful for capturing relationships regardless of distance but fails to model the sequential nature essential for language and other ordered data. To address this, the Transformer architecture introduces positional encodings, which are vectors added to the input embeddings to provide the model with information about the position of each token.

The original Transformer paper ("Attention Is All You Need") proposed a fixed, non-learned method using sine and cosine functions of different frequencies. This approach, known as sinusoidal positional encoding, generates a unique encoding vector for each position in the sequence up to a predefined maximum length.

Mathematical Formulation

For a given position pospospos in the sequence (where pos=0,1,2,...pos = 0, 1, 2, ...pos=0,1,2,...) and a given dimension iii within the dmodeld_{model}dmodel​-dimensional embedding vector (where i=0,1,...,dmodel−1i = 0, 1, ..., d_{model}-1i=0,1,...,dmodel​−1), the positional encoding PEPEPE is defined by applying sine functions to the even dimension indices (2i2i2i) and cosine functions to the odd dimension indices (2i+12i+12i+1):

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

Here:

  • pospospos represents the index of the token's position in the input sequence.
  • iii represents the index of the dimension within the encoding vector. Note that iii here effectively ranges from 000 up to dmodel/2−1d_{model}/2 - 1dmodel​/2−1, as each iii defines a pair of dimensions (2i2i2i and 2i+12i+12i+1).
  • dmodeld_{model}dmodel​ is the dimensionality of the embedding vectors used throughout the Transformer model (e.g., 512, 768).

The term 1/100002i/dmodel1 / 10000^{2i/d_{model}}1/100002i/dmodel​ determines the angular frequency of the sine and cosine waves. Let's analyze its behavior:

  • When iii is small (representing the initial dimensions of the encoding vector), the exponent 2i/dmodel2i/d_{model}2i/dmodel​ is close to 0. The base 100002i/dmodel10000^{2i/d_{model}}100002i/dmodel​ is close to 100000=110000^0 = 1100000=1. This results in a relatively large argument pos/1pos/1pos/1, meaning the sine/cosine functions oscillate with a high frequency (short wavelength) across positions for these dimensions.
  • As iii increases towards dmodel/2d_{model}/2dmodel​/2, the exponent 2i/dmodel2i/d_{model}2i/dmodel​ approaches 1. The base 100002i/dmodel10000^{2i/d_{model}}100002i/dmodel​ approaches 100001=1000010000^1 = 10000100001=10000. This results in a smaller argument pos/10000pos/10000pos/10000, meaning the functions oscillate with a very low frequency (long wavelength) across positions for these later dimensions.

This design creates positional encoding vectors where each dimension corresponds to a sinusoid of a specific frequency. The combination of these sinusoids across all dimensions generates a unique signature for each position pospospos.

Heatmap showing the sinusoidal positional encoding values for the first 50 positions (sampled every 2 positions) across the first 128 dimensions (sampled every 4 dimensions). Each row represents a dimension index, and each column represents a position in the sequence. The color intensity indicates the value of the encoding (ranging from -1 to 1). Notice the different frequencies of oscillation along the dimension axis (y-axis).

An important property derived from these trigonometric identities is that the encoding for a position pos+kpos + kpos+k can be represented as a linear transformation of the encoding for position pospospos. This linearity property might help the model easily learn to attend based on relative positions, as the relationship between the encodings of tokens separated by a fixed distance kkk remains consistent regardless of their absolute positions.

In summary, the sinusoidal positional encoding provides a deterministic and computationally efficient way to inject sequence order information into the Transformer. It generates unique positional signatures and possesses properties beneficial for modeling relative positions, without requiring additional learnable parameters.

  • Attention Is All You Need, Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017 Advances in Neural Information Processing Systems (NIPS 2017) DOI: 10.48550/arXiv.1706.03762 - The foundational paper introducing the Transformer architecture and the original sinusoidal positional encoding.
  • Speech and Language Processing (3rd ed. draft), Daniel Jurafsky and James H. Martin, 2025 (Stanford University) - Provides an accessible yet comprehensive explanation of the Transformer architecture and positional encodings in its dedicated chapter.

© 2026 ApX Machine Learning