GNGiseldo Neo and Alana NeoBooks
Language Models with Python5 / 16

Vector Representation: Embeddings and Positional Encoding

In Natural Language Processing (NLP) models based on deep learning, specifically in the Transformer architecture, raw data (text) cannot be processed directly. The first critical step is the transformation of discrete tokens (integer indices from a vocabulary) into continuous, dense vector representations enriched with information about the order of the sequence.

This chapter details the architecture of the input layer, composed of two main subcomponents: Input Embeddings and Positional Encoding.

5.1 Input Embeddings (the Embedding Layer)

The embedding layer acts as a learnable lookup table. Whereas one-hot encoding produces sparse, extremely high-dimensional vectors (the size of the vocabulary), embeddings project these tokens into a dense vector space of lower dimension (dmodeld_{model}), where geometric proximity reflects semantic similarity.

5.1.1 Technical Characteristics

  • Mapping: Each token ID xx is mapped to a vector v∈Rdmodelv \in \mathbb{R}^{d_{model}}.
  • Dimensionality (dmodeld_{model}): An architecture hyperparameter (e.g., 512 in the original Transformer, 4096 in GPT-3).
  • Variance scaling: In the original paper “Attention Is All You Need”, the embedding weights are multiplied by dmodel\sqrt{d_{model}}. This is done to counterbalance the magnitude of the dot product in the subsequent attention layer, helping the stability of gradients during training.

5.2 Positional Encoding

Unlike Recurrent Neural Networks (RNNs) or LSTMs, the Transformer architecture does not process data sequentially; it processes the entire sequence in parallel. Consequently, the self-attention mechanism is permutation invariant. Without an explicit injection of position, the model would see the sentences “The dog bit the man” and “The man bit the dog” as identical in terms of token composition.

To solve this, we inject a Positional Encoding (PE) vector by adding it to the embedding vector.

5.2.1 Mathematical Implementation

Positional encoding uses sine and cosine waves of different wavelengths. For a position pospos in the sequence and a dimension ii within the embedding vector:

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

Why this formula?

  1. Deterministic values: It requires no extra learnable parameters (although learnable positional embeddings are also used in modern models such as BERT).
  2. Linear relativity: For any fixed offset kk, PEpos+kPE_{pos+k} can be represented as a linear function of PEposPE_{pos}. This makes it easier for the model to learn to attend to relative positions (e.g., the previous or the next token).
  3. Extrapolation: It allows the model to process sequences longer than those seen during training.

5.3 Data Flow Architecture

The combination of these two layers produces the final input to the Transformer blocks. The operation is an element-wise addition, usually followed by a Dropout layer for regularization.

5.3.1 Flow Diagram

Diagram

5.4 Reference Implementation (PyTorch)

Below we present a robust, annotated implementation following industry-standard specifications.

import torch
import torch.nn as nn
import math

class InputEmbeddings(nn.Module):
    def __init__(self, d_model: int, vocab_size: int):
        """
        Args:
            d_model (int): Dimension of the embedding vector.
            vocab_size (int): Vocabulary size.
        """
        super().__init__()
        self.d_model = d_model
        self.vocab_size = vocab_size
        # Standard PyTorch embedding layer
        self.embedding = nn.Embedding(vocab_size, d_model)

    def forward(self, x):
        # Scaling by sqrt(d_model) as in the original paper
        return self.embedding(x) * math.sqrt(self.d_model)

class PositionalEncoding(nn.Module):
    def __init__(self, d_model: int, seq_len: int, dropout: float):
        """
        Args:
            d_model (int): Model dimension.
            seq_len (int): Maximum sequence length.
            dropout (float): Dropout rate.
        """
        super().__init__()
        self.dropout = nn.Dropout(dropout)

        # Creates a (seq_len, d_model) matrix of zeros
        pe = torch.zeros(seq_len, d_model)

        # Creates a vector of positions (0, 1, ... seq_len-1)
        # Shape: (seq_len, 1)
        position = torch.arange(0, seq_len, dtype=torch.float).unsqueeze(1)

        # Divisor term for the frequencies (10000^(2i/d_model))
        # Implemented in log-space for numerical stability
        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))

        # Applies sine to the even indices (2i)
        pe[:, 0::2] = torch.sin(position * div_term)

        # Applies cosine to the odd indices (2i+1)
        pe[:, 1::2] = torch.cos(position * div_term)

        # Adds a batch dimension to ease broadcasting in the sum: (1, seq_len, d_model)
        pe = pe.unsqueeze(0)

        # Registers as a buffer (not a learnable parameter, but part of the model state)
        self.register_buffer('pe', pe)

    def forward(self, x):
        """
        Args:
            x: Input embeddings. Shape: (Batch_Size, Seq_Len, d_model)
        """
        # Adds the embedding to the positional encoding (up to the current sequence length)
        # x.requires_grad_(False) is not needed since pe is a buffer, but the sum keeps x's gradient
        x = x + self.pe[:, :x.shape[1], :]
        return self.dropout(x)

# Integrated usage example
class TransformerInputLayer(nn.Module):
    def __init__(self, vocab_size, d_model, max_len, dropout=0.1):
        super().__init__()
        self.embeddings = InputEmbeddings(d_model, vocab_size)
        self.positional_encoding = PositionalEncoding(d_model, max_len, dropout)

    def forward(self, x):
        x = self.embeddings(x)
        x = self.positional_encoding(x)
        return x

5.4.1 Code Analysis

  1. Numerical stability: In computing div_term, we use torch.exp and math.log. Mathematically, eln⁡(x)=xe^{\ln(x)} = x. This avoids direct powers of very large or very small numbers, preserving floating-point precision.
  2. Buffers: Using register_buffer ensures that the Positional Encoding matrix is saved along with the model (state_dict) but is not updated by the optimizer (backpropagation), since it is fixed.
  3. Broadcasting: The shape of the pe tensor is (1, seq_len, d_model). This lets it be added automatically to a batch of inputs (Batch, seq_len, d_model) without duplicating memory.

5.5 An Embedding Is Not Meaning in Isolation

The row of the embedding table provides only a token’s starting point. After each block, its representation becomes contextual. Thus, occurrences of “bank” in “bank account” and “river bank” start with the same vector but end with different hidden states because of the neighboring tokens.

If the IDs have shape (B,T)(B,T), nn.Embedding produces (B,T,dmodel)(B,T,d_{model}). The positional encoding must be compatible with the last two dimensions; the sum does not concatenate position and content, so the shape remains unchanged. This is a good place to use assert x.shape == (B,T,d_model) during implementation.

Besides sinusoids, current models may use learned positions, RoPE, or relative biases. The criterion is not only to represent order: it is also to generalize to different lengths and to let attention express relevant distances.

Exercise

Swap two tokens in a sequence and compare the sum embedding + position. Then remove the positional encoding and explain why self-attention no longer distinguishes the two orders.

5.6 Relative Positions with RoPE

Absolute positional embeddings add a vector that represents the index. Rotary positional encoding, known as RoPE, follows a different idea: pairs of coordinates of queries and keys are rotated by angles that depend on the position. Since the dot product between rotated vectors depends on the difference between the angles, attention receives information about relative distance.

For a pair (x2i,x2i+1)(x_{2i},x_{2i+1}) and an angle θ\theta, the rotation is

[x2i′x2i+1′]=[cos⁡θ−sin⁡θsin⁡θcos⁡θ][x2ix2i+1].\begin{bmatrix} x'_{2i}\\x'_{2i+1} \end{bmatrix} = \begin{bmatrix} \cos\theta & -\sin\theta\\ \sin\theta & \cos\theta \end{bmatrix} \begin{bmatrix} x_{2i}\\x_{2i+1} \end{bmatrix}.

Different frequencies are used across the dimensions: some vary quickly and distinguish nearby positions; others vary slowly and preserve relationships at larger scales. The rotation is applied to QQ and KK, not necessarily to VV, because its purpose is to alter the compatibility computation.

RoPE does not make the context unlimited. Lengths far beyond those observed in training can produce unfamiliar angular patterns. Scaling techniques adjust frequencies or positions, but they must be evaluated for information retrieval, stability, and loss of local resolution.

Content and position remain conceptually separate

The embedding represents the token; the positional transformation modifies how tokens in different places relate to one another. Although they are combined in the computation, these functions help debug the model separately.

5.7 Visualizing Embeddings with Care

PCA, t-SNE, and UMAP project high-dimensional vectors into two or three dimensions. These figures help formulate hypotheses about clusters, but they inevitably distort relationships. t-SNE emphasizes local neighborhoods; UMAP tries to preserve more global structure; PCA is linear and easier to interpret. No two-dimensional plot, by itself, proves that the model has learned a concept.