KatInterview

Add Positional Encoding to a Transformer Language Model

Machine LearningModel answer
MediumModel answerMachine Learningtransformerspositional-encodingpytorch

Last updated

Implement sinusoidal or learned positional encodings in PyTorch, explain the math and tensor shapes, integrate them into a Transformer LM, and diagnose what breaks without them.

Background

A Transformer's self-attention mechanism computes weighted combinations of value vectors using query-key dot products. Nothing in that computation references the order of the input tokens — if you shuffle the sequence, the output is shuffled the same way. For any language task where word order carries meaning, this is a serious problem.

Positional encodings solve it by injecting an order-aware signal into the token embeddings before they enter the attention layers.

Your Task

Part 1 — Implementation

Implement a SinusoidalPositionalEncoding module in PyTorch. Your implementation should:

  • Accept a tensor of shape (B, T, d_model) (batch-first) and return a tensor of the same shape.
  • Correctly apply the sinusoidal formulas for even and odd embedding dimensions.
  • Use a non-trainable buffer so the table moves with the model across devices but is not updated by the optimizer.
  • Support an offset argument for incremental (KV-cached) decoding.

Also sketch a LearnedPositionalEncoding alternative using nn.Embedding, and note how it differs.

Part 2 — Integration

Show how to wire the positional encoding into a small Transformer language model class. Highlight where in the forward pass it sits, how token embedding scaling interacts with it, and the weight-tying pattern between the embedding table and the output projection.

Part 3 — Diagnosis and Verification

Suppose a colleague removes positional encodings from a trained model. Describe:

  • What observable symptoms would appear at inference time, separately for a bidirectional encoder and a causal decoder.
  • How you would verify empirically that adding positional encodings back fixes the issue — go beyond "loss went down."

What You Are Expected to Cover

  • The sinusoidal equations and the intuition behind them (frequency spectrum, relative-offset linearity).
  • Tensor shapes at each step and how broadcasting works.
  • The register_buffer vs nn.Parameter distinction.
  • The KV-cache offset bug.
  • A brief comparison of sinusoidal, learned absolute, and modern relative schemes (RoPE / ALiBi) with trade-offs.
  • Concrete, measurable verification strategies.

Hints

Hint 1

Self-attention is permutation-equivariant: write out the attention formula applied to PX (a permuted input) to see exactly why position information cannot emerge from the weights alone.

Hint 2

For the sinusoidal formula, think about what the wavelengths look like across dimension indices. Low-index dimensions oscillate fast; high-index dimensions oscillate slowly — similar to how binary digits change at different rates. Also ask yourself: what property of sin and cos makes relative positions easy to represent?

Hint 3

The KV-cache offset bug is subtle: when decoding token t given a cache of t-1 tokens, the new token must receive positional encoding for index t-1, not index 0. Trace through the forward method with offset=0 vs offset=t-1 to see why the distinction matters.