Million-Token Context LLMs: Sparse Attention and Cost Reduction in Practice

    Long context has become a default requirement, but window size is not the same as affordable latency and memory. This article explains quadratic attention and KV-cache growth, how sparse attention and MoE trade compute and capacity, and which serving-layer optimizations (paged KV, prefix cache, continuous batching, quantization) cut unit-task cost without retraining.

    1. Why long context moved from a nice-to-have to a default filter

    Context length used to sit at the bottom of a model spec sheet. It is often the first screening criterion now. Real workloads are long by nature: coding assistants need related files and dependency declarations from a whole repository; document review spans hundred-page contracts and attachments; customer support and ops keep multi-turn histories that reach tens of thousands of tokens; log and trace analysis dumps raw text in bulk.

    “Can it fit?” and “Can we afford it after it fits?” are separate questions. Many teams pick models by window size, then discover bills and latency are unacceptable in production. This article focuses on the second problem: what actually drives long-context cost, which general techniques the industry uses to compress it, and which engineering levers do not depend on changing model architecture.

    2. Cost driver one: quadratic attention

    In self-attention, every token attends to every other token in the sequence, so prefill compute grows with the square of sequence length. Going from thousands of tokens to a million is about five orders of magnitude more theoretical compute. That is why first-token latency on long documents (often tens of seconds) becomes an experience bottleneck.

    3. Cost driver two: linear KV-cache growth

    During decoding, each new token reads the key-value cache of the full history. Memory use is roughly:

    1. KV_bytes ≈ 2 × L × H_kv × D_head × S × B × bytes_per_elem
    2. # 2: K and V; L: layers; H_kv: KV heads; D_head: head dim
    3. # S: sequence length; B: concurrent batch; bytes_per_elem: precision

    S and B multiply. At million-token context, a single request’s KV cache can fill a GPU, and concurrency collapses to single digits. The real bottleneck is often not FLOPs but HBM capacity and memory bandwidth. Any cost plan must answer both “compute less” and “store less.”

    4. Sparse attention: compression along the token axis

    The idea is that not every token pair needs exact interaction. Common patterns fall into four families, usually combined:

    1. Local windows: each token attends only to a fixed nearby range. Complexity becomes linear; this captures local syntax and short-range dependency.
    2. Global anchors: a few tokens (e.g., the first token or summary tokens) remain globally visible and aggregate cross-segment information.
    3. Block sparsity: the sequence is chunked and attention is computed selectively at block granularity, balancing long-range dependency and hardware friendliness.
    4. Compress then retrieve: history is stored as a few low-resolution representations and original spans are fetched only when needed (coarse-to-fine).

    Illustrative pseudocode (structure only, not a specific implementation):

    1. def sparse_attention(q, k, v, window=4096, block=256, top_blocks=16):
    2. # 1) Local window: exact attention nearby
    3. local = dense_attention(q, k[:, -window:], v[:, -window:])
    4. # 2) Block-level scores; pick history blocks most relevant to the query
    5. scores = block_mean_pool(q @ k.transpose(-1, -2)) # [B, H, num_blocks]
    6. idx = scores.topk(top_blocks, dim=-1).indices
    7. # 3) Exact attention only on selected blocks
    8. far = gather_block_attention(q, k, v, idx, block)
    9. return combine(local, far)

    Production has three hard constraints. First, train–serve consistency: the sparse pattern must be in pretraining and post-training; switching it only at inference hurts quality. Second, long-range extrapolation: positional encodings must match the sparse pattern, or quality drops quickly outside the trained window. Third, kernels: without efficient operators, lower theoretical complexity does not become higher throughput—easy to miss in a self-hosted serving stack.

    Sparse attention pays twice: less compute cuts prefill latency, and a smaller KV cache (window plus anchors) frees memory and raises concurrency. That is why long-context capability and inference cost are tightly coupled in engineering.

    5. Mixture of experts: decoupling total parameters from activated parameters

    The second structural lever is MoE. In a dense model every token runs through all parameters. MoE uses a router so each token activates a few experts. Total parameter count (capacity) and per-token activated parameters (compute) can differ by an order of magnitude.

    A common misconception: MoE saves compute, not memory. All expert weights still reside on device (or must be swapped in), so HBM and bandwidth pressure remain—especially with long context. Typical companion techniques include load-balancing auxiliary losses to avoid expert collapse, capacity factors for overflow, combining expert and pipeline parallelism to amortize communication, and sharing experts across layers to shrink total weights.

    The practical test is clear: if the bottleneck is throughput and compute budget, MoE helps a lot; if a single GPU cannot hold the request, prioritize KV compression, quantization, and sharding rather than expecting MoE to fix memory.

    6. Serving-system engineering: the same model can differ by several times in cost

    Outside the model, serving optimizations often yield larger and faster gains without retraining.

    • Paged KV cache: split contiguous HBM into fixed-size pages allocated on demand, reduce fragmentation, and raise concurrent load.
    • Prefix-cache reuse: system prompts, tool definitions, and repo context repeat across requests; a hit skips redundant prefill—often the highest-ROI item for long context.
    • Continuous batching: form batches at iteration granularity so short and long requests do not stall each other.
    • Quantization: weight and KV-cache quantization hit memory and bandwidth; validate quality on an internal eval set.
    • Speculative decoding: a small model drafts and a large model verifies, reducing decode latency at small batch sizes.
    • Split pools by length: route by input length so ultra-long requests do not dominate P99.

    Instrument at least: input/output tokens, cache hit rate, time to first token, peak memory per request, and cost per task. Without those metrics, cost work is blind tuning.

    7. How to read coding benchmarks

    Coding skill is a convenient scoreboard, but public leaderboards need care. Contest problems are well-bounded, single-file, auto-gradable algorithms. Real delivery involves cross-file dependencies, implicit conventions, legacy, and regression risk. Pass@k is sensitive to sample count and temperature, and public items may leak into training data.

    A more reliable approach is a small internal suite covering four task types: repo-level edits (multi-site call understanding), bugfix given failing tests, test generation, and refactor with behavior preserved. Optimize for pass-on-first-try, rework rounds, review comment count, and regression rate—metrics that map to business cost better than leaderboard rank.

    8. Open vs. closed selection framework

    Do not decide on a “catch-up” narrative. Score dimensions: unit-task cost, data residency and compliance, fine-tune and control, peak elasticity, ops headcount, iteration cadence. Mature teams often mix routes: frequent simple traffic on smaller models with cache-first, complex traffic on larger models, one gateway for quotas and fallback. Open weights matter most for compliance-sensitive and deep customization work; fully managed APIs win on elasticity and low ops. They are complementary, not substitutes.

    9. A generic cloud landing architecture

    • Container platform for inference with elastic scale for peaks.
    • Object storage for weights, eval sets, and long-text corpora.
    • Message queues to absorb async long jobs so they do not block the online path.
    • Unified logging and alerting on token cost, latency percentiles, and cache hit rate.
    • Gateway for multi-model routing, canaries, and quotas.

    10. Closing

    The capability bar for million-token context is dropping quickly. Competition shifts to unit-task cost and delivery stability. Sparse attention reduces compute; KV compression reduces storage; MoE decouples capacity from compute; serving raises utilization. Together they turn long context from a demo into a scalable production setting. Suggested order: internal evals and cost observability first, then serving optimizations, then architecture-level swaps—each step driven by data, not leaderboards.