# Sinusoidal vs Learned vs RoPE Positions

> How sine waves, learned tables and rotary position embeddings (RoPE) tell a transformer word order, and where each one breaks, explained simply for your AI interview.

**In short:** Sinusoidal positions are fixed sine and cosine waves added to each word's vector. Learned positions are a trained table with one row per slot, so they stop at the table's size. Rotary (RoPE) turns the query and key vectors by position, so the score depends on the gap between two words and their content.

AI and LLM interview question Q048, Transformer architecture. Advanced, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/sinusoidal-vs-learned-vs-rotary-rope-positions

## Say it in 30 seconds

There are three common ways to give a transformer word order. Sinusoidal uses fixed sine and cosine waves, so nothing is learned. Learned uses a trained table with one row per position, so it stops at the largest position it was trained on. Rotary, or RoPE, turns the query and key vectors by their position, so the score depends on the gap between two words and their content. Meta's Llama models use RoPE. I'd test any method on the longest documents the product will see.

## Say it in 2 minutes

A transformer reads all the words of a sentence at once, so it has no built-in sense of order. Something has to tell it where each word sits. That something is positional encoding, and three designs come up in interviews: sinusoidal, learned, and rotary, which is RoPE.

Sinusoidal positions appear in the 2017 Transformer paper. Each slot gets a pattern of sine and cosine waves, added to the word's vector, and nothing in it is trained. The authors also tried learned positions and found nearly identical results. They hoped the sine waves might let the model handle inputs longer than the ones it saw in training.

Learned positions keep one trained row per slot, up to a maximum, so the model fits its own pattern. The catch is the limit: a slot past the end of the table has no row. RoPE adds nothing to the word. It turns the query and key vectors inside attention by an angle set by position, so the score depends on the gap between two words and their content. Meta's Llama papers use it.

For the interview, name the trade-off: a fixed formula, a trained table that caps at its size, or a rotation that depends on the gap. Then say you would test any method on the longest real documents before you trust it.

## What are the three ways, in plain words?

A transformer reads every word in a sentence at the same time. It needs an extra signal to know which word is first, which is second, and so on. Each word is turned into a vector, a short list of numbers that stands for its meaning. The attention step is where each word looks at the others to decide what matters. The three designs differ in where the position signal comes from and how it reaches that step.

Picture a loan team numbering the pages of a 400-page credit file. They can use a formula that prints page numbers from a rule. They can use a stamp book with one stamp per page, filled in once and kept. Or they can write each cross-reference as 'two clauses back', which only needs the distance between clauses. All three tell a reader where things sit, and each has a different cost.

- **Position:** Where a word sits in the input: first, second, tenth.
- **Sinusoidal:** Fixed sine and cosine waves, one pattern per position. Nothing is trained.
- **Learned table:** A trained list of vectors, one row for each position up to a set maximum.
- **RoPE:** Rotary position embedding. It turns the query and key vectors (the two sides of an attention match) by an angle set by position.

## How does each one give a word its position?

The 2017 Transformer paper uses fixed sine and cosine waves. Each slot gets a list of sine and cosine values, each pair at its own speed. Those values are added to the word's vector before attention runs. The authors hoped the design would make it easy for the model to attend by relative positions.

The paper says there are many choices of positional encodings, learned and fixed. Its own test is the key comparison. It also tried learned positions on its English-to-German translation test, and the two gave nearly identical results. So the choice came down to the other property: the sine waves might keep working on inputs longer than training.

> "We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training." (Vaswani et al., 2017, Attention Is All You Need)

Learned positions are simpler to explain. Training gives each slot its own row, and the model adjusts those rows like any other weight. BERT is the usual example. Its input adds together the token, segment and position vectors. Most of its pre-training ran on 128-token sequences. Only the last 10% of its steps used 512 tokens, to learn the position rows.

*Diagram, Two ways to build a position vector: Both methods start from the same slot number and end with a vector for that slot. The sine path computes the vector, and the table path looks up a trained row. Either way, the vector is then added to the word.*
1. The slot number goes to the sine and cosine waves.
2. Or the same slot number goes to the learned table.
3. The waves compute a fixed vector for that slot.
4. The table gives its trained row. Either way, the vector is then added to the word.

The weak point of the table is simple. If training only reached slot 511, slot 600 has no row. A table can only give a trained vector to a slot it has seen.

## How does RoPE work, and which models use it?

RoPE skips the adding step. It turns the query and key vectors inside attention, so each one is rotated by an angle that depends on its position. When a query meets a key, the rotations leave only the gap between their positions, if the two word vectors are the same. So a query at slot 5 and a key at slot 2 score the same as a query at slot 105 and a key at slot 102, because both gaps are 3. With different word vectors, the word meanings change the score too.

*Diagram, RoPE: same vectors, the gap decides: Each side turns by its own position angle. With the same query and key vectors, multiplying the matching numbers and adding them keeps only the gap, so a gap of 3 scores the same wherever it sits in the text.*
1. The query turns by the angle its slot sets.
2. The key turns by its own angle, from its slot.
3. Multiply matching numbers and add them up. With equal vectors, only the gap is left: 5 minus 2 is 3.

RoFormer, submitted in April 2021, named the method and listed its properties. Its abstract says RoPE puts the explicit relative position into attention, and that the link between two tokens fades as the distance between them grows.

> "the proposed RoPE encodes the absolute position with a rotation matrix and meanwhile incorporates the explicit relative position dependency in self-attention formulation" (Su et al., 2021, RoFormer)
>
> "We remove the absolute positional embeddings, and instead, add rotary positional embeddings (RoPE), introduced by Su et al. (2021), at each layer of the network." (Meta, LLaMA paper)

Meta's Llama papers use it. Llama 1 removed the absolute position embeddings and put RoPE into every layer. For Llama 3, Meta raised the RoPE base frequency, a setting that controls how the angles spread. Meta says this helps it support longer contexts.

Here are all three in plain Python, for the made-up contract assistant. The learned table stops at slot 511, while the sine waves and the rotation work for any slot. The two RoPE scores match because the gap is the same, for these same query and key vectors.

```python
import math

# Sine and cosine waves: a fixed pattern per slot, nothing to train.
def sinusoidal(pos, d=4):
    vec = []
    for i in range(d // 2):
        angle = pos / (10000 ** (2 * i / d))
        vec += [round(math.sin(angle), 3), round(math.cos(angle), 3)]
    return vec

# Learned: a trained row per slot. The contract assistant's table has 512 rows, so slot 600 has none.
TABLE = {slot: [0.0] * 4 for slot in range(512)}

# RoPE: turn the query and key by angles set by their positions.
def rotate(vec, pos, step=0.5):
    x, y = vec
    a = pos * step
    return (x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a))
def score(q, k):
    return round(q[0] * k[0] + q[1] * k[1], 3)

print("sinusoidal, slot 0:", sinusoidal(0))
print("sinusoidal, slot 1:", sinusoidal(1))
try:
    TABLE[600]
except KeyError:
    print("learned, slot 600: no trained row")
q, k = (1.0, 0.0), (0.6, 0.8)  # made-up query and key vectors
for m, n in [(5, 2), (105, 102)]:
    print(f"RoPE, positions {m} and {n}, gap {m - n}: score {score(rotate(q, m), rotate(k, n))}")
```

Output:

```text
sinusoidal, slot 0: [0.0, 1.0, 0.0, 1.0]
sinusoidal, slot 1: [0.841, 0.54, 0.01, 1.0]
learned, slot 600: no trained row
RoPE, positions 5 and 2, gap 3: score 0.84
RoPE, positions 105 and 102, gap 3: score 0.84
```

## Which one should you pick, and where does each break?

- **Sinusoidal: Fixed, nothing to train.** No parameters to learn, and the 2017 authors hoped it would reach past the training length. A hope, not a promise, so test it.
- **Learned: Fits the data, stops at the table.** Nearly identical to sinusoidal on the paper's test. Slots past the trained table have no vector at all.
- **RoPE: Relative by design.** Scores depend on the gap between tokens, and on their content. Meta's Llama models use it. Going past the training length still needs a test.

Worked example: a legal team's contract assistant. The team's made-up model was trained on inputs up to 512 tokens, with a learned table of 512 rows. A supplier contract runs to 900 tokens. The termination clause sits near token 120, and the liability cap sits near token 860. Rows 512 and up do not exist, so the model has no trained vector for the cap. Three fixes are on the table.

1. **Retrain with longer inputs:** Costly, and it needs enough long documents to train on.
2. **Switch the position method:** A new model with RoPE or sinusoidal positions, tested on real contracts.
3. **Split the contract into chunks:** Cheap, but a clause that falls across two chunks gets cut. Overlap the chunks and test the edges.

The first two fixes change the model. The third changes the pipeline. A good interview answer names the cost of each and says which test would show it works.

### How would you choose a method for a long-document product?

1. **Start with the method your model uses:** Changing it means training again, so the choice is often made for you.
2. **Build a test from your longest documents:** Put the answer near the start, the middle and the end of each one.
3. **Score by length band:** Find where the answers start to fail as the input grows.
4. **Match the drop to the trained length:** If the drop lines up with the length the model was trained on, plan a retrain or another model, and say so.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Why position is needed: transformers read all tokens at once.
- [ ] Sinusoidal: fixed waves from 2017, nothing trained.
- [ ] Learned: a trained row per slot, so it stops at the table's size.
- [ ] RoPE: rotates queries and keys, so the score depends on the gap and the content.
- [ ] Meta's Llama papers use RoPE, so name the model family when you cite it.
- [ ] Test on your longest documents before trusting any method.

**Common traps**

- Trap: "Learned is always better, since the model fits its own data." Better: On the 2017 test it was nearly identical. Its catch is the table's size, not its quality.
- Trap: "RoPE just adds a position vector like the old way." Better: It turns the query and key inside attention, so the score reflects the gap between two words, plus their content.
- Trap: "Sine waves mean any length works." Better: The 2017 authors only hoped for it. Test the length you need before you promise it.

## Can you spot the problem?

**Spot the problem:** A contract assistant fails on long clauses. Which line of this made-up setup is the cause?

A. pos_table = learned(512, 768)  # one trained row for each slot, 0 to 511
B. angles = slot / freq  # sine and cosine, computed for any slot
C. q, k = rotate(q, pos_q), rotate(k, pos_k)  # RoPE, any slot
D. word_vec = embed[word_id]  # the word's meaning, from a word table

**Answer:** A. A learned table has a trained row only up to its size, so slot 512 and up have no vector. The sine and RoPE lines compute values for any slot, and the word table holds word meanings, not positions.

**Quick check:** A made-up assistant reads 900-token contracts, but its position table has only 512 rows. What is the real problem?

A. Its word meanings are stored in too few numbers
B. Slots 512 and up have no trained row to use
C. The temperature setting is too high
D. The attention step can only read a short list of words

**Answer:** B. A table only holds what training gave it. Slots past its end have nothing to look up. The fix is a method or a retrain that covers the length, then a test on real contracts.

## Can you answer these from memory?

**Flash cards**

- **Why does a transformer need position?** It reads all tokens at once, so without a position signal, word order is lost.
- **Sinusoidal in one line?** Fixed sine and cosine waves per slot. Nothing is trained.
- **Learned positions in one line?** A trained row for each slot, so slots past the table's size have no row.
- **What does RoPE do?** Rotates query and key vectors by position, so the score depends on the gap and the content.
- **Which Meta models use RoPE?** Llama 1 and Llama 3, per Meta's papers.
- **Which method wins on length?** No single winner. Test the length you need on real documents.

## Likely follow-up questions

- Q047 What is positional encoding, and why is it needed? https://designervenkat.online/interview/ai/what-is-positional-encoding
- Q046 What is multi-head attention? https://designervenkat.online/interview/ai/what-is-multi-head-attention
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q049 Encoder-only vs decoder-only vs encoder-decoder? https://designervenkat.online/interview/ai/encoder-only-vs-decoder-only-vs-encoder-decoder
- Q045 Why scale attention scores by √d_k? https://designervenkat.online/interview/ai/why-scale-attention-scores-by-square-root-of-d-k
