HyperAIHyperAI

Command Palette

Search for a command to run...

MemOnce: 대규모 언어 모델을 위한 확장 가능한 메모리 아키텍처

Chang Nie Chaoyou Fu Songlin Liu Yiqing Hu Caifeng Shan

초록

장기간의 연속적인 상호작용에서 대규모 언어 모델(LLM)을 배포하려면 향후 추론을 위해 재사용 가능한 메모리 상태를 유지해야 하며, 이는 기존 아키텍처에 여러 어려움을 제기한다. 표준 트랜스포머는 계층별·토큰 수준의 KV 캐시를 누적하므로 컨텍스트가 확장됨에 따라 GPU 메모리 사용량이 선형적으로 증가하고 계산 복잡도가 이차적으로 증가한다. 반면 선형 시간 아키텍처는 이력을 고정 크기 상태로 압축하지만 세부적인 정보를 유지하는 데 어려움을 겪는다. 본 논문에서는 언어 모델을 위한 확장 가능한 메모리 상태를 학습하는 기반 아키텍처인 MemOnce를 소개한다. MemOnce는 두 가지 핵심 설계에 기반한다: (a) 메모리 인코더-디코더: 최종 계층 은닉 상태의 일부만을 압축된 메모리 표현으로 캐시하고, 이를 어텐션 계층을 위한 KV 캐시로 동적으로 다시 디코딩한다. (b) 메모리 희소 어텐션: 각 연속 입력에 대해 MemOnce는 관련 메모리 표현을 적응적으로 검색하며, 희소 인덱스는 모든 계층에서 단 한 번만 계산된다. 이 두 설계를 결합함으로써 즉석 메모리 로딩과 KV 캐시 디코딩이 효율적으로 이루어져 GPU 메모리 사용량을 획기적으로 줄이고 선형 시간 복잡도를 달성한다. 광범위한 실험을 통해 MemOnce가 다양한 모델 크기, 컨텍스트 길이, 학습 패러다임(사전 학습 및 사후 학습 적응)에서 트랜스포머와 다른 아키텍처를 능가함을 보인다. 특히 Qwen3.5-4B를 MemOnce로 적응시키면 1M 컨텍스트에서 메모리 상태 캐시를 1313배, 프리필 지연 시간을 6.9배 줄이고, 처리량을 3.5배, 전반적인 메모리 성능을 +5.77% 향상시킨다. 마지막으로 MemOnce는 다운스트림 표현 과제에 제로샷으로 일반화되어 특화 모델에 필적하는 결과를 달성한다.

One-sentence Summary

Nanjing University and the University of Science and Technology of China introduce MemOnce, a scalable memory architecture for large language models that combines a memory encoder-decoder, which caches only a small subset of final-layer hidden states and decodes them back into KV caches, with memory sparse attention, which adaptively retrieves relevant memory representations and computes sparse indices once across layers, thereby achieving linear-time complexity and reduced GPU memory, outperforming Transformers across model sizes, context lengths, and training paradigms, and, when adapting Qwen3.5-4B, reducing memory state cache by 1313×1313\times1313× and prefill latency by 6.9×6.9\times6.9× at 1M context while improving throughput by 3.5×3.5\times3.5× and overall memory performance by +5.77%+5.77\%+5.77%.

Key Contributions

  • MemOnce introduces a memory encoder-decoder that stores a small subset of final-layer hidden states as compact reusable memory and decodes them back into attention-layer KV caches on demand. Its memory sparse attention retrieves relevant memory representations with sparse indices computed once across layers, yielding linear-time inference, reduced GPU memory footprint, and constant active memory states for continual language modeling.
  • In experiments, MemOnce outperforms Transformers and other memory architectures across model sizes, context lengths, and both pretraining and post-training adaptation. Adapting Qwen3.5-4B with MemOnce reduces memory state cache by 1313× and prefill latency by 6.9× at 1M context, while improving throughput by 3.5× and overall memory performance by +5.77%.
  • MemOnce generalizes zero-shot to downstream representation tasks with competitive results against specialized models and is presented as the first native memory model to surpass full-context baselines.

Introduction

As large language models shift toward continual interactions and long-horizon agent tasks, they need reusable memory states to avoid recomputing history and to maintain low-latency generation. Standard transformers retain layer-wise token-level key-value caches, which grow linearly with context and create quadratic attention cost; recurrent and linear models compress history into fixed-size states for constant memory but can lose fine-grained details. Prior hybrid, sparse, native-memory, and external-memory approaches still face linearly growing caches, performance degradation, retrieval overhead, or costly discrete stores that are difficult to optimize end-to-end. The authors propose MemOnce, which maintains a single compact global cache and retrieves relevant memory only once during continual inference, then decodes layer-wise KV caches on demand through a memory encoder-decoder and memory sparse attention, achieving linear-time inference and constant active memory.

Method

The authors introduce MemOnce, a foundation architecture designed to learn scalable memory states MtM_tMt​ for efficient continual inference. Formally, the framework constructs and utilizes the active memory state through three core functions: memory writing gθg_\thetagθ​, indexing iθi_\thetaiθ​, and reading uθu_\thetauθ​.

Gt=gθ(x1:t−1),Mt=iθ(xt,Gt),Ct=uθ(Mt)G_t = g_\theta(x_{1:t-1}), \quad M_t = i_\theta(x_t, G_t), \quad C_t = u_\theta(M_t)Gt​=gθ​(x1:t−1​),Mt​=iθ​(xt​,Gt​),Ct​=uθ​(Mt​)

MemOnce is instantiated through two primary designs: a memory encoder-decoder and memory sparse attention. In practice, the architecture adopts an L-stage hybrid backbone, where each stage interleaves three linear blocks with one Memory Sparse Attention block.

The memory encoder-decoder is designed to eliminate the storage bottleneck of multi-layer token caches by compressing historical context across both layer depth and sequence length. For the memory writing operation gθg_\thetagθ​, the model maintains a single global cache generated from final-layer hidden states. Given historical inputs, the interleaved linear blocks and causal attention aggregate sequential context, allowing the trailing token states to encapsulate the semantics of the entire segment. The memory encoder retains only the last 1/r1/r1/r fraction of token states from each segment, writing a total of k=⌊N/r⌋k = \lfloor N/r \rfloork=⌊N/r⌋ compact memory representations into the global cache:

Gt=Concat({hi,−ni/r:L}i=1t−1)=[m1,m2,…,mk]⊤∈Rk×DG_t = \mathrm{Concat}\left(\{h_{i, -n_i/r:}^L\}_{i=1}^{t-1}\right) = [m_1, m_2, \ldots, m_k]^\top \in \mathbb{R}^{k \times D}Gt​=Concat({hi,−ni​/r:L​}i=1t−1​)=[m1​,m2​,…,mk​]⊤∈Rk×D

This step reduces the persistent memory footprint by a factor of LrLrLr. For the reading operation uθu_\thetauθ​, instead of sharing identical KV states across layers, the memory decoder applies lightweight layer-specific MLP projections to decode the retrieved active memory state MtM_tMt​ into KV caches for all attention layers on demand:

Kl=KProjl(Mt),Vl=VProjl(Mt),l∈{1,…,L}K^l = K_{\mathrm{Proj}}^l(M_t), \quad V^l = V_{\mathrm{Proj}}^l(M_t), \quad l \in \{1, \dots, L\}Kl=KProjl​(Mt​),Vl=VProjl​(Mt​),l∈{1,…,L}

By projecting final-layer semantic representations back to all attention blocks, MemOnce establishes looped memory generation and utilization. This design allows the model to achieve comparable or lower validation perplexity compared to standard Transformers and strong baselines, even at high compression ratios.

To prevent linear growth in cache memory and attention compute when decoding the entire memory bank, the authors introduce memory sparse attention. This module retrieves relevant memory representations only once for each continual input and reuses them across layers. The persistent memory bank GtG_tGt​ is partitioned into a long-term memory pool and a short-term memory window. The short-term window retains the most recent representations to preserve local continuity, while the long-term pool stores distant historical states. Given the final-layer representation of the continual input, the indexing function iθi_\thetaiθ​ selects the top-K task-relevant memory states from the long-term pool:

Mtlong=Top-Kmi∈Gtlong(Sim(ϕ(htL),ϕ(mi)))M_t^{\mathrm{long}} = \mathrm{Top\text{-}K}_{m_i \in G_t^{\mathrm{long}}} \left(\mathrm{Sim}\left(\phi(h_t^L), \phi(m_i)\right)\right)Mtlong​=Top-Kmi​∈Gtlong​​(Sim(ϕ(htL​),ϕ(mi​)))

where ϕ(⋅)\phi(\cdot)ϕ(⋅) extracts and projects the last-token representation, and Sim(⋅,⋅)\mathrm{Sim}(\cdot, \cdot)Sim(⋅,⋅) computes cosine similarity. The retrieved long-term representations are concatenated with the short-term window to form the active memory state MtM_tMt​. Once decoded into layer-specific KV caches, each attention block prepends these decoded states to the current input's local key-value states for attention computation. Because the active subset size is bounded by a constant budget, MemOnce restricts the active memory state cache to O(CD)\mathcal{O}(CD)O(CD) while maintaining an expandable persistent bank.

MemOnce supports end-to-end optimization under the standard next-token prediction paradigm. During pretraining, the backbone and memory encoder-decoder are jointly optimized, with historical segments encoded in parallel and gradients flowing directly through the active memory state and decoded KV caches. During post-training adaptation, the backbone is frozen, and the authors optimize only the lightweight projections in the indexing and reading functions, alongside low-rank adapters activated exclusively during memory encoding. This approach equips pretrained large language models with native long-range memory capabilities without compromising their general task performance.

Experiment

The experiments evaluate MemOnce across four tracks: foundational language modeling and zero-shot reasoning, long-context memory recall from 4K to 1M tokens, general capability retention under memory load, and transferability of learned memory representations to retrieval and reranking. Compared with Transformer, cache-sharing, efficient attention, native memory, and specialized retrieval baselines, MemOnce maintains or improves foundational performance while compressing context caches, surpasses full-context baselines on long-context memory without catastrophic forgetting, and achieves linear-time prefilling with bounded GPU cache and steady decoding throughput. Its learned representations also transfer to retrieval and reranking, and ablations confirm that temporal compression and sparse retrieval preserve recall while reducing latency.

MemOnce achieves a strictly bounded memory state cache that stays constant with respect to layer depth and context length, while standard Transformers and YOCO store full-sequence states and GDN, SWA, and M+ keep layer-dependent states. Its prefilling time scales linearly with context length, avoiding the quadratic prefilling cost of standard Transformers and YOCO. Compared with other linear-time baselines, MemOnce offers the same linear prefill scaling but a much smaller persistent memory footprint. MemOnce has a constant-size memory state cache, unlike full-sequence caches in standard Transformers and YOCO and layer-dependent caches in GDN, SWA, and M+. MemOnce retains linear prefilling time, whereas standard Transformers and YOCO require quadratic prefilling time.

MemOnce variants lead the evaluated architectures on both language modeling and zero-shot common-sense reasoning, with the top two average accuracy scores and the lowest perplexities on WikiText-103 and LAMBADA. Among the other listed models, SWA and Transformer perform best on language modeling perplexity, while GDN records the highest average zero-shot accuracy. Linear and recurrent baselines such as DeltaNet trail the leading attention and memory architectures. MemOnce variants achieve the highest and second-highest average zero-shot accuracy and the best language modeling perplexities on WikiText-103 and LAMBADA. Among listed non-memory models, SWA and Transformer show the strongest language modeling perplexity, while GDN leads on average zero-shot accuracy. DeltaNet is the weakest listed model on average accuracy and LAMBADA perplexity, illustrating the limitations of the evaluated linear recurrent baseline.

Across five memory benchmarks spanning 4K to 1M tokens, MemOnce surpasses full-context Qwen3.5 baselines at both 2B and 4B scales, with a larger improvement at the 4B scale. Native fixed-state memory baselines fall far behind, especially on longer multi-session evaluations such as LoCoMo and LongMemEval. The pattern suggests MemOnce's retrieval and expandable state design avoids the representational bottlenecks that limit fixed-state memory models. MemOnce is the first native memory model to outperform full-context baselines across the evaluated context lengths. The gain over full-context baselines is larger at the 4B scale than at the 2B scale. Fixed-state native memory baselines show substantial drops on longer benchmarks, with several falling to single-digit or low double-digit scores on LoCoMo and LongMemEval. Full-context baselines lose accuracy on the 1M-token PersonaMem benchmark, while MemOnce's retrieval-based design is reported to mitigate attention dilution.

Under a 32K memory load, MemOnce preserves general reasoning essentially on par with the full-context Qwen3.5-4B baseline and achieves the highest general average among the evaluated approaches. δ-Mem also retains general accuracy, while model weight fine-tuning, soft-prompt injection, and some linear-state approaches lead to large accuracy declines. MemOnce obtains the best general average under a 32K memory load, narrowly surpassing both the full-context baseline and δ-Mem. Soft-prompt injection and some linear-state approaches show severe forgetting, falling far below the full-context baseline on general reasoning.

MemOnce is evaluated against dedicated embedding models on eight long-context and conversational retrieval benchmarks. It achieves the best overall Recall@10 and NDCG@10 with a compact 1024-dimensional representation, surpassing BGE-M3 and Qwen3-Embedding-4B. Gains are strongest on long-context benchmarks such as ESG-Reports, LoCoMo, and LongMemEval, while performance is less consistent on a few conversational or specialized query sets. MemOnce attains the highest overall retrieval quality among evaluated models, leading in both Recall@10 and NDCG@10. It outperforms dedicated embedding baselines while using a smaller descriptor size than Qwen3-Embedding-4B and the same compact dimension as BGE-M3. The largest gains appear on long-context retrieval tasks such as ESG-Reports, LoCoMo, and LongMemEval, while some conversational and COVID-specific benchmarks show closer or lower results.

MemOnce is evaluated across efficiency, language modeling, long-context memory, general reasoning, and retrieval tasks. The efficiency experiments show that MemOnce maintains a constant-size memory state cache and linear prefilling time, unlike full-sequence or layer-dependent baselines. In quality benchmarks, MemOnce variants lead on language modeling and zero-shot reasoning, outperform full-context Qwen3.5 at 2B and 4B scales on memory tasks spanning 4K to 1M tokens, preserve general reasoning under a 32K memory load, and achieve the best retrieval quality with compact 1024-dimensional representations.


AI로 AI 구축

아이디어에서 출시까지 — 무료 AI 코코딩, 즉시 사용 가능한 환경, 최적의 GPU 가격으로 AI 개발을 가속화하세요.

AI 협업 코딩
바로 사용 가능한 GPU
최적의 가격

HyperAI Newsletters

최신 정보 구독하기
한국 시간 매주 월요일 오전 9시 에 이번 주의 최신 업데이트를 메일로 발송합니다
이메일 서비스 제공: MailChimp