Million-Token Sparse Models: From Attention to Kernel Optimization

    Million-token context and sparse mixture-of-experts are pushing large models from single-turn Q&A toward continuously running agents. This article clarifies why capability and latency SKUs are not simple distillation pairs, why ultra-long context is not a toggle, and how attention, KV cache, scheduling, and kernels must be redesigned together for production agent workloads.

    Million-token context and sparse mixture-of-experts (MoE) are moving large models from single-turn Q&A toward continuously running agents. Two mistakes often appear in these discussions: treating a generation’s high-capability and low-latency SKUs as a simple teacher–student pair, and treating long context as a switch you can flip at request time. The first undervalues independent pretraining and sparse architecture; the second underestimates cache, memory, scheduling, and kernel work. This article walks through the system-level optimization chain for ultra-long-context models.

    Two concepts: SKUs are not distillation, and long context is not a switch

    High-capability and low-latency SKUs may both be independently pretrained MoE

    When one generation ships both a high-capability and a high-throughput variant, smaller parameter count does not prove the smaller model is a distillate of the larger one. A more reasonable design is that both use sparse MoE, but differ in total parameters, activation ratio, routing, and training objectives. The high-capability SKU can store more knowledge in a larger total parameter budget while sparse activation keeps per-token compute in check. The low-latency SKU trades smaller total parameters and lower activation for throughput, time-to-first-token, and deploy cost.

    Independent pretraining means each model forms its own routing behavior and representation space, rather than copying the large model’s outputs. Distillation can compress models, but it is better as a targeted capability-transfer tool. Forcing a model that depends on long context, tool use, and multi-step reasoning into a small student often loses long-tail state consistency and recovery on complex tasks first. Evaluate SKUs on task success, context utilization, and cost per successful task—not total parameter count alone.

    Million-token context should not be a long-model / short-model switch

    If the platform treats million-token context as a unified capability, it should not swap to a separate “long-text model” based on request length. A better approach is one set of weights, one tokenizer, and one capability boundary. The scheduler allocates resources from request length, cache hits, latency targets, and batch size. For callers, long context is on by default. For the platform, it means unified GPU memory management, batching, cache reuse, and degradation.

    Default support for a million-token window does not mean every request should fill it. The window is a capacity ceiling, not a prompt-engineering goal. Longer requests raise time-to-first-token, cache occupancy, scheduling complexity, and cost. Keep “window size” (model capability) separate from “effective context budget” (product policy).

    Why agents consume hundreds of thousands of tokens quickly

    Classic chat is a few turns. Agents keep executing: they read files, call tools, observe results, record reasoning, maintain memory, and write state back into context. Context is a growing run log, not a one-shot prompt.

    Coding agents over many turns

    A coding agent over thirty turns may include hundreds of tokens of user instruction, thousands to tens of thousands from several source files, thousands from command output, and thousands of plans and summaries. At ~10k tokens per turn, thirty turns is 300k tokens. Large files, compile logs, and stack traces can push a single turn into tens of thousands. Hundreds of thousands of tokens is not unusual.

    Those tokens are not all disposable. User constraints, API contracts, edited files, failed commands, and rollback points must stay. Without context governance, the agent treats full history as valid state, wasting the window and polluting attention.

    Long-document analysis and multi-round revision

    Contracts, reports, codebases, and research often need cross-section citation, consistency checks, and iterative edits. Each turn may add source snippets, annotations, rationales, and locations. “Stuff everything” grows context linearly; naive truncation drops earlier constraints and produces contradictions.

    Persistent memory and tool state

    Long-lived assistants need preferences, project state, progress, and tool results. More memory raises the bar for retrieval and compression. Without layered memory, all history is appended to the prompt. With it, you still need summaries, indexes, TTLs, and confidence scores, or old memory contaminates new tasks and long context amplifies errors.

    A 100k–200k window is often insufficient for multi-turn agents. The fix is not blindly growing the window; it is long-context capacity plus context governance.

    The real bottlenecks: attention, cache, and scheduling

    Extending from ~100k to a million tokens is not a config change. Under full attention, prefill compute grows quickly with sequence length; decode repeatedly reads historical KV cache. Longer sequences inflate cache, so GPU memory capacity and bandwidth fail first. Even with enough FLOPs, scheduling and communication can cap throughput.

    Sparse MoE: gains and costs

    Sparse MoE routes each token to a subset of experts. Total parameters can be large for knowledge capacity; activated parameters per token stay smaller for compute. That fits “large capacity, low activation” serving, but adds complexity:

    • Total parameters still reside or are sharded; capacity planning cannot look only at activated parameters.
    • Expert parallelism adds token dispatch and result aggregation; long sequences make communication bursts worse.
    • Routing load can be uneven; capacity factor, load balancing, and hot-expert protection matter.
    • Mixing long and short requests requires batching that considers both KV cache and expert-parallel efficiency.

    Attention must be designed with the product goal

    Million-token context cannot rely on exact full attention alone. Common ideas include block attention, local windows plus global summaries, sparse block selection, retrieval augmentation, and hierarchical cache. The trade-off is how much exact history to keep, how much approximate summary to use, when to retrieve, and how to avoid dropping critical facts.

    For agents, the goal is often not “remember every token” but “fetch the right state at the right step.” Attention work should be co-designed with external memory, tool state, and file summaries. Otherwise the model advertises a million-token window and still loses key constraints in long history.

    KV cache is the scarce resource

    A simplified estimate:

    1. kv_bytes ≈ batch_size × seq_len × layers × kv_heads × head_dim × 2 × bytes_per_element

    At million-token length, KV cache can exceed model weights. Typical engineering includes paged cache, prefix reuse, quantization, hierarchical offload, and eviction. Paging reduces fragmentation; prefix reuse cuts repeated system prompts and tool schemas; quantization eases bandwidth; eviction decides what remains “visible.” These must couple to the scheduler, or you get low hit rates, long requests starving short ones, or poor batching.

    Six directions from attention to kernels

    1. Operator fusion and memory layout

    Long-context inference is not one attention kernel. Norms, positional encodings, residuals, activations, routing, and cache I/O create extra round trips. Fusion, contiguous layouts, blocked I/O, and async prefetch reduce materializing intermediates and improve bandwidth use. In decode, each new token reads a large history; access patterns often matter more than peak FLOPs.

    2. Chunked prefill and continuous batching

    Splitting long prefills into chunks lets them mix with short-request decode, cutting time-to-first-token and improving accelerator utilization. Continuous batching admits new requests when capacity allows instead of waiting for a long job to finish. The scheduler should constrain on token budget, cache occupancy, and latency—not queue length alone.

    3. Decouple prefill and decode

    Prefill is compute-heavy; decode is more memory-bandwidth and cache bound. Scaling and scheduling them separately reduces tail-latency impact of long jobs on short ones. Priority queues, timeouts, and degradation keep one ultra-long task from collapsing the service.

    4. Prefix cache and stable prompt structure

    System prompts, tool defs, fixed rules, and project background repeat across requests. Stable prefix order, cache keys, and invalidation raise hit rates. Prompt engineering should serve the cache: stable content first, changing content last. Avoid timestamps and random IDs that break prefix reuse.

    5. Overlap MoE communication and compute

    Under expert parallelism, dispatch, expert compute, and aggregation should be pipelined. Overlap, expert prefetch, hot-expert replication, and load balancing reduce communication jitter on long sequences. Avoid sending all heavy requests into the same expert group at once.

    6. Context compression and external memory

    Compression is not truncation; it keeps verifiable state. Split history into system constraints, recent dialogue, retrieved material, tool results, and task summaries. For tools, keep exit codes, key error lines, and file summaries; for long docs, citations and conclusions; for multi-turn work, checkpoints and rollback points so the model can re-fetch via indexes.

    A simplified budget policy:

    1. budget = window_tokens - output_reserve - safety_margin
    2. quota = allocate(budget, system, tool_schema, memory, files, history)
    3. context = keep(system) + keep(tool_schema)
    4. context += retrieve(memory, current_task)
    5. context += select(files, current_task)
    6. context += summarize(history, quota.history)
    7. while estimate(context) > budget:
    8. candidate = choose_compaction_candidate(context)
    9. context = compact(candidate)

    The point is the principle: reserve output and safety margin, allocate quotas, then compact by verifiability.

    Evaluation and capacity: “does it fit?” is not enough

    Layer evaluation:

    • Short-context basics: coding, math, instruction following, tool use
    • Long-document retrieval: facts, constraints, citations
    • Multi-hop synthesis: across sections, files, and turns
    • Long-task state consistency after many tool calls
    • Compression robustness when summary, eviction, or retrieval fails
    • Serving metrics: time-to-first-token, per-token latency, throughput, cache hit rate, cost per successful task

    Capacity planning must count weights, KV cache, activation intermediates, and communication buffers. Sparse MoE total parameters set a memory floor; activated parameters drive part of compute; sequence length and concurrency set cache ceilings. “Window supports a million tokens” is meaningless without: how many requests finish in latency SLO at target concurrency; cache hit rate; success drop after compression; long-request impact on short-request tails.

    Shipping long context as systems engineering

    First, token budgets. Cap system prompts, tool defs, retrieved material, history summaries, and output. When over budget, compact low-confidence, re-retrievable content first.

    Second, layered memory. Recent state in a short window, project knowledge in a retrieval index, long-term preferences in structured store, with TTL and confidence. Do not append all history to the prompt.

    Third, prompt structure. Stable first, volatile last; files as summary plus citation; tool output as key lines; multi-turn checkpoints instead of full replay.

    Fourth, quality telemetry. Besides latency and errors, track truncation, compaction rate, cache hits, duplicate reads, and tokens per successful task. Cost is often retries and wasted context, not list price.

    Fifth, tier by task. Complex coding, cross-document analysis, and long-lived agents get higher context budget and scheduling guarantees; short Q&A and high concurrency get latency and throughput. Tiering belongs in serving policy, not a fake second model capability.

    Conclusion

    Million-token context, sparse MoE, and agent memory are coupled system capabilities. The model must hold long sequences and state; the engine must optimize attention, cache, operators, and scheduling; the application must budget tokens, compress, retrieve, and evaluate. What users feel is not how many tokens fit on paper, but whether long-horizon tasks finish reliably at acceptable cost. Connecting the stack from attention to kernels turns a demo parameter into an operable production capability.