Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

How models handle long inputs: keeping positions within the range seen in training (RoPE scaling), sliding windows, and cutting KV-cache memory with GQA, paging, quantization and compression.

Advanced · Graduate mathematics · about 22 minutes

Reading map and next steps

What limits a longer context?

Storage, visibility and position are different questions. Choose one to inspect; each view states what it leaves untested.

Start with eight tokens → A separate worked example, in single-token units. The demos below also cover grouped key–value heads and larger memory settings.

Intuition

The idea in plain words, before the symbols.

Running a model on a long input raises two separate problems: the model must handle token positions it never saw in training, and it must store and read the keys and values of every earlier token. We compare the techniques that address each. The code counts KV-cache bytes and the attention work a sliding window saves. Fitting a longer context does not show that the model can find and use the evidence it contains.

The two problems are:

  1. Position extrapolation: the model must make sense of token positions it never saw during training, so their positions are out of distribution.
  2. Memory and bandwidth: even if the model could use a million tokens, the KV cache for all of them still has to be stored and read.

The two problems have separate remedies. RoPE scaling methods (position interpolation, YaRN, LongRoPE) keep the rotation angles of distant positions inside the range seen in training. KV-cache techniques (GQA/MQA, paging, quantization, eviction) reduce how many bytes must be stored and read per token.

A third question sits on top of both: does the model find and use the evidence it needs? A cache that fits and positions that are familiar do not answer it. Retrieving one planted fact is the easiest case; harder tests move the evidence around, add distractors and need several facts at once (Hsieh et al., 2024; Liu et al., 2024).

Which resource runs out depends on the phase. Processing a long prompt (prefill) handles all its tokens in parallel and is usually limited by arithmetic. Generating the answer (decode) produces one token per step, and each step must read the model's weights and the whole KV cache from memory, so at small batch sizes it is limited by memory bandwidth, and the longer the context, the more of that traffic is cache (Pope et al., 2023, §2).

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Sliding window attention (reduce T2T^2 compute)

If each token attends only to itself and the W−1W-1 tokens before it, a window of WW keys (Beltagy et al., 2020), then attention compute is closer to O(TW)O(TW) instead of O(T2)O(T^2). One way to express this is with a mask:

Mij={0if 0≤i−j<W−∞otherwiseM_{ij} = \begin{cases} 0 & \text{if } 0 \le i-j < W \\\\ -\infty & \text{otherwise} \end{cases}

and:

Attn(Q,K,V)=softmax ⁣(QK⊤dk+M)V.\mathrm{Attn}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V.

KV cache memory (the bottleneck at long TT)

Across a batch of BB sequences and LL layers, storing keys and values for TT tokens costs roughly:

MemKV≈B⋅L⋅T⋅Hkv⋅dhead⋅2⋅bytes.\mathrm{Mem}_{KV} \approx B\cdot L\cdot T\cdot H_{kv}\cdot d_{\mathrm{head}}\cdot 2 \cdot \mathrm{bytes}.

Here HkvH_{kv} is the number of key/value heads per layer and dheadd_{\mathrm{head}} their width. This grows linearly in TT. At long context and large batch it can exceed the memory taken by the model's weights: with the settings in the code below (80 layers, 8 KV heads of width 128, batch 8, 2 bytes per value), it reaches about 344 GB at 131,072 tokens.

Three claims about one request

"Supports 131,072 tokens" can mean three things, and each needs its own evidence.

  1. The cache fits. For one request (B=1B=1) with Nlayers=32N_{\mathrm{layers}}=32, T=131,072T=131{,}072, Hkv=8H_{kv}=8, dhead=128d_{\mathrm{head}}=128 and 2 bytes per value, the formula gives 1⋅32⋅131,072⋅8⋅128⋅2⋅2=2341\cdot32\cdot131{,}072\cdot8\cdot128\cdot2\cdot2=2^{34} bytes, exactly 16 GiB or about 17.18 GB. Halving HkvH_{kv} to 4 halves it. That compares two architectures; whether the narrower one keeps its quality is measured separately (Ainslie et al., 2023). A server allocates more than this ideal count (paging metadata, padding, other tensors), and a measured fit holds for that request, model and implementation.
  2. Positions past the training length still work. This needs the same model evaluated beyond its training length, with and without a position method such as interpolation, on the same tasks. A smaller cache says nothing about it.
  3. The model finds and uses what it needs. This needs behaviour tests. RULER (Hsieh et al., 2024) adds several planted facts, tracing and aggregation to the single-fact test, and finds that models scoring almost perfectly on that test still lose much of their accuracy as inputs grow. Liu et al. (2024) find that accuracy is often highest when the relevant passage is near the start or end of the input and drops when it is in the middle.

These are not the only constraints; prefill compute, decode bandwidth and scheduling sit beside them. The practice section works the first claim exactly and matches the other two to their evidence.

RoPE scaling (positions beyond the training range)

RoPE encodes position by rotating queries and keys. At positions far beyond training, those rotations reach angles the model never saw, especially in the slowly rotating (low-frequency) pairs, which never completed a full turn during training. RoPE scaling methods change the map from position mm to angle θ(m)\theta(m) so that long inputs produce familiar angles while short-range detail is preserved. Position interpolation (Chen et al., 2023) replaces mm by m Ttrain/Tnewm\,T_{\mathrm{train}}/T_{\mathrm{new}} for every pair, where TtrainT_{\mathrm{train}} is the training context length and TnewT_{\mathrm{new}} the extended one; YaRN (Peng et al., 2024) rescales the slow pairs more than the fast ones.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

import numpy as np

def kv_gb(T, L, Hkv, d_head, B=1, bytes_per_elem=2):
    elems = B * L * T * Hkv * d_head * 2  # K and V
    return elems * bytes_per_elem / 1e9

L, Hkv, d_head, B = 80, 8, 128, 8  # example: 80 layers, GQA with 8 KV heads, fp16
for T in [2048, 8192, 32768, 131072]:
    print("T=", T, "KV~", round(kv_gb(T, L, Hkv, d_head, B), 2), "GB")

def attn_work(T, W, d):
    # crude: per token ~ 2 * W * d multiply-adds (QK + weights*V)
    return T * W * d * 2

T, d = 131072, 128
full = attn_work(T, T, d)
for W in [128, 512, 2048, T]:
    print("window=", W, "relative attention work:", round(attn_work(T, W, d) / full, 6))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization, then open its guide.

Use the figures to connect each formula to what a serving system experiences:

  • A sliding window reduces attention compute, but can hurt retrieval of tokens outside the window.
  • RoPE makes the score depend on relative position; angles beyond the training range are still unfamiliar to the model.
  • The KV-cache figure shows how stored bytes grow with tokens, layers, KV heads, head width and precision.
Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Three claims about one request

Work out the cache for a 131,072-token request exactly, then match each long-context claim to the evidence it needs.

Loading the exercise…
In focus

Concept: Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

What is the smallest example of Long Context Engineering you can work through by hand, and what does it show?

BeforeScaled Dot-Product Attention & Transformer LayersNextFlashAttention: IO-Aware Attention
DetailsAttention & Transformers

Equation, code and demo

The equation, the code and the demo compute the same KV memory.

The cache stores keys and values for every layer, token, KV head, and head dimension. With batch, layers, KV heads, head size, and bytes fixed, memory grows linearly with context length T.

Bbatch sizeB
Lnumber of transformer layersL
Tcontext length in tokensT
H_kvkey/value heads after GQA or MQA sharingHkv
d_headwidth of each headd_head
2store both keys and values* 2
bytesbytes per cached elementbytes_per_elem
Predict firstIf T doubles while B, L, H_kv, d_head, and bytes stay fixed, what should happen to KV memory?

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

How models handle long inputs: keeping positions within the range seen in training (RoPE scaling), sliding windows, and cutting KV-cache memory with GQA, paging, quantization and compression.

Choose what to look for (no demo yet)01 / Intuition
Illustration of a stretched token scroll, rotary position arcs, and paged KV-cache blocks with selective long-range links.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

How models handle long inputs: keeping positions within the range seen in training (RoPE scaling), sliding windows, and cutting KV-cache memory with GQA, paging, quantization and compression.

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
paper · 2024RoFormer: Enhanced Transformer with Rotary Position EmbeddingSu et al.
Why it is cited

Neurocomputing 568, 127063 (arXiv 2021). Rotary position embedding, whose query-key product depends on the relative offset; not a RoPE-scaling method.

Open source
paper · 2022Train Short, Test Long: Attention with Linear Biases Enables Input Length ExtrapolationPress, Smith, and Lewis
Why it is cited

ICLR 2022. Treats extrapolation to inputs longer than in training as a problem of how position is represented, and proposes ALiBi, an alternative to RoPE.

Open source
paper · 2023Efficient Memory Management for Large Language Model Serving with PagedAttentionKwon et al.
Why it is cited

SOSP 2023. Treats serving long and many sequences as a KV-cache memory-management problem and allocates the cache in fixed-size pages.

Open source
paper · 2020Longformer: The Long-Document TransformerBeltagy, Peters, and Cohan
Why it is cited

arXiv preprint. Sliding-window attention, in which each token attends to a fixed-size window of nearby tokens, so cost grows linearly with length.

Open source
paper · 2023Extending Context Window of Large Language Models via Position InterpolationChen et al.
Why it is cited

arXiv preprint. Scales position indices of a RoPE model down into the trained range, then fine-tunes briefly.

Open source
paper · 2024YaRN: Efficient Context Window Extension of Large Language ModelsPeng et al.
Why it is cited

ICLR 2024. Interpolates slow rotary frequencies more than fast ones and rescales attention to extend RoPE models' context.

Open source
paper · 2023Efficiently Scaling Transformer InferencePope et al.
Why it is cited

MLSys 2023. Section 2 separates prefill from decode and shows that each decode step reloads weights and the KV cache, which can exceed the weights in size.

Open source
paper · 2024RULER: What's the Real Context Size of Your Long-Context Language Models?Hsieh et al.
Why it is cited

COLM 2024. Adds multi-fact retrieval, tracing and aggregation to the single-fact test; models near-perfect on that test lose accuracy as inputs grow.

Open source
What each claim rests on2 claims, each with its sources, where it appears on this page, and its caveats.

Claims and sources

How models handle long inputs: keeping positions within the range seen in training (RoPE scaling), sliding windows, and cutting KV-cache memory with GQA, paging, quantization and compression.

Each claim checked against the cited passages

The checks were made by this site, not by an independent reviewer.

Long-context engineering has two separate constraints: positional extrapolation must keep attention usable beyond training lengths, and KV-cache memory management must keep long-context serving feasible.
What the sources support

RoFormer grounds the rotary relative-position mechanism; ALiBi directly frames train-short/test-long length extrapolation as a position-representation problem; PagedAttention directly frames high-throughput...

Caveat

Checks two long-context constraints, not every bottleneck; RoFormer is not a RoPE-scaling recipe, ALiBi is not RoPE, and this page's code and figures are small illustrations, not production guarantees.

StatusChecked against the cited passages.

RoFormer supports rotary relative-position mechanics; ALiBi supports train-short/test-long extrapolation as a position-representation issue; PagedAttention supports KV-cache memory as a serving bottleneck. The code and figures on this page are small illustrations of KV sizing and rotation angles, not evidence about real serving systems.

A cache that fits, positions that still work past the training length, and a model that finds and uses its evidence are separate claims; evidence for one does not establish another.
What the sources support

Kwon et al. treat the cache as a memory problem, Chen et al. change how positions are mapped and evaluate the result, and Hsieh et al. test whether models find and use evidence beyond a single planted fact.

Where to see it on this page
Equation 3
MemKV≈B⋅L⋅T⋅Hkv⋅dhead⋅2⋅bytes.\mathrm{Mem}_{KV} \approx B\cdot L\cdot T\cdot H_{kv}\cdot d_{\mathrm{head}}\cdot 2 \cdot \mathrm{bytes}.
Caveat

The 131,072-token request and its 16 GiB cache are an ideal count chosen for round numbers, not a measurement. Prefill, bandwidth and scheduling are further constraints.

StatusChecked against the cited passages.

The RULER abstract and venue were checked for the single-fact finding, and Lost in the Middle (linked in the text) for the position finding. The 2^34-byte cache and its halving at four key–value heads were recomputed independently.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

Try the idea in your own words

How models handle long inputs: keeping positions within the range seen in training (RoPE scaling), sliding windows, and cutting KV-cache memory with GQA, paging, quantization and compression.

Concept · Selected for practice

Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

What it rests on: Sources: RoFormer: Enhanced Transformer with Rotary Position Embedding; Train Short, Test Long: Attention with Linear Biases Enables Input Length E...

Context and links
Choose a task

Explain the mechanism

For Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization: What is the smallest example of Long Context Engineering you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptLong Context Engineering: RoPE Scaling, KV Compression & Memory OptimizationSources: RoFormer: Enhanced Transformer with Rotary Position Embedding; Train Short, Test Long: Attention with Linear Biases Enables Input Length E...elems = B * L * T * Hkv * d_head * 2 # K and V

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

    Open the draft below to save one note and next action in this browser.

    conceptAttention & Transformers

    Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization

    Starting question

    What is the smallest example of Long Context Engineering you can work through by hand, and what does it show?

    SourcesCheck the 8 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Long Context Engineering: RoPE Scaling, KV Compression & Memory Optimization" feel predictable rather than familiar.
    Assumption

    The 8 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 8 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 8 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/attention-transformers/long-context concept:attention-transformers/long-context