MemCode: Discrete Semantic Representations for Long-Term Agent Memory

Xin Li, Liang Hu, Duoqian Miao, Ming Peng, Qi ZhangNeurIPS 2026

TL;DR

Giving AI agents long-term memory usually means chopping chat histories into raw snippets and searching them by vector similarity—a recipe for lost context and missed logical connections. MemCode fixes this by rewriting messy dialogue into self-contained atomic facts and indexing them with both standard continuous vectors and a discrete, Hopfield-inspired "codebook" of semantic anchors. The result is an agent memory system that connects logically related but differently worded memories, beating state-of-the-art accuracy while building memories up to 21$\times$ faster.

What Problem Does This Paper Address?

Imagine keeping a diary by ripping random sentences out of your conversations and tossing them into a shoebox. Later, you pull out a slip that says, "Tomorrow she will do the same thing again." Who is "she"? When was "tomorrow"? What "thing"?

Most Retrieval-Augmented Generation (RAG) memory systems for LLM agents suffer from a fundamental write–retrieve mismatch:

  1. Weak storage units (What to write): Raw dialogue fragments depend heavily on surrounding context (pronouns, relative times). Conversely, aggressive summaries erase the fine-grained hooks needed for multi-hop reasoning.
  2. Geometric blindness (How to retrieve): Standard vector search finds memories that sound alike (surface similarity), systematically missing facts that are logically connected across sessions but phrased completely differently.
Figure 1: Traditional memory pipelines store raw dialogue fragments and retrieve them primarily by surface similarity. Ours rewrites dialogue into atomic memory units and retrieves them through complementary vector and codebook paths.

Inspired by how the human hippocampus separates similar inputs into distinct, sparse traces for associative recall, the authors ask: how can we jointly design what we write and how we index it so memories remain both self-contained and associatively linked?

Methods

MemCode retains the standard RAG loop (ingest $\rightarrow$ index $\rightarrow$ retrieve) and vector embeddings, but introduces three novel architectural upgrades alongside offline maintenance:

Overview of the MemCode architecture across ingestion, dual-path indexing, retrieval, and offline memory evolution.
  • Atomic Memory Units (AMUs): As dialogue streams in, an LLM rewrites each turn—using a tiny read-only window of the previous turn—into self-contained facts. Pronouns are resolved to speakers, relative times ("yesterday") are anchored to absolute timestamps, and pointers are saved back to the raw source utterances.
  • Isomorphic Semantic Quantization (ISQ): Alongside a standard dense vector, each AMU is passed through a custom VQ-VAE (Vector-Quantized Variational Autoencoder) to map tokens onto a finite, learnable codebook of discrete IDs—creating a compact "semantic fingerprint." Crucially, it uses a stride-1 projection (no downsampling) so vital tokens like dates and names aren't squashed away, and trains via predictive coding (predicting the next dialogue response rather than reconstructing input text) to capture reasoning cues over lexical noise.
  • Topology-Aware Dual-Path Retrieval: MemCode tracks how often discrete code IDs co-occur within AMUs across the entire memory store, forming an implicit association graph. At query time, Path A grabs high-precision vector matches, while Path B hops 1 step across the codebook co-occurrence matrix (weighted by Inverse Document Frequency to mute generic concepts) to pull in logically associated facts that vector search missed. Source pointers then reconstruct the original dialogue spans in chronological order.
  • Asynchronous Consolidation: Offline and out of the user's way, MemCode clusters similar AMUs using hierarchical agglomerative clustering and uses an LLM to merge duplicates, aggregate multi-session arcs, or archive outdated states—forwarding source pointers so nothing is permanently lost.

Datasets

No new benchmarks are introduced; the authors strictly separate representation learning from evaluation:

  • Training (Offline Codebook): The VQ-VAE codebook is trained once on the official training split of DailyDialog (11,118 dialogues) to learn general conversational patterns, then frozen.
  • Evaluation: Tested incrementally (turn-by-turn) on two established long-term agent memory benchmarks: LongMemEval-S (~30–40 sessions, ~115K tokens per dialogue, stressing dynamic updates and multi-session recall) and LoCoMo (~305 turns, stressing multi-hop, temporal, open-domain, and single-hop QA).

Key Insights and Ideas

  • Throwing more vectors at a query doesn't fix multi-hop reasoning: Doubling the vector retrieval budget ($K=20 \rightarrow 40$) barely nudges accuracy (+1.4%) because dense search just scoops up near-duplicates from the same neighborhood. Spending that exact same extra budget on codebook associations jumps Multi-Hop accuracy by +5.3 points.
  • Compression kills memory hooks: Increasing the quantization stride (compressing multiple tokens into one code) tanks Temporal and Multi-Hop accuracy while leaving Single-Hop untouched—proving that exact dates, quantities, and entity IDs are load-bearing pillars of compositional memory.
  • Consolidation is a trade-off, not a free lunch: Offline merging boosts cross-session and multi-hop reasoning (up to +7.09 points), but slightly dips temporal precision because distinct timestamps get folded into broader [Time Span] intervals.

Key Results

Evaluated across two backbones (GPT-4o-mini and Qwen3-30B-A3B-Instruct-2507), MemCode achieves the best overall accuracy while slashing memory-construction latency:

  • LongMemEval-S: Reaches 78.40% (GPT-4o-mini) and 74.60% (Qwen3) overall accuracy with consolidation, beating the strongest baseline (LightMem) by nearly 10 and 13 percentage points, respectively. Speaker-grounded AMUs shine on Single-Assistant queries (92.86% vs. LightMem's 32.14%).
  • LoCoMo: Achieves 79.55% (GPT-4o-mini) and 76.88% (Qwen3) overall accuracy, outperforming Full-Text attention, Mem0, A-MEM, MemoryOS, and LightMem—and beating BM25, dense-sparse reranking, and HyDE under strict fixed-budget controls.
  • Blistering Construction Speed: Because turn-level AMU extraction runs in parallel (unlike sequential batch compression), MemCode builds a dialogue's memory in ~41–130 seconds—making it 3–21$\times$ faster than LightMem and 10–100$\times$ faster than A-MEM and MemoryOS, even on a modest consumer RTX 3050 Ti GPU.
Table 1: Accuracy and memory-construction cost on LongMemEval-S. We report Overall/category ACC (↑), runtime per dialogue (↓), Total Tokens, and Calls. Asyn. denotes asynchronous consolida- tion. Bold and underline denote the best and 2nd-best results within each backbone.

Limitations and Future Work

  • Subtext doesn't propositionalize neatly: On LoCoMo's Open questions—which probe implicit emotions, unspoken motivations, and mental states—stuffing the raw Full Text into the prompt still wins (56.25% vs. MemCode's 51.04%). Crisp atomic facts excel at who, what, and when, but flatten subtle human subtext.
  • Future Directions: Rather than scaling up vector dimensions or context budgets, the authors suggest future agent memory research should focus on richer semantic structures for stored units and smarter associative topologies.

Summary updated

Abstract

Long-term memory remains a fundamental bottleneck for large language model (LLM) agents across sessions. Existing systems typically adopt a write-then-retrieve paradigm, storing context-dependent dialogue fragments and retrieving them via nearest-neighbor search in continuous embedding space. This design yields unstable access units and systematically misses logically related but lexically distant evidence. We propose MemCode, a long-term agent memory framework that couples retrieval-oriented writing with discrete associative retrieval. MemCode rewrites dialogue into self-contained atomic memory units (AMUs), maps AMUs into a learnable codebook with isomorphic semantic quantization (ISQ), and uses codebook co-occurrence topology as a retrieval path complementary to vector search. For long-term memory stores, MemCode separates online atomic writes from asynchronous offline consolidation. On LongMemEval-S and LoCoMo with GPT-4o-mini and Qwen3-30B-A3B-Instruct-2507 backbones, MemCode achieves the best overall accuracy while keeping per-dialogue memory construction within roughly 40--130 seconds, making it 3--21$\times$ faster than LightMem and over an order of magnitude faster than A-MEM and MemoryOS.
BibTeX
@inproceedings{li2026memcode,
  author = {Xin Li and Liang Hu and Duoqian Miao and Ming Peng and Qi Zhang},
  title = {{MemCode: Discrete Semantic Representations for Long-Term Agent Memory}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=PYZcd99axs},
}
Figure