Hybrid Attention and MoE: Memory, Routing, and Deployment Guide

    This article is tailored for engineers involved in model selection, training, and cloud inference. It explores why long-context inference first exhausts GPU memory, explains what hybrid attention can and cannot compress, compares four MoE routing paradigms, and concludes with a deployment checklist and selection recommendations. All numerical values in the text are derived from demonstration configurations and do not represent any specific model.

    This article is designed for engineers handling model selection, training, and cloud inference. We will first explain why long-context inference exhausts GPU memory, then discuss what hybrid attention can and cannot compress, compare four MoE routing paradigms, and finally provide a deployment checklist and selection recommendations. All numerical figures in the text are calculated results from demonstration configurations and do not represent any specific model.

    1. The First Hurdle of Long Context: KV Cache

    When a Transformer generates a new token, it needs to read the Keys and Values of all previous tokens. These vectors are saved and referred to as the KV cache. Its size grows linearly with the sequence length, meaning longer sequences put greater pressure on GPU memory.

    KV Cache Bytes = 2 × Number of Layers × Number of KV Heads × Dimension per Head × Sequence Length × Bytes per Element × Batch Size

    Here is what each term means. The “2” in the formula represents the two sets of data for K and V. The number of layers is the number of Transformer blocks. The number of KV heads is the number of key-value heads that need to be cached, which does not necessarily equal the number of query heads. The dimension per head is the vector length of a single head. Bytes per element is determined by numerical precision: BF16 is 2 bytes, and FP8 is 1 byte. Batch size is the number of requests processed simultaneously.

    For example, let’s set 60 layers, 64 KV heads (Standard Multi-Head Attention, MHA), a dimension per head of 128, BF16 precision, a sequence length of 1 million, and a batch size of 1. Plugging this into the formula, the KV cache is approximately 1.97TB. If we switch to Grouped-Query Attention (GQA) with 8 KV heads, the same configuration yields about 246GB. These numbers are for demonstration purposes only and are not parameters of any specific model.

    From this, three factors have the greatest impact. First is the number of KV heads; GQA and MQA reduce the cache directly by reducing KV heads. Second is precision; reducing bytes per element linearly decreases memory usage, but quality loss must be validated. Third is batch size; the larger the batch, the more cache concurrent requests consume. KV cache is also linearly related to batch size, so memory limits must be considered alongside throughput optimization.

    2. Hybrid Attention: Shallow Compression, Deep Refinement

    The idea behind hybrid attention is a division of labor across layers. Shallow layers compress long sequences into a fixed number of summary vectors to extract global semantics, shortening the context that deep layers need to process. Deep layers only perform high-precision attention calculations on local segments most relevant to the current token.

    The reduction in KV cache after compression depends on the compression ratio, layer division, and baseline implementation. Some approaches report reductions of around 90%, but such figures are only meaningful when accompanied by the baseline configuration, sequence length, and measurement method. Readers should test on their own models and workloads, recording at least the following during testing:

    • Baseline configuration: Number of KV heads, precision, number of layers, and whether the comparison uses MHA, GQA, or another method.
    • Sequence length distribution: Average length, tail length, and maximum length.
    • Batch size and concurrency.
    • Metrics: Peak memory, Time to First Token (TTFT), Tokens Per Second (TPS), and task quality metrics.

    Dynamic Compression Ratio

    A fixed compression ratio cannot adapt to different inputs. Dynamic compression allows the model to adjust the compression intensity based on the information density of the input: paragraphs with dense information retain more features, while repetitive or templated content is compressed more deeply.

    The compression ratio can be set per layer, per attention head, or per segment. The trade-offs are as follows. Setting it per layer is the simplest to implement, where all positions and heads within the same layer share the compression ratio, resulting in minimal kernel changes. Setting it per head is more granular, allowing different heads to focus on information of different granularities, but cache indexing and kernel complexity increase significantly. Setting it per segment is the closest to information density, but scheduling, batching, and parallelization are the most difficult to implement.

    A recommended starting point is to set a fixed compression schedule per layer, verify quality on a validation set, and then consider refining it to per head or per segment. Each refinement step should be compared against the simpler approach in terms of memory and quality.

    Intermediate Layer Auxiliary Loss

    During training, in addition to the final output loss, auxiliary loss measuring information retention and discarding can be added to intermediate layers, encouraging the model to learn what information should be retained. The auxiliary loss is added to the main loss by weight:

    Total Loss = Main Loss + λ × Auxiliary Loss

    The weight λ requires tuning. If the weight is too large, the main task converges slowly, and the summary vectors may degrade into fixed patterns unrelated to the content, actually degrading the model’s performance on long-text tasks. If the weight is too small, the intermediate layers hardly learn to retain information, making compression nothing more than random discarding, which defeats the purpose.

    When tuning, you can start with a smaller weight, conduct several comparison sweeps, and simultaneously monitor the following metrics: information retention rate (measured by a set of probing tasks to see how much original information the summary vectors can recover), validation set loss, gradient norm, and whether spikes occur during training. These metrics need to be compared on the same batch of data and under the same random seed to determine the true impact of weight changes.

    3. Comparison of Four MoE Routing Paradigms

    Mixture of Experts (MoE) places multiple expert feed-forward networks in each layer, and the router decides which experts each token passes through. Here, “activated parameters” refers to the number of parameters each token actually passes through, which is usually much smaller than the model’s total parameters.

    The FFN parameters activated by a single token can be estimated as:

    Activated Parameters ≈ Number of Shared Experts × Parameters per Expert + Number of Routed Experts Selected per Token × Parameters per Expert

    For example, suppose a layer has 8 routed experts, each with 1B parameters, and each token selects 2 experts. The total parameters for this layer are 8B, and the activated parameters per token are 2B. This is a demonstration calculation; actual models also include attention, embedding layers, etc.

    Routing Paradigm How it Works Activated Parameter Characteristics Expert Structure Applicable Scenarios Main Limitations
    Top-1 (Single Expert Routing) Each token selects only the 1 highest-scoring expert Minimum, approximately 1 expert’s parameters Experts are usually the same scale and simple in structure Tight training and inference compute, wanting large parameter scale but small per-compute cost Tokens may be dropped when expert capacity overflows, expressiveness limited to a single expert
    Top-K (Multi-Expert Weighted Routing) Each token selects the top K highest-scoring experts, merges outputs by weight Approximately K experts’ parameters, K is usually 1 to 2 Experts have a uniform structure, router outputs weights Needs stronger expressiveness and can accept higher compute Load easily unbalanced, requires auxiliary loss constraints; communication and compute increase as K grows
    Expert-Choice (Expert selects Token) Each expert selects a fixed number of tokens from the batch Number of experts selected per token is not fixed, average activation needs to be statistically calculated Expert load is naturally balanced, structure is uniform Pursuing load balancing during training, sufficient data within the batch Expert selection depends on other tokens in the same batch; if used for autoregressive decoding, it may introduce future information leakage and requires careful validation
    Shared Expert + Fine-grained Routing Some shared experts are always activated, plus a large number of small routed experts selected via Top-K Shared expert part is fixedly activated, routing part calculated by K Experts are finer and more numerous, with a few shared experts carrying general knowledge Requires finer expert division and can handle larger total parameters and memory footprint All experts must reside in memory or be distributed across multiple cards, expert parallel communication overhead is high, many hyperparameters

    Key Points of Each Paradigm

    The advantage of Top-1 routing is that it is the most compute-efficient. Its risk lies in capacity. The number of tokens each expert can process usually has an upper limit, and excess tokens are skipped or dropped, so the drop rate must be monitored.

    Top-K routing is the most common approach. The larger the K, the higher the compute per token, and the smoother the output. It relies on auxiliary loss to prevent a few experts from being overused. During training, observe the number of tokens each expert receives; if the distribution is chronically skewed, adjust the auxiliary loss weight or capacity factor.

    Expert-Choice routing allows experts to actively select tokens, naturally balancing the load. Its problem is that selection occurs within a batch, and experts may select tokens after the current position. In autoregressive models, this design requires special handling, otherwise training performance may be higher than real inference performance. Causality validation should be performed in inference scenarios before selection.

    Shared expert plus fine-grained routing places general capabilities in shared experts and distributes specialized capabilities among a large number of fine-grained experts. This structure is more flexible in expert division, but it requires more memory and communication resources. During selection, total parameters, per-card memory, and the communication topology of expert parallelism must be calculated clearly.

    4. Deployment Essentials and Troubleshooting Checklist

    Pre-deployment Checklist

    • Calculate the memory budget based on total parameters, not activated parameters. If routed experts are not offloaded, they must all reside in memory or be distributed across multiple cards.
    • Calculate the KV cache under the target sequence length and batch size using the formula, and add it to the weight footprint.
    • Confirm the number of KV heads, precision, and attention type (MHA, GQA, MQA, or hybrid attention), keeping it consistent with baseline reports.
    • Confirm the communication method and topology of expert parallelism, and measure all-to-all communication latency on the target hardware.
    • Set a capacity limit for each expert and record the drop rate.
    • Perform stress testing with real request distributions (not uniform random data) and record P50 and P99 latency.

    Common Errors and Troubleshooting Steps

    • Out of memory during loading: First, check whether memory was estimated based on activated parameters rather than total parameters. Then check if resident loading of all experts was enabled.
    • Out of memory for long text: Verify the KV cache item by item according to the formula, focusing on sequence length, batch size, and the number of KV heads. If it doesn’t match the formula result, check for duplicate caches or unreleased temporary tensors.
    • Quality degradation after quantization: Compare the output differences before and after quantization layer by layer, prioritizing the router and attention layers. The router is sensitive to precision, and quantization may change expert selection.
    • High tail latency: Count the number of tokens per expert. If a single popular expert accounts for too high a proportion, it indicates routing skew; check the load balancing loss or capacity settings.
    • Sudden loss spike during training: Check whether the router logits are numerically too large, whether the auxiliary loss weight is too large, and whether the learning rate is too high.
    • Expert collapse (most tokens concentrated on a few experts): Increase the auxiliary loss weight, or check expert initialization and the router’s normalization method.
    • Quality degradation with hybrid attention: First confirm whether the compression ratio and layer division are consistent with those during training, then check whether the information retention rate of the intermediate layer auxiliary loss dropped significantly in the later stages of training.

    5. Selection Decisions and Risk Warnings

    Requirement Priority Consideration Things to Confirm
    High memory pressure for long text Evaluate GQA or MQA first, then hybrid attention and low-precision KV cache Baseline configuration, sequence length distribution, quality metrics
    Needs larger parameter capacity but limited per-compute Evaluate MoE, prioritizing Top-1 or Top-K Total memory, expert parallel communication, drop rate
    Needs finer expert division Evaluate shared expert plus fine-grained routing Per-card memory, communication topology, hyperparameter stability
    Pursuing load balancing during training Evaluate Expert-Choice Causality and real-world performance during inference
    Simultaneous long text and large capacity needs The two types of approaches can be combined, but must be validated separately Quality, latency, and memory superposition effects after combination

    Risk Warnings

    First, all numbers in this article come from demonstration configurations. Any reduction, speed, or quality figures are only meaningful when the baseline, sequence length, and measurement method are specified.

    Second, the benefits of different paradigms are highly dependent on the workload. A routing setting that works on one dataset may fail on another.

    Third, both compression and routing alter model behavior. Before going live, perform a quality regression on an evaluation set close to your business, rather than just looking at memory and speed.

    Fourth, all hyperparameters (compression ratio, auxiliary loss weight, capacity factor, K value) need to be validated on your own data. The starting points given in the text are just for discussion and should not be directly used as final configurations.