Conquering 2M Token Context: Sliding Window, Attention Sinks, and Paged KV Cache

How MeeDoo-OnE achieves practical 2 million token context through sliding window attention, attention sinks, INT8 KV cache quantization, paged KV cache, and YaRN positional encoding.

Abstract

Serving a 2-million-token context window is one of the most significant engineering challenges in modern LLM deployment. A naive implementation that materializes the full KV cache for 2M tokens would require approximately 687 GB of GPU memory per request — far beyond what any single GPU can hold. This article details the four complementary techniques that MeeDoo-OnE uses to make 2M context practical: sliding window attention with attention sinks, INT8 KV cache quantization, paged KV cache with CPU offloading, and grouped-query attention. Together, these reduce the GPU memory footprint from 687 GB to approximately 21.5 GB, enabling multiple concurrent long-context requests on a single 96 GB GPU.

The Math: Why Naive 2M Context Is Impossible

Let us compute the KV cache size for a single request at 2M tokens with the MeeDoo-OnE architecture:

Tokens:           2,097,152
Layers:            80 (attention layers)
KV Heads:          8
Head Dimension:    128
K + V:             2 tensors

Total elements = 2,097,152 * 80 * 8 * 128 * 2
              = 34,360,078,131,200
              = ~343 billion elements

In FP16 (2 bytes): 343B * 2 = 686 GB
In INT8 (1 byte):  343B * 1 = 343 GB

687 GB per request is obviously impractical. Even with INT8 quantization, 343 GB exceeds the capacity of any single GPU. The following sections describe how MeeDoo-OnE reduces this to a manageable footprint through a combination of algorithmic and systems-level innovations.

Technique 1: Sliding Window Attention + Attention Sinks

The first and most impactful optimization is replacing full causal attention with sliding window attention combined with attention sinks. The core idea is that most tokens only need to attend to a local window of recent context, while a small set of "sink" tokens at the beginning of the sequence serve as global anchors.

The attention mask is constructed by the build_long_context_mask function, which creates a boolean mask where each position can attend to:

  • All positions within a sliding window of 128K tokens (local attention)
  • The first 256 positions (attention sinks, always visible globally)
  • All positions before the current position (causal constraint)

Mathematically, the mask is: allowed = causal & (local | sinks)

def build_long_context_mask(
    seq_len: int,
    window_size: int = 131072,  # 128K
    num_sinks: int = 256,
    device = "cuda",
):
    # Causal mask: position i can attend to positions 0..i
    causal = torch.tril(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device))

    # Local window: |i - j| <= window_size
    positions = torch.arange(seq_len, device=device)
    local = (positions[None, :] - positions[:, None]).abs() <= window_size

    # Attention sinks: first num_sinks positions always visible
    sinks = torch.zeros(seq_len, seq_len, dtype=torch.bool, device=device)
    sinks[:, :num_sinks] = True

    allowed = causal & (local | sinks)
    return allowed

This reduces the attention complexity per token from O(2M) to O(128K), a 16x reduction. More importantly, only the KV cache for the 128K window plus the 256 sinks needs to be resident in GPU memory. This brings the KV cache from 687 GB down to approximately 43 GB.

The attention sinks serve a critical purpose: they give the model stable global anchors. Empirical research has shown that LLMs naturally attend heavily to the first few tokens of a sequence, using them as "sinks" for excess attention probability. By explicitly preserving these tokens, we maintain the model ability to reference early context (system prompts, instructions, document headers) without paying the full cost of global attention.

Flash Attention integration is straightforward: the window_size parameter in Flash Attention 2 and 3 directly implements the sliding window, and the sinks are handled by including them in the attention computation as a separate block.

Technique 2: INT8 KV Cache Quantization

The second optimization quantizes the KV cache from FP16 (16-bit) to INT8 (8-bit), halving the memory requirement. MeeDoo-OnE uses per-tensor symmetric quantization, which is simple, fast, and requires no calibration data.

def quantize_kv_int8(tensor: torch.Tensor) -> tuple[torch.Tensor, float]:
    """Per-tensor symmetric INT8 quantization."""
    scale = tensor.abs().max().item() / 127.0
    quantized = torch.clamp(
        torch.round(tensor / scale), -128, 127
    ).to(torch.int8)
    return quantized, scale

def dequantize_kv_int8(quantized: torch.Tensor, scale: float) -> torch.Tensor:
    return quantized.to(torch.float16) * scale

Per-tensor symmetric quantization computes a single scale factor as max(|tensor|) / 127 and applies it to all elements. This is less precise than per-channel or per-group quantization but is extremely fast and introduces negligible overhead during attention computation. The 2x memory reduction brings the 43 GB sliding window cache down to approximately 21.5 GB.

The quality impact of INT8 KV quantization is minimal. Research has shown that KV cache values have a much lower sensitivity to quantization than model weights, because they represent intermediate activations rather than learned parameters. Perceptual quality degradation is typically less than 0.5 BLEU or 0.3 ROUGE compared to FP16 KV cache.

Technique 3: Paged KV Cache

The third optimization borrows from vLLM the concept of a paged KV cache, which manages KV cache memory in fixed-size pages rather than as a contiguous block. This enables efficient memory utilization, CPU offloading, and eviction of cold pages.

The paged KV cache in MeeDoo-OnE is configured as follows:

  • Page size: 16 tokens — each page stores K and V for 16 tokens across all KV heads and layers
  • Maximum pages: 131,072 (supports up to 2,097,152 tokens = 131,072 * 16)
  • LRU eviction: whe n GPU memory is full, the least recently accessed pages are evicted to CPU RAM
  • Page fault handling: when attention computation needs an evicted page, it is fetched from CPU to GPU on demand
class PagedKVCache:
    def __init__(self, page_size=16, max_pages=131072, gpu_pages=2048):
        self.page_size = page_size
        self.max_pages = max_pages
        self.gpu_pages = gpu_pages  # resident on GPU
        self.cpu_cache = {}  # page_id -> CPU tensor
        self.gpu_cache = {}  # page_id -> GPU tensor
        self.lru = OrderedDict()

    def get_page(self, page_id):
        if page_id in self.gpu_cache:
            self.lru.move_to_end(page_id)
            return self.gpu_cache[page_id]

        # Page fault: bring from CPU
        if page_id in self.cpu_cache:
            self._evict_if_needed()
            tensor = self.cpu_cache.pop(page_id).cuda()
            self.gpu_cache[page_id] = tensor
            self.lru[page_id] = True
            return tensor

        raise KeyError(f"Page {page_id} not found")

    def _evict_if_needed(self):
        while len(self.gpu_cache) >= self.gpu_pages:
            evict_id, _ = self.lru.popitem(last=False)
            self.cpu_cache[evict_id] = self.gpu_cache.pop(evict_id).cpu()

The paged approach means that only the hot pages — those within the current sliding window and recently accessed sink pages — need to be resident on GPU. Cold pages (older context beyond the sliding window) are transparently evicted to CPU RAM and brought back only if explicitly needed. This decouples the GPU memory footprint from the total context length, enabling the model to claim a 2M token context window while only keeping ~128K tokens on GPU at any time.

Technique 4: Grouped-Query Attention (GQA)

The fourth optimization is architectural rather than algorithmic. MeeDoo-OnE uses GQA with 56 query heads but only 8 KV heads, a 7:1 ratio. This means the KV cache is 7x smaller than it would be with multi-head attention (MHA), where each query head has its own K and V head.

Configuration KV Heads KV Cache Size (relative)
MHA (full)561.0x (baseline)
GQA (MeeDoo-OnE)80.14x (7x reduction)
MQA (extreme)10.018x (56x reduction)

GQA strikes a balance between KV cache efficiency and model quality. MQA (single KV head) provides the most aggressive compression but can degrade quality on tasks that require fine-grained attention diversity. GQA with a 7:1 ratio preserves most of the quality while delivering a 7x reduction in KV storage, which compounds with the other techniques.

Memory Comparison: Putting It All Together

Configuration GPU Memory CPU Memory Reduction
Baseline (naive FP16)687 GB01x
+ Sliding window (128K)43 GB016x
+ INT8 quantization21.5 GB032x
+ Paged cache (CPU offload)21.5 GB~350 GB32x GPU, full ctx

The final configuration keeps only 21.5 GB of KV cache on GPU (fitting comfortably within a 96 GB GPU alongside model weights), while the remaining cold pages are stored in CPU RAM. The total system memory requirement is ~370 GB (21.5 GB GPU + ~350 GB CPU), which is achievable on a single server with sufficient RAM.

YaRN Positional Encoding

Extending context from the 8K training base to 2M tokens requires robust positional encoding. MeeDoo-OnE uses YaRN (Yet another RoPE extensioN), which applies a frequency-dependent scaling to Rotary Position Embeddings:

  • Low-frequency dimensions: interpolation (compress the position range)
  • High-frequency dimensions: extrapolation (no scaling, rely on high base frequency)
  • Transition band: smooth interpolation between the two regimes, controlled by beta_fast=32 and beta_slow=1.0

The mscale factor of 0.707 (= 1/sqrt(256), where 256 is the scaling factor) is applied as a temperature correction to the attention logits. Without this correction, the softmax over 2M tokens would become too diffuse, washing out attention patterns. The mscale sharpens the attention distribution, preserving the model ability to focus on relevant tokens even at extreme context lengths.

The rope_theta base of 500,000 is deliberately high. Standard RoPE uses theta=10,000, which provides sufficient positional resolution for 8K tokens but aliases badly at 2M. A base of 500,000 ensures that even the lowest-frequency dimensions have wavelengths long enough to distinguish positions across the full 2M range.

Ring Attention for Distributed Training

While the techniques above address inference, training on 2M token sequences presents its own challenge: no single GPU can hold the activations for 2M tokens. MeeDoo-OnE uses Ring Attention to distribute long sequences across multiple GPUs.

In the Ring Attention scheme:

  • A ring group of 14 GPUs is formed, each holding approximately 150K tokens (2M / 14)
  • Each GPU computes local attention for its token shard
  • KV blocks are passed around the ring, and each GPU accumulates the attention output using online softmax computation
  • Causal masking is applied using global position information, so tokens correctly attend only to preceding tokens regardless of which GPU holds them
# Ring Attention (simplified)
# 14 GPUs in a ring, each holds ~150K tokens
# Each step: compute local Q * remote KV, pass KV to next GPU

local_q = ...  # [150K, heads, dim] on this GPU
local_kv = ... # [150K, kv_heads, dim] on this GPU

accumulator = torch.zeros_like(local_q)
online_softmax = OnlineSoftmax()

for step in range(14):  # 14 GPUs in ring
    # Compute attention with local Q and current KV block
    block_output, online_softmax = ring_attention_step(
        local_q, local_kv, online_softmax,
        global_offset=step * 150000
    )
    accumulator += block_output

    # Pass KV to next GPU in ring
    local_kv = ring_send_recv(local_kv)

The online softmax algorithm is key: it allows computing the exact softmax over all 2M keys without materializing the full 2M x 2M attention matrix. Each GPU maintains running maximum and sum statistics, and the final output is mathematically equivalent to standard attention.

Inference Latency Targets

With all optimizations in place, MeeDoo-OnE targets the following inference latencies for a single 2M token context request:

Precision TTFT (Time to First Token) Notes
BF16~12sFull precision, 21.5GB KV cache
FP8~8sBlackwell native FP8
INT4~5sAggressive quantization

Speculative decoding with the MTP head provides an additional 2-3x speedup on generation throughput, though TTFT (which is dominated by prefill) is not improved by speculative decoding.

Conclusion

Achieving a 2 million token context window is not a single optimization but a stack of complementary techniques. Sliding window attention with sinks reduces the algorithmic complexity from O(n) to O(window) per token. INT8 quantization halves the KV cache memory. Paged KV cache with CPU offloading decouples GPU memory from total context length. GQA reduces the KV storage by 7x at the architectural level. YaRN scaling enables positional encoding to function at 256x the training length. Ring Attention makes training on 2M sequences feasible across a GPU ring.

Together, these techniques transform an impossible 687 GB per-request memory requirement into a practical 21.5 GB GPU footprint, making 2M token context serving viable on commodity hardware. This is what makes MeeDoo-OnE not just a research model with impressive numbers, but a deployable system that can serve real users with real long-context needs.

#long-context#attention#kv-cache#inference#meedoo-one#yarn