Extending GPU Memory with CPU RAM: A Deep Dive into Conditional Memory and Scalable Lookup Techniques

    This article explains how conditional memory with scalable lookup can turn CPU RAM into a usable "second-tier memory" for large language models. It covers the motivation behind external memory, the core design of the Engram mechanism, its system architecture and data path, a simplified prototype implementation, practical engineering considerations, a comparison with alternative approaches, and the limitations to keep in mind. If you are building LLM inference services and struggling with KV cache and VRAM costs, this design offers a concrete architectural direction.

    1. Background: Why LLMs Need External Memory

    As model parameter counts and context lengths keep growing, GPU memory capacity has become the most direct cost bottleneck in inference deployments. Beyond the model weights themselves, the KV cache grows linearly with context length. In multi-turn conversations, long-document understanding, and code completion scenarios, it is easy to exhaust VRAM.

    The industry’s mainstream responses fall into three categories:

    1. Model-side compression: quantization, sparse attention, and context compression to reduce per-token memory usage;
    2. System-side scheduling: batch scheduling and preemptive request management, trading throughput for availability;
    3. Storage tiering: placing some data in CPU memory or fast storage media and fetching it on demand.

    The third approach has long been constrained by PCIe bandwidth and latency, and was considered “only suitable for infrequently accessed data.” However, a recent paper from a research team in collaboration with a university, “Conditional Memory via Scalable Lookup,” offers a different answer: since CPU memory is large in capacity and its bandwidth keeps improving, why not explicitly place a portion of “memory” on the CPU side and use an efficient lookup mechanism to make it nearly as usable as GPU memory? The proposed mechanism is named Engram (borrowed from the psychology concept of a “memory trace”), and is regarded as one of the key technical foundations that next-generation large models may adopt.

    2. Core Idea: Decoupling Knowledge from the Computation Graph

    In a traditional Transformer, all knowledge is encoded in dense weight matrices. The problem: whether or not a piece of knowledge is relevant to the current input, it still occupies VRAM and participates in computation. The conditional memory approach is:

    • Model weights retain only “general capabilities” and can be relatively small in scale;
    • Large amounts of knowledge, facts, and long-context information go into an external, retrievable memory store;
    • At inference time, the model dynamically decides which memory entries to retrieve based on the input, loading only what is truly needed onto the GPU for computation.

    This is essentially a “compute-storage decoupling” design. In database terms, the weights are like hot data resident in memory, while the memory store is like cold data on disk, paged in via an index. The difference is that the “index” and “retrieval” here are learned by the neural network itself rather than hand-engineered.

    3. Engram’s Key Design: Scalable Lookup

    For this idea to work, three engineering challenges must be solved:

    1. Retrieval latency: if every lookup requires heavy computation on the CPU, inference speed will suffer;
    2. Bandwidth pressure: moving large volumes of memory entries from CPU memory to the GPU may bottleneck on PCIe bandwidth;
    3. Training alignment: the model must learn during training “when to look up, what to look up, and how to use it”; otherwise, retrieved content becomes noise at inference time.

    The paper’s solution can be summarized as “conditional + scalable lookup”:

    • Conditional: not every token triggers retrieval. A lightweight gating module decides whether external memory is needed for the current step and which keys to retrieve. This dramatically reduces the average number of lookups.
    • Scalable lookup: the memory store’s organization and retrieval are designed as approximate-nearest-neighbor-style operations that run efficiently in CPU memory and support sharded scaling across multiple nodes. The GPU side only needs to receive a small number of Top-K results, which are then fused through the attention mechanism.

    An intuitive analogy: instead of “attending over the entire context,” the model “checks the table of contents first, then reads a few pages closely.” It no longer needs to load the entire book into VRAM.

    4. Using the CPU as GPU Memory: Architecture and Data Path

    From a system architecture perspective, the data path looks roughly like this:

    1. Input tokens
    2. |
    3. v
    4. GPU: first few backbone layers -> generate query vector q (gate decides whether to retrieve)
    5. |
    6. v
    7. CPU: memory store (key-value table resident in main memory, sharded)
    8. | |- Approximate nearest neighbor search (Top-K)
    9. | |- Results packed into a sparse batch
    10. v
    11. GPU: Top-K key-values returned -> attention fusion with q -> continue subsequent layers

    The benefits:

    • CPU main memory capacity is typically far larger than GPU VRAM, and can hold far more memory entries than the VRAM limit allows;
    • The query vector and Top-K results are much smaller than the full memory store, so PCIe transfer volume stays manageable;
    • With a sharded memory store, capacity can scale nearly linearly without requiring a single machine with enormous VRAM.

    Note that “using the CPU as GPU” does not mean running matrix multiplications on the CPU. Instead, CPU memory acts as a “second-tier VRAM” for the GPU, allowing the GPU’s attention computation to transparently access information beyond VRAM capacity.

    5. Illustrative Implementation: A Minimal Retrieval-Fusion Prototype

    The following pseudocode illustrates the core flow (conceptual demo only, not the paper’s actual implementation):

    1. # GPU side
    2. hidden = backbone_layers(tokens) # regular forward pass
    3. q, gate = query_head(hidden) # generate query and gate
    4. if gate.max() > THRESHOLD: # conditional trigger, not every step
    5. # CPU side: key-value memory store in main memory, sharded approximate search
    6. keys, values = memory_store.ann_search(q, top_k=K)
    7. # Results returned to GPU for sparse attention fusion
    8. mem_out = attention(q, keys, values)
    9. hidden = fusion(hidden, mem_out)
    10. logits = output_head(hidden)
    1. # Simplified CPU-side memory store structure
    2. class MemoryStore:
    3. def __init__(self, shards, dim):
    4. self.shards = [ANNIndex(dim) for _ in range(shards)]
    5. def ann_search(self, q, top_k):
    6. # Search all shards in parallel, then merge Top-K
    7. results = [s.search(q, top_k) for s in self.shards]
    8. return merge_topk(results, top_k)

    6. Engineering Practice Considerations

    To deploy a similar mechanism in production, focus on the following issues:

    1. Balancing retrieval quality and speed. Approximate nearest neighbor search involves a trade-off between recall and latency. The larger the memory store, the more you need quantization and hierarchical indexes to control per-query cost. In practice, tiered indexes are typically built for memories of different heat levels and types.

    2. Training the gating policy. A loose gate leads to frequent retrieval and higher latency; a tight gate makes the memory useless. Curriculum-style training helps: first let the model rely heavily on memory, then gradually tighten the threshold. Also introduce random “retrieval unavailable” masks during training so the model can still produce sensible output when memory is missing.

    3. Writing and updating memory. In long or multi-turn tasks, you must decide which intermediate states get written to the store and when old entries are evicted. You can borrow cache eviction policies (e.g., LRU, frequency-aware) or attach time-decay scores to memory entries.

    4. Consistency and versioning. The memory store evolves over time, and multi-replica deployments must guarantee consistent retrieval results. A common approach is to attach version numbers or snapshots to memory entries and read from a single snapshot.

    5. Hardware-aware deployment. PCIe bandwidth, NUMA topology, and CPU memory bandwidth all affect real-world gains. It is recommended to pipeline memory retrieval with GPU computation: prefetch the next batch of candidate results while the current layer is computing, hiding transfer latency.

    6. Evaluation metrics. Beyond standard task accuracy, monitor: average retrievals per token, Top-K hit rate, end-to-end latency distribution, and bytes transferred between CPU and GPU. These metrics directly determine whether the approach is cost-effective.

    7. Comparison with Traditional Approaches

    Approach VRAM usage Long-context scalability Main cost
    Full-attention KV cache High, grows linearly Poor Inference cost rises with length
    KV cache offloaded to CPU Medium Medium Paging thrashing, unstable latency
    Conditional memory + scalable lookup Low (only Top-K resident) Good Retrieval system complexity, training difficulty
    Retrieval-augmented generation (external docs) Low Good Depends on external retriever, coarse-grained fusion

    What makes conditional memory distinctive is that retrieval and fusion are end-to-end learnable: the model itself learns to construct queries, select memories, and fuse results, without requiring a separate retrieval pipeline and cumbersome prompt stitching.

    8. Limitations and Risks

    To be clear, this is no silver bullet:

    • Training complexity rises significantly; the gating and retrieval modules require careful tuning to converge;
    • Strong hardware dependency: gains may be limited in low-bandwidth environments such as single consumer-grade GPUs;
    • Weak interpretability and controllability of memory content; when debugging, it is hard to tell whether retrieval or fusion went wrong;
    • If the memory store contains sensitive information, additional permission and data-masking mechanisms are needed.

    9. Conclusion

    The real meaning of “using the CPU as GPU” is turning cheap, high-capacity main memory into a usable carrier of knowledge and context for the model through conditional retrieval and tiered storage. The Engram-style scalable lookup mechanism demonstrates a realistic path around the VRAM wall: not by making the CPU do general-purpose computing, but by letting the GPU’s attention reach, on demand, far more information than VRAM can hold. For engineering teams building LLM inference services and struggling with KV cache and VRAM costs, this design is a valuable reference direction for architectural evolution.