Position Interpolation › A Complete Implementation

Michael BrenndoerferUpdated July 6, 20254 min read
Language AI HandbookAll chapters
Part 18 of 67Long Context
Chapter 127Position Interpolation › A Complete Implementation
Reading section 8 of 12 · A Complete Implementation · 4 minSection 8 of 12 · 4 min

Book contents

Section 8 of 12 · 4 min read

Position Interpolation › A Complete ImplementationOne section · Sections in this chapter8 / 12 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

Let's put everything together into a complete Position Interpolation implementation that can be applied to RoPE. The class below combines all the pieces we've developed: scale factor computation, position scaling, frequency precomputation, and rotation matrix construction. Understanding this implementation end-to-end is valuable because production implementations in frameworks like Hugging Face Transformers follow exactly the same logic, just with additional optimizations for batched computation on GPU hardware.

In[17]:
Code
class RoPEWithPositionInterpolation:
    """RoPE implementation with Position Interpolation support."""

    def __init__(
        self, d_model, base=10000, train_length=2048, target_length=None
    ):
        """Initialize RoPE with optional Position Interpolation.

        Args:
            d_model: Embedding dimension (must be even)
            base: Base for frequency computation
            train_length: Maximum position seen during training
            target_length: Extended context length (None = no interpolation)
        """
        if d_model % 2 != 0:
            raise ValueError("d_model must be even for RoPE")

        self.d_model = d_model
        self.base = base
        self.train_length = train_length

        # Compute scale factor for Position Interpolation
        if target_length is not None and target_length > train_length:
            self.scale = train_length / target_length
        else:
            self.scale = 1.0

        # Precompute frequencies
        dim_pairs = d_model // 2
        i = np.arange(dim_pairs)
        self.theta = 1.0 / (base ** (2 * i / d_model))

    def get_rotation_matrix(self, position):
        """Get the block-diagonal rotation matrix for a position.

        Args:
            position: Integer position index

        Returns:
            R: Rotation matrix of shape (d_model, d_model)
        """
        # Apply position scaling
        scaled_pos = position * self.scale

        # Compute angles for each dimension pair
        angles = scaled_pos * self.theta

        # Build block-diagonal rotation matrix
        R = np.zeros((self.d_model, self.d_model))
        for i, angle in enumerate(angles):
            cos_a, sin_a = np.cos(angle), np.sin(angle)
            idx = 2 * i
            R[idx, idx] = cos_a
            R[idx, idx + 1] = -sin_a
            R[idx + 1, idx] = sin_a
            R[idx + 1, idx + 1] = cos_a

        return R

    def apply(self, x, positions):
        """Apply RoPE to input vectors.

        Args:
            x: Input array of shape (seq_len, d_model)
            positions: Position indices for each element

        Returns:
            rotated: Rotated vectors of shape (seq_len, d_model)
        """
        seq_len = x.shape[0]
        rotated = np.zeros_like(x)

        for i, pos in enumerate(positions):
            R = self.get_rotation_matrix(pos)
            rotated[i] = R @ x[i]

        return rotated

The implementation's most important property is that it falls back to standard RoPE when no target length is specified or when the target length is within the training limit. This makes it a drop-in replacement that adds zero overhead for standard use cases.

Let's verify that our implementation produces the expected behavior.

In[18]:
Code
# Create instances with and without interpolation
rope_standard = RoPEWithPositionInterpolation(d_model=64, train_length=2048)

rope_interpolated = RoPEWithPositionInterpolation(
    d_model=64, train_length=2048, target_length=8192
)

# Test on a sample vector at an extended position. The hidden setup cell seeds
# the chapter once so all render variants stay deterministic.
test_vector = np.random.randn(64)
test_position = 6000  # Beyond training range

# Get rotation matrices
R_standard = rope_standard.get_rotation_matrix(test_position)
R_interpolated = rope_interpolated.get_rotation_matrix(test_position)
R_training_equiv = rope_standard.get_rotation_matrix(test_position * 0.25)
Out[19]:
Console
Testing at position 6000 (training limit: 2048)
Interpolation scale factor: 0.25

Rotation matrix diagonal (cos of angles) for first 5 dimension pairs:
----------------------------------------------------------------------
Pair     Standard           Interpolated       Training Equiv    
----------------------------------------------------------------------
0        0.903912           -0.110267          -0.110267         
1        0.822743           0.988599           0.988599          
2        0.999746           0.005640           0.005640          
3        -0.365213          -0.467238          -0.467238         
4        0.987955           -0.999246          -0.999246         

Note: 'Interpolated' and 'Training Equiv' columns should match,
since position 6000 × 0.25 = 1500.0

The interpolated rotation matrix at position 6,000 matches the standard rotation matrix at position 1,500, confirming that our implementation correctly maps extended positions back to the training range.

The "Training Equiv" column in the output is computed by scaling position 6,000 by 0.25 to get 1,500, then applying standard RoPE. The "Interpolated" column applies Position Interpolation directly. They should be identical up to floating-point precision. This equivalence provides a sanity check and the mathematical guarantee that Position Interpolation delivers: every position in the extended sequence is handled exactly as if it were a proportionally smaller position in the original system.