Conditional Memory: Adding a Knowledge Lookup Axis to Large Language Models

    Conditional computation increases the computation that can be invoked by an input, but it does not remove the need for models to reconstruct locally decidable knowledge in deep layers. This article presents conditional memory as a complementary sparsity axis, covering its distinction from conditional computation, lookup constraints, capacity allocation, effective depth, training and deployment trade-offs, evaluation, and rollout guidance for LLM teams.

    Stacking more parameters into more experts does not automatically solve the fact that a model is, in part, memorizing knowledge. The current mainstream sparsity path is conditional computation: dynamically select a subset of parameters for the forward pass according to the input, so total parameter count can rise while per-inference computation remains controlled. This path expands “callable computation capacity,” not “directly addressable static memory.” Many entities, fixed collocations, local grammar patterns, and code idioms are written into the weights during training, yet at inference time they still have to be reconstructed step by step through multiple layers of attention and feed-forward networks. Reconstruction can work, but the cost is that shallow depth is occupied by knowledge restoration, leaving less effective depth for compositional reasoning. Latency and activation memory also rise unnecessarily.

    Conditional memory is meant to add the missing sparse axis: for knowledge that can be decided locally, use near-constant-time lookup instead of repeated computation, and make it complementary to conditional computation rather than a replacement.

    Two Kinds of Sparsity Solve Different Problems

    Conditional computation answers: “Which block of parameters should be used for this computation?” A routing network selects experts based on the hidden state. This suits computation that requires contextual composition, long-range dependencies, and multi-step transformations. Its benefit comes from parameter scale; its cost comes from routing, communication, and matrix multiplication in the activated experts.

    Conditional memory answers: “Can this specific, already-determined piece of local knowledge be retrieved directly this time?” Typical objects include high-frequency token-piece combinations, fixed definitions of domain terms, syntactic constraints that are almost decidable within a short window, and factual fragments that can be recalled without long context. If such information continues to be simulated by deep networks as retrieval, it is equivalent to using expensive dynamic computation to approximate a table that could have been looked up.

    The boundary between the two can be drawn by asking whether the information depends on the global hidden state. Cases that strongly depend on the current long context and require multi-hop composition should be left to the computation path; cases that can be indexed within a limited window are better suited to the memory path. Engineering practice should not aim to convert all knowledge into lookup tables. Otherwise, tables will expand, conflicts will increase, and dynamic reasoning capability will be bypassed too early.

    Constraints a Lookup Primitive Should Satisfy

    A usable conditional memory module should satisfy at least four constraints at the same time.

    First, the time complexity should be approximately constant with respect to sequence length, or linear in window width, and independent of model depth. In practice, local N-grams or equivalent short-window features are often used as keys, mapped through hashing to an embedding table, and added to the current layer representation according to hit weights. In this way, the extra cost per token is mainly a few hashes, table lookups, and vector additions, rather than another large matrix layer.

    Second, the key space must be extensible, but it should not require the vocabulary to grow on the same order as the corpus. A raw N-gram vocabulary would explode combinatorially. Modern approaches use hierarchical hashing, multi-hash voting, or low-conflict bucketing to compress rare combinations into a fixed-capacity table. When capacity is insufficient, the symptom is collisions rather than an immediate inability to train. Collisions are a design parameter, not an implementation accident: multiple tables, learnable gating, and residual scaling should be used to keep the impact of incorrect hits within a learnable range.

    Third, lookup must be differentiable or stably trainable. If a hit is a hard index, backpropagation can update only the rows that were hit. If gating is introduced, the gate itself should use the hidden state to decide whether to trust the table, preventing noisy embeddings from misleading early training. Gate initialization should be conservative, allowing the network to converge first on the existing computation path and then gradually increasing the weight of the memory branch.

    Fourth, the memory branch and the backbone must be comparable under equal budgets. When comparing “is it stronger with memory added,” total parameter count, per-forward computation, and training-token budget should be locked. Reporting only that “scores are higher because there is an extra table” is meaningless, because that is merely adding parameters. A fair comparison is to turn the same number of parameters either into more experts or wider feed-forward layers, or into a static memory table, and then see which performs better on validation and downstream tasks under the same FLOPs.

    The schematic structure below expresses only the data flow; it is not an interface for any specific implementation:

    1. def conditional_memory(token_ids, hidden, tables, gates):
    2. # short-window features -> multiple hash buckets -> embedding sum -> gated residual
    3. keys = ngram_keys(token_ids, widths=(2, 3))
    4. mem = 0
    5. for table, width_keys in zip(tables, keys):
    6. idx = hash_buckets(width_keys, num_buckets=table.size(0))
    7. mem = mem + table[idx].sum(dim=1)
    8. alpha = sigmoid(gates(hidden)) # decide acceptance by layer and channel
    9. return hidden + alpha * mem

    Hash functions, bucket counts, window widths, and which layers receive gates are all hyperparameters. They affect collision rate and gradient sparsity. There is no “best constant” independent of the data distribution.

    How to Allocate Capacity: The Trade-off Between Computation and Memory

    Divide the total sparse budget into two parts: one for dynamic experts and one for static tables. Empirically, this curve is often not monotonic. If the memory share is too low, the model still repeatedly reconstructs local knowledge in shallow layers, and reasoning depth is squeezed. If the memory share is too high, dynamic computation is insufficient, and long-range composition, mathematical transformations, and complex code control flow can degrade. Somewhere in the middle there is a more suitable ratio, shaped roughly like a U or a bowl: both ends are worse, and the middle is better.

    Therefore, sparse allocation itself should be treated as a modeling problem, not as a table size chosen just before launch. Under the same data recipe, run a small-scale grid: fix total parameters and target FLOPs, scan the memory parameter ratio, observe relative changes in three classes of metrics — knowledge recall, multi-step reasoning, and long-context stability — and then extrapolate the ratio to larger scales. During extrapolation, monitor the hash collision rate as well: if the same undersized buckets are reused after scaling up, the memory budget is being wasted on collisions.

    Do not report improvement points for specific tasks without evidence from a reproduced experiment under the same setting. In the literature and internal experiments, knowledge-oriented questions often improve first, while reasoning, code, and math sometimes improve more noticeably. This is not contradictory: the memory branch removes part of the shallow reconstruction burden, so deeper layers can be used more for variable binding, search, and symbolic operations. If your bottleneck is long-context retrieval or tool-call planning, short-window lookup alone will not automatically solve it; you still need attention and external retrieval.

    Why It May Increase “Effective Depth”

    The nominal number of layers stays the same, but effective depth changes. If the first several layers are mainly doing “turning local co-occurrence into semantics,” their marginal contribution to complex reasoning is limited. Once local dependencies are delegated to lookup, the same layers can enter compositional computation earlier. This is not magic; it is a division of labor in the computation graph: tables handle high-confidence, low-composition mappings; matrices handle low-confidence, high-composition transformations.

    For analysis, use two types of probes rather than looking only at the aggregate leaderboard. One is inter-layer representation similarity: after the memory branch is enabled, do shallow layers repeat the same local patterns less? The other is an intervention experiment: when the memory branch is masked, the drop on knowledge questions should be larger than on questions requiring multi-hop reasoning. Conversely, if all questions collapse together, gating has failed to restrict the branch to where it should be used, and the module is leaking shortcuts.

    Engineering Considerations During Training and Inference

    Data and token pieces. When keys come from a token-piece sequence, changing the tokenizer invalidates the entire table. The memory module should be versioned together with the tokenization scheme. A table cannot be hot-updated alone without retraining the gates.

    Collisions and bias. When hashing merges rare N-grams into popular buckets, the table becomes biased toward high-frequency patterns and can worsen forgetting of long-tail entities. Multiple independent hash tables, frequency-tiered tables, and higher dropout for low-frequency buckets are common mitigations. Monitor bucket utilization: many empty buckets indicate wasted capacity, while a few extremely hot buckets indicate severe collisions.

    Numerical stability. Memory vectors are added directly to the residual stream, so their scale should match the hidden state at that layer. Learnable scaling can be used, with the branch output initialized close to zero. If mixture-of-experts already has a load-balancing loss, do not add an overly strong memory sparsity penalty; otherwise the two routing mechanisms will compete for gradients.

    Communication and memory access. When tables are large, the bottleneck shifts from compute to memory bandwidth and cross-device table lookup. On the inference side, hot tables should be placed in memory tiers close to compute, while cold tables can be swapped out. On the training side, avoid irregularly gathering large numbers of embedding rows for each token; otherwise the kernel will be dominated by indexing overhead. Fusing lookup into token embeddings or shallow layers is often more cost-effective than looking up once at every layer, unless experiments show that middle layers still contain local patterns that can be matched.

    Difference from external retrieval. Conditional memory is an in-parameter, training-updated static prior. It has low latency and does not allow direct editing of a single fact. External retrieval is an out-of-parameter, updatable document store. It has higher latency and is governable. When facts expire and sources need auditing, use an external knowledge base. When patterns are stable and invoked very frequently, use internal memory. The two can coexist: internal tables handle lexical patterns and short facts, while external systems handle long documents.

    For deployment, object storage is suitable for version-frozen embedding tables, while a container platform can handle multi-replica inference. Logs and monitoring alerts should expose collision rate, mean gate value, table hit entropy, and branch output norm. These are generic operational signals and do not depend on any one vendor’s proprietary interface.

    How to Evaluate Without Fooling Yourself

    At minimum, report the following together: comparisons under the same parameter count, the same training FLOPs, and the same activated parameters; results separated into knowledge, reasoning, code, math, and long context rather than a single overall score; an ablation with the memory branch on and off; a curve across different memory ratios to test whether a middle optimum really exists; and whether metrics remain stable as the number of hash buckets changes.

    If only the aggregate score improves and budgets are not aligned, the conclusion should be treated as a capacity effect. If knowledge rises while reasoning falls, allocation has crossed the optimum, or gating has replaced middle-layer computation. If shallow gates remain close to zero for a long time, the table is not being used, and continuing to enlarge it only increases memory usage.

    First validate on a small model whether “short-window lookup can reduce shallow reconstruction,” using probes rather than immediately running the full leaderboard. Then scan the memory ratio to find the inflection point between computation and memory. Next, fix the inflection point, expand table capacity, and monitor collisions. Only after that should the module be placed into a training recipe jointly with mixture-of-experts, while keeping activated computation no higher than the baseline. Change one factor at a time at each step; otherwise it is impossible to tell whether gains come from memory itself or from more training steps or a different data mix.

    Conditional memory is not another parameter block that must be stacked on; it is an independent sparse axis: remove directly lookupable local knowledge from forced simulation through computation, and reserve depth for the parts that genuinely require composition. With good allocation, knowledge and reasoning can benefit at the same time. With poor allocation, it is just a more expensive embedding table.