Scale RoPE frequencies with NTK-aware interpolation

Why it matters Long-context variants of Llama-family models were extended with this trick before YaRN.

To stretch a RoPE model to a longer context, NTK-aware scaling raises the frequency base instead of squashing positions.

Write rope_freqs_ntk(d, base=10000.0, scale=1.0). The new base is base * scale^(d / (d - 2)). Return the d // 2 inverse frequencies new_base^(-2i / d) for i = 0 .. d/2 - 1.

Signaturedef rope_freqs_ntk(d, base=10000.0, scale=1.0)

Example

rope_freqs_ntk(4, 10000, 1) is [1, 0.01].

Understand the idea

RoPE rotates query and key pairs by angles that grow with position, using one frequency per pair. A model trained on 4k tokens has never seen the large angles of 16k tokens. NTK-aware scaling raises the frequency base so the slowest frequencies slow down by the scale factor, while the fastest ones, which encode local order, stay almost the same. Worked example: d = 4, base 10000, scale 4. The exponent d / (d - 2) is 2, so the new base is 10000 * 4^2 = 160000. Inverse frequencies are new_base^(-2i / d) for i = 0, 1: i = 0 gives 1, and i = 1 gives 160000^(-0.5) = 1 / 400 = 0.0025. The original was 10000^(-0.5) = 0.01, so the slowest frequency dropped by exactly 4, and the fastest stayed at 1. Rule: new_base = base * scale^(d / (d - 2)); return new_base^(-2i / d) for i = 0 .. d/2 - 1. With scale 1 you get standard RoPE. Just multiplying the base by scale under-stretches the low frequencies. Used in: extending Llama style models to longer context without much fine-tuning.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplerope_freqs_ntk(4, 10000, 1)
  • Sample 2: scaledrope_freqs_ntk(8, 10000, 4)
  • Test 3: highest freq unchangedfloat(rope_freqs_ntk(64, 10000, 8)[0])
  • Test 4: lowest freqfloat(rope_freqs_ntk(64, 10000, 8)[-1] / rope_freqs_ntk(64, 10000, 1)[-1])