Mixture of Block Attention: How It Accelerates Long-Context Inference and How to Apply It
This article explains why standard self-attention becomes the bottleneck as context grows to hundreds of thousands or millions of tokens, and how Mixture of Block Attention applies sparse activation and learnable routing from Mixture-of-Experts to attention. It covers the routing mechanism with pseudocode, complexity and real-world speedups, four engineering challenges (causality, load balancing, block size and k, train-inference consistency), hybrid sparse-dense layer design, serving considerations, and a three-step adoption path with selection signals.
1. The Starting Problem: Why Attention Becomes the Long-Context Bottleneck
Standard self-attention requires every query token to compute an inner product against all historical key-value (KV) pairs, so both compute and memory usage grow quadratically with sequence length. When the context expands from a few thousand tokens to the million-token range, most of the compute is spent on historical segments that are irrelevant to the current semantics. After softmax, these inner products receive tiny weights and contribute almost nothing to the output. In other words, full attention casts a very wide net, but the genuinely useful information is highly concentrated.
Existing approaches in the industry fall into roughly three categories. The first is sparse patterns: a fixed sliding window, global tokens, or a strided pattern defines the connections in advance. This is simple to implement, but the connections are unrelated to the task. The second is linear attention and state-space methods, which compress history into a fixed-size state. They offer high throughput but introduce an information bottleneck that degrades exact retrieval. The third is cache compression, which reduces memory by evicting or merging historical KV entries but usually does not change the order of magnitude of the computation. Mixture of Block Attention takes a fourth path: it leaves the decision of which blocks to connect to the data itself.
2. Core Idea: Bringing Mixture-of-Experts into Attention
The key to Mixture-of-Experts (MoE) is not the “multiple experts” form itself, but “sparse activation plus learnable routing”: each token travels only a few paths, so the total parameter count can be very large while per-step compute stays small. Mixture of Block Attention transplants this paradigm to attention. The context is split into contiguous blocks, each block acts as one “expert,” and each query token goes through a scoring and selection mechanism that runs full attention only against a few of those blocks.
Formally, suppose the sequence is divided into blocks. When a query sits at position t, a relevance score is first computed for every candidate block, the top-k blocks are selected, and standard scaled dot-product attention with normalization is executed only over the keys and values of those blocks:
# Illustrative pseudocode: block-level top-k routing + full attention within blocksdef block_sparse_attention(q, k, v, block_size, topk):# q: [1, d]; k, v: [S, d]S = k.shape[0]blocks = [(i, slice(i, i + block_size)) for i in range(0, S, block_size)]# 1) Block representation: pool the KV inside each block into a lightweight summaryscores = []for idx, sl in blocks:k_mean = k[sl].mean(dim=0)scores.append((q @ k_mean) / (d ** 0.5)) # relevance score# 2) Sparse routing: keep only the topk highest-scoring blocks (including the current block to preserve causality)chosen = [blocks[i] for i in topk_indices(scores, topk)]# 3) Compute full attention within each block, then normalize across blockslogits, vs = [], []for idx, sl in chosen:logits.append((q @ k[sl].T) / (d ** 0.5))vs.append(v[sl])out = softmax_with_global_norm(cat(logits), cat(vs))return out
Two implementation routes exist for the accompanying gating network. One is a parameterized linear score, using a small projection matrix to map the query into the block space; it is more expressive. The other is parameter-free content addressing, which takes the inner product of the query with the pooled block summary directly; it is extremely simple and carries no extra state. The two usually perform similarly, and engineering practice tends to favor the latter because it introduces no additional weights that need to be synchronized and sharded.
It is worth stressing that this sparsity is dynamic and content-dependent: the same query selects different blocks under different contexts. This is fundamentally different from a fixed pattern, and it is also why the method retains accuracy on retrieval-style tasks.
3. Complexity and Where the Speedup Comes From
Let the sequence length be S, the block size be B, and the number of blocks selected per query be k. Per-step attention compute is roughly O(S·k·B). Compared with the O(S²) of full attention, this is close to linear as long as k·B is much smaller than S. Take million-token sequences as an example: with a block size of a few hundred and k in the teens, the share of KV actually involved in computation can be squeezed down to around one percent. In public evaluations, this class of methods achieves roughly 6.5x compute speedup at the million-token scale, and at the ten-million-token level the speedup ratio widens to more than 16x. The longer the sequence, the more pronounced the benefit of sparsity.
The speedup does not come only from fewer multiply-add operations. During decoding, reading the KV cache is the bandwidth bottleneck, and sparse routing means only a few blocks are moved each time, which directly relieves memory bandwidth pressure. Block-level access also has better locality, making it easier to apply tiled pipelines and operator fusion. This also explains why the speedup under very long contexts exceeds the ratio suggested by theoretical compute alone.
4. Four Engineering Challenges That Must Be Solved
Causality and visibility of the current position. Generative models cannot see the future, so routing candidates must be restricted to blocks before the current position, and the block containing the current position must be included unconditionally; otherwise missing information causes anomalous perplexity.
Load balancing. Routing naturally favors “hot blocks.” If a few blocks are selected by the vast majority of queries, severe load skew appears after parallel sharding. Common mitigations include an auxiliary balancing loss, random permutation or noise perturbation, or capping block capacity with overflow fallback.
The tradeoff between block size and k. If blocks are too small, routing overhead and scoring cost take a larger share; if blocks are too large, sparsity is insufficient and the method degenerates into full attention. In practice, block size depends on the model layer and sequence length and needs to be swept on a validation set rather than hard-coded globally.
Train-inference consistency. If training uses full attention but inference switches to sparse, the distribution shift causes quality regression. The safer route is to use block sparsity during pre-training or continued pre-training, while keeping a small number of full-attention layers to aggregate global information.
5. Hybrid Layer Design: Sparse by Default, Dense as Backstop
Pure sparsity is not optimal in every layer. A fairly general engineering structure is to keep full attention or sliding-window attention in the bottom layers and a few key layers, where they handle local syntax and global anchors, while the remaining layers use block sparsity to carry long-range retrieval. This “sparse by default, dense as backstop” combination typically matches full attention on benchmarks such as long-document question answering, cross-file code understanding, and long-conversation memory, while retaining most of the speedup.
On the inference serving side, the implementation priorities include organizing the KV cache by block with support for paging and eviction, caching routing scores for reuse to avoid repeated pooling, and using variable-length operators to handle differing block selections across requests in a batch. Hit rate, block selection distribution, and overflow rate should also be wired into logging services and monitoring alerts, making it easier to locate quality regressions and performance jitter. If the context exceeds single-machine memory, cold blocks can be persisted to object storage to enable near-unlimited conversation memory.
6. Selection Guidance
Three signals help decide whether block sparsity is needed: whether the context length has already reached hundreds of thousands of tokens or more; whether sampled attention weights are highly concentrated (very low entropy); and whether memory and time-to-first-token have become the main cost items. The benefit is greatest when all three hold. If the workload is mainly short prompts and heavy reasoning, full attention or a lightweight sliding window is often the simpler choice.
A three-step adoption path is recommended. First, compare the quality gap between full attention and block sparsity on an offline evaluation set, and lock down the block size and k. Second, introduce sparsity during continued pre-training while keeping a few dense layers. Finally, roll out gradually and use monitoring metrics to watch the latency and quality curves for long requests. General-purpose capabilities such as the container platform, logging service, and monitoring alerts on Baidu AI Cloud can support this kind of gradual rollout and observability, while the model side only needs to keep the routing implementation consistent between training and inference to obtain both accuracy and throughput in long-context scenarios.
