Conditional Computation and Conditional Memory: A Dual-Pillar Design for LLM Inference
Dense large language models waste compute by activating nearly all parameters for every token, regardless of input complexity. This article explains how conditional computation (Mixture of Experts) and conditional memory can work together as complementary pillars: one handles dynamic reasoning through sparse computation, the other retrieves static knowledge through sparse lookup. It covers how each mechanism works, how they differ across key dimensions, and practical guidance for evaluation, ablation, and production deployment.
Why Dense Computation Wastes Resources
Traditional dense models activate almost all parameters in the forward pass for every input token. The larger the model, the more compute a single inference requires, with cost and latency growing linearly with parameter count. This design is simple but uses resources inefficiently: processing a simple query like “What’s the weather today?” costs the same as handling complex multi-step reasoning.
Increasing a model’s knowledge capacity usually means adding parameters. If every inference requires full computation, capacity and inference cost become tightly coupled. Researchers need a way for a model to “own many parameters” while “using only a subset of them per inference.”
Mixture of Experts and Conditional Computation
Mixture of Experts (MoE) is one of the mainstream architectures for solving this problem. The core idea is to split the feed-forward network into multiple subnetworks, each called an expert. A router scores every expert based on the hidden state of the current token, then only the top-scoring experts participate in the computation. This approach of dynamically selecting computation paths based on input is known as conditional computation.
Conditional computation delivers two immediate benefits. First, the total parameter count can scale to a very large size, because expert parameters are only used when selected. Second, the number of activated parameters per token stays small, so inference speed approaches that of a smaller model. Here is a simplified illustration of Top-k routing:
def moe_forward(x, experts, router, k=2):scores = router(x) # matching score for each experttopk_idx = scores.topk(k).indices # select the k highest-scoring expertsweights = softmax(scores[topk_idx]) # normalize into combination weightsreturn sum(w * experts[i](x) for w, i in zip(weights, topk_idx))
This code is for illustration only and omits engineering details such as load balancing, batching, and distributed communication.
Conditional computation is well suited to dynamic logical reasoning because expert selection depends on context. But its essence is still “computation.” For static knowledge such as names, fixed terminology, common phrases, and basic arithmetic results, the model must re-derive answers through multiple layers of transformation every time, even when the answer is already determined. This computation adds no new reasoning value; it simply burns cycles.
Conditional Memory: Bringing Lookup into the Model
How humans handle common questions offers a useful analogy. Asked “What is 2 times 2?”, most people answer directly, because the result is stored in memory. They do not derive it step by step from the axioms of addition. Only when facing an unfamiliar, complex problem do they engage the full reasoning process.
Inspired by this, a conditional memory mechanism introduces a “lookup” path into the model. It runs in parallel with conditional computation, forming a two-step workflow:
- For high-frequency, stable patterns (fixed phrases, common entities, frequent expressions), read vectors directly from a memory table.
- For content requiring contextual reasoning, hand off to the conditional computation path.
The “conditional” aspect lies in context-dependent retrieval. Rather than reading a global vector from a fixed address, the system generates a retrieval key from nearby token snippets and locates the corresponding memory slot. Below is an illustrative teaching module covering three stages: indexing, reading, and fusion.
class ConditionalMemory(nn.Module):def __init__(self, num_slots, dim):super().__init__()self.table = nn.Embedding(num_slots, dim) # large-scale sparse memory tableself.gate = nn.Linear(dim * 2, 1) # fusion gatedef forward(self, hidden, context_ids):slot = hash_ids(context_ids) % self.table.num_embeddings # illustrative index functionmem = self.table(slot) # read memory vectorg = torch.sigmoid(self.gate(torch.cat([hidden, mem], dim=-1)))return hidden + g * mem # fuse based on gate strength
Three design points deserve attention. First, the index function determines which contexts share the same slot, directly affecting hit quality and collision rates. Second, the memory table can be very large, but only a few rows are accessed per query, so its main pressure comes from storage capacity and memory bandwidth rather than floating-point compute. Third, the gate lets the model judge how trustworthy the retrieved memory is. When the retrieved content does not match the current context, the gate can downweight it to prevent faulty memories from interfering with reasoning.
How the Two Pillars Work Together
Conditional computation and conditional memory address different problems and consume different types of resources, making them complementary. The table below compares them across several dimensions:
| Dimension | Conditional Computation | Conditional Memory |
|---|---|---|
| Primary workload | Dynamic reasoning, composition, judgment | Static knowledge, fixed patterns |
| Resource consumption | Compute (FLOPs) | Storage capacity and memory bandwidth |
| Routing basis | Current hidden state | Retrieval key generated from context |
| Typical failure modes | Uneven expert load | Hash collisions, stale or incorrect memories |
This division of labor means designers must decide how to allocate sparse parameters: how many go into experts, and how many into the memory table. Leaning too far toward experts leaves static knowledge dependent on computation; leaning too far toward memory may weaken the model’s reasoning ability. There is no universal ratio—the right balance depends on task type and hardware constraints and must be determined experimentally.
Evaluation from an Engineering Perspective
After introducing new mechanisms, teams need a reproducible set of metrics rather than a single “improvement” conclusion. Consider evaluating along these lines:
- Separated quality evaluation: Test knowledge-heavy and reasoning-heavy tasks separately. Looking only at aggregate metrics makes it hard to tell which path contributed the gains.
- Memory hit statistics: Track the hit rate and collision rate of retrieval keys. A low hit rate suggests the memory table under-covers the real distribution; a high collision rate suggests different contexts are being incorrectly merged.
- Memory latency and throughput: Memory tables are typically much larger than conventional activated parameters, so measure their read latency on target hardware and compare it with the computation path’s runtime.
- Storage footprint: The memory table’s size directly determines deployment cost. Evaluate placement options across GPU memory, host memory, or tiered storage.
- Out-of-distribution behavior: When inputs deviate from the training distribution, memory may return irrelevant content. Build dedicated test sets to verify whether the gating can mitigate this.
Practical Recommendations
First, run performance profiling to determine whether the bottleneck is compute-bound or memory-bound. If the system is already limited by memory bandwidth, simply enlarging the memory table may yield limited gains.
Second, run small-scale ablation experiments. Compare three configurations in sequence—conditional computation only, conditional computation plus fixed memory, and conditional computation plus gated memory—to isolate each component’s contribution.
Third, pay close attention to index function design. Context window length, hashing method, and slot count must be tuned jointly. A window that is too short provides insufficient semantic differentiation; one that is too long reduces sparsity and makes hit rates unstable.
Fourth, define explicit fallback behavior for memory misses. The system should rely on the conditional computation path to complete reasoning rather than outputting blank or random vectors. This is especially important for production service stability.
Fifth, establish a versioned memory table management process. Memory content changes as data is updated, so record build time, data sources, and validation metrics to support rollback and auditing.
