LLM Architecture

Offloading FFN Memorization to Lookup Tables: PLE, STEM, Engram, and PCIe Prefetch

Contents
  1. 1. Architectural Evolution: PLE, SCONE, STEM, and Engram
  2. 2. Host-RAM Offloading Arithmetic: Asynchronous PCIe Prefetch vs. Two Ceilings
  3. 3. Practical Scope, Engineering Costs, and Open Directions
  4. References

When an LLM is compressed down to an edge-sized $3\text{B}\text{–}4\text{B}$ checkpoint or shrunk via weight-tied looping, core syntactic fluency tends to hold up far better than factual recall—multi-word entity attributes, fixed idioms, and encyclopedic associations erode first. FFN matrices account for roughly $80\%$ of non-embedding weights ($\sim 80.8\%$ in LLaMA-3 8B) because standard Transformers use dense MLP projections simultaneously for general nonlinear reasoning and as a static key-value bookshelf. Cutting independent layer weights shrinks that factual storage along with compute capacity.

Because general algebraic reasoning and static pattern lookup exhibit fundamentally different computational structure, Conditional Memory acts as a separate sparsity axis—stripping static factual lookup out of expensive tensor-core matrix multiplies and offloading it into large, cheap embedding tables. From Gemma 3n PLE ([262144, 256] int8 tables × 30 layers $\approx 2.01\text{B}$ offloaded params streaming $\sim 8\text{K}$ params/token) to DeepSeek-V4.1-Flash (552B + 196B Engram) and LongCat 2.0 (135B N-gram table), offloading lexical memory frees early backbone depth while introducing tight PCIe prefetch and optimizer-residency bounds.

Note

Why decoupling lookup helps reasoning: Offloading early lexical and phrase reconstruction out of FFN/Attention frees early backbone capacity for compositional routing and multi-hop retrieval—for example, Engram at 27B scale reports multi-query needle-in-a-haystack (MQ-NIAH) accuracy rising from $84.2 \to 97.0$.


1. Architectural Evolution: PLE, SCONE, STEM, and Engram#

Across coverage granularity, collision control, and insertion site in the forward graph, lookup-augmented memory has evolved along four distinct designs:

  1. Per-layer token-ID lookup: PLE (Per-Layer Embeddings, Gemma 3n): The simplest strategy maintains an independent embedding table $E^{(\ell)} \in \mathbb{R}^{V \times d_e}$ per layer, looking up $e_t = E^{(\ell)}[\text{token\_id}]$ directly from the token index and gating it back into the residual stream. Why not simply widen the Layer-1 embedding and residual highway by $4\times$? Widening the residual stream $d \to 4d$ forces every Attention ($Q,K,V,O$) and FFN ($W_g, W_u, W_d$) projection across all layers to scale quadratically by $4 \times 4 = 16\times$ in parameters and FLOPs, whereas PLE adds narrow per-layer lookups with virtually zero GEMMs. To handle polysemy—where the same token_id "Newton" fetches identical rows in "a force of 10 Newtons" vs. "what year was Newton born"—context-dependent gating modulates how strongly the static lookup vector injects into the stream. As for why 2017-era cloud Transformers skipped PLE, datacenter clusters had abundant HBM relative to modest vocabularies ($V \approx 32\text{K}$); on mobile devices (Gemma 3n) with $V = 262{,}144$ and $2\text{–}4\text{ GB}$ RAM budgets, streaming per-layer tables from Flash or CPU RAM becomes high-leverage. Single token_id indexing still struggles with multi-subword entities such as "New York Times", whose phrase identity spans multiple subwords.

Pairing PLE with weight-tied looped Transformers exposes a clean "shared living room vs. private safe" division: external nn.ModuleList cartridges (ple_tables) sit outside the tied shared_block, receiving sparse row gradients strictly on active token_id entries per pass while the shared block handles structural reasoning:

PYTHON
class LoopedModelWithPLE(nn.Module):
    def forward(self, ids, h, num_loops):
        for t in range(num_loops):
            e_t = self.ple_tables[t](ids)  # per-pass lookup
            h = self.shared_block(h + self.gate(h, e_t))
        return h

One hard engineering limit applies: because ple_tables[t] is indexed by fixed loop step t, test-time unrolling cannot extrapolate cleanly past the trained num_loops without running out of pass-specific cartridges.

  1. Precomputed phrase embeddings: SCONE (Yu et al., 2025): To inject multi-token contextual meaning into static tables, SCONE precomputes contextualized representations for frequent f-grams using an auxiliary model and stores them inside an expansive host-memory lookup index. Fetching and fusing those embeddings during inference lets a model with 1B GPU-resident parameters beat a 1.9B dense baseline at roughly half the inference FLOPs, at the cost of maintaining an auxiliary precomputation pipeline and static frozen table semantics.
Original figure (Yu et al., 2025, Fig. 1): SCONE precomputing contextualized f-gram embeddings with an auxiliary model and offloading the table to host memory for lookup during main-model inference (arXiv:2502.01637).
Figure 1: SCONE precomputing contextualized f-gram embeddings with an auxiliary model and offloading the table to host memory for lookup during main-model inference (arXiv:2502.01637). (Source: Yu et al., 2025, Fig. 1)

In the "to be, or not to be" trace above, input tokens are grouped into frequent f-grams (such as <or> <not> <to>), encoded offline by the auxiliary Embedding Transformer into a precomputed offloaded embedding table, and looked up during main-model inference.

  1. Replacing FFN up-projections in place: STEM (Sadhukhan et al., 2026): Rather than injecting a parallel residual branch, STEM alters the SwiGLU operator itself—eliminating the dense up-projection matrix $W_\ell^{(u)}$ entirely in favor of a token-indexed layer embedding $U_\ell[t] \in \mathbb{R}^{d_{\text{ff}}}$:

$$\mathbf{y}_\ell = W_\ell^{(d)} \left( \mathrm{SiLU}\big(W_\ell^{(g)} \mathbf{x}_\ell\big) \odot U_\ell[t] \right)$$

This drops roughly one-third of FFN parameters and arithmetic multiplies while localizing factual memory into explicit editable rows $U_\ell[t]$, though it remains restricted to single-token keys.

Original figure (Sadhukhan et al., 2026, Fig. 2): Comparison of SwiGLU FFN, MoE FFN, and STEM, which replaces the dense FFN up-projection $W^u$ with a CPU-offloaded token-indexed embedding table $u_T$ (arXiv:2601.10639).
Figure 2: Comparison of SwiGLU FFN, MoE FFN, and STEM, which replaces the dense FFN up-projection $W^u$ with a CPU-offloaded token-indexed embedding table $u_T$ (arXiv:2601.10639). (Source: Sadhukhan et al., 2026, Fig. 2)

Comparing panels (a) SwiGLU FFN, (b) MoE FFN, and (c) STEM shows that STEM removes the dense $W^u(\cdot)$ projection from (a) and multiplies $\mathrm{SiLU}(W^g(\cdot))$ directly by $u_T$ fetched from the CPU Embedding Table before applying $W^d(\cdot)$.

  1. Multi-head N-gram hashing + context gating: Engram (DeepSeek-AI & Peking University, 2026): Indexing arbitrary 2-gram and 3-gram phrases without auxiliary precomputation runs straight into combinatorial $|\mathcal{V}|^3$ table explosion; replacing exact tables with modular hashing fixes memory size yet introduces hash collisions that inject unrelated noise into the residual stream. Engram addresses both issues in three coordinated steps:

$$\begin{aligned} e_t &= \mathrm{Concat}_{n,k}\!\big(E_{n,k}[h_{n,k}(g_{t,n}) \bmod M_{n,k}]\big), \\ \alpha_t &= \sigma\!\left(\frac{\mathrm{RMSNorm}(h_t^{(l)})^\top \mathrm{RMSNorm}(W_K e_t)}{\sqrt{d}}\right), \\ \tilde{v}_t &= \alpha_t W_V e_t, \quad u_t = \mathrm{CausalConv1D}\!\big(\mathrm{RMSNorm}(\tilde{v}_t)\big), \\ h_t^{(l+1)} &= h_t^{(l)} + \mathrm{SiLU}(u_t) + \tilde{v}_t \end{aligned}$$

Original figure (DeepSeek-AI & Peking University, 2026, Fig. 1): Engram architecture combining multi-head 2-gram/3-gram hash lookups, hidden-state scaled dot-product gating, and short convolution ahead of Attention and MoE (arXiv:2601.07372).
Figure 3: Engram architecture combining multi-head 2-gram/3-gram hash lookups, hidden-state scaled dot-product gating, and short convolution ahead of Attention and MoE (arXiv:2601.07372). (Source: DeepSeek-AI & Peking University, 2026, Fig. 1)

Walking through the concrete example "Only Alexander the Great could tame the horse Bucephalus ." in the diagram: the zoomed Engram block hashes the 2-gram (the Great) and 3-gram (Alexander the Great) across $h$ Hash heads into 2-Gram and 3-Gram Embedding tables, concatenates them, runs two Linear projections ($W_K, W_V$) with Scaled Dot Product gating against Input Hidden, and passes through Conv ahead of Attention and MoE (note that the diagram depicts this concrete "Alexander the Great" path while abstracting away the inner $\tilde{v}_t$, RMSNorm, and SiLU steps written in the equations).

Comparing MoE, PLE, and Engram side by side highlights how addressing determinism separates static lookup from dynamic compute routing:

DimensionSparse MoEPer-Layer Lookup · PLEN-gram Lookup · Engram
Lookup Key & ScopeDynamic router over expertsSingle token_id per layerMulti-head N-gram hash + gating
Addressing TimeAfter Router(h) per layer100% deterministic at $t=0$ ms100% deterministic at $t=0$ ms
Compute & PlacementHeavy GEMMs; pinned in HBMNear-zero GEMM; RAM/Flash offloadGate + short conv; Host-RAM offload
Primary TradeoffScales capacity; EP comm boundEdge lexical boost; no subword spanAbundant host DDR; repeat overfitting

2. Host-RAM Offloading Arithmetic: Asynchronous PCIe Prefetch vs. Two Ceilings#

Evicting tens of gigabytes of static lookup tables out of scarce GPU HBM into plentiful CPU Host RAM raises an immediate systems concern: won't fetching weights across the PCIe bus stall GPU execution on every forward step?

Static lookup memory enjoys a critical scheduling advantage over sparse MoE: zero-millisecond deterministic addressing. An MoE layer cannot determine which experts to fetch until layer $\ell$'s gating projection Router(h) finishes computing dynamically inside the forward pass. By contrast, Engram and PLE table indices depend strictly on input token_ids and fixed hash functions—meaning every host-RAM byte offset across the forward pass is known completely at millisecond zero before Layer 1 executes.

Original figure (DeepSeek-AI & Peking University, 2026, Fig. 2): Engram execution pipeline showing All2All communication at training vs. asynchronous host-RAM prefetch overlapped with on-device early-layer computation at inference (arXiv:2601.07372).
Figure 4: Engram execution pipeline showing All2All communication at training vs. asynchronous host-RAM prefetch overlapped with on-device early-layer computation at inference (arXiv:2601.07372). (Source: DeepSeek-AI & Peking University, 2026, Fig. 2)

As illustrated above, distributed training (left) exchanges sharded table entries across ranks via All2All, whereas inference (right) forks immediately from Input IDs: On Device Computation advances through the embedding and initial Transformer blocks concurrently with On Host Communication fetching from Offloaded Engram for downstream layers.

Placing the lookup module at slightly deeper layers (such as layer 2 onward) allows the runtime to overlap host-memory gathers and PCIe transfers behind earlier layers' dense GEMMs. With $T_{\text{uniq}}$ unique queries in the batch (each fetching $K_{\text{hash}}$ slots totaling width $K_{\text{hash}} d_e$ in BF16 at 2 bytes), overlap requires the sum of random host DDR5 gather time $T_{\text{DDR5}}$ and PCIe wire time $T_{\text{wire}}$ to fit inside preceding GPU compute:

$$T_{\text{prefetch}} = T_{\text{DDR5}} + \frac{2 \cdot T_{\text{uniq}} \cdot K_{\text{hash}} \cdot d_e}{\mathrm{BW}_{\text{PCIe}}} \;\le\; T_{\text{compute}}(\text{preceding layers})$$

Evaluating both sides of that inequality across realistic serving topologies exposes where PCIe wire speed ends and host-DDR5 contention begins (using ~700 TFLOP/s achieved on H100 for the 2-layer compute shadow):

Two PyTorch pitfalls must be avoided when coding async prefetch. First, never call .pin_memory() inside the forward step. Second, never wrap torch.index_select(host_table, ...) inside with torch.cuda.stream(stream): expecting it to run asynchronously: because host_table and pinned_buf are CPU tensors, a CUDA stream context does not offload CPU indexing, so the Python main thread blocks synchronously on the DDR5 gather before layer1(layer0(x)) is even enqueued!

In production, enqueue asynchronous GPU compute layer1(layer0(x)) onto the default stream first (or run a dedicated C++ worker thread feeding a double-buffered pinned ring buffer), gather into pinned_buf while the GPU runs early layers, launch non_blocking=True H2D DMA on h2d_stream, and synchronize with a CUDA Event:

PYTHON
# 1) Enqueue async GPU compute on default stream first!
h = layer1(layer0(x))
# 2) CPU gathers into pre-pinned ring slot while GPU runs layer0/1
torch.index_select(host_table, 0, uniq_slots, out=pinned_buf)
with torch.cuda.stream(h2d_stream):
    gpu_slots.copy_(pinned_buf, non_blocking=True)
    h2d_done.record(h2d_stream)
torch.cuda.current_stream().wait_event(h2d_done)
h = engram_fuse(h, gpu_slots)

The runnable Python simulator below compares payload size, PCIe wire latency, DDR5 gather time, and 2-layer compute shadows across all five regimes:

PYTHON
# PCIe Gen5 H2D (50 GB/s) + DDR5 random gather (~15 GB/s base)
BW_PCIE, BW_DDR, BYTES_Q = 50.0e9, 15.0e9, 1024 * 2

def sim_ms(t_uniq, mode="base"):
    nb = t_uniq * BYTES_Q / (8 if mode == "tp" else 1)
    pcie = 25.0e9 if mode == "tp" else BW_PCIE
    ddr = 2.5e9 if mode == "dp" else BW_DDR
    return nb / 1024**2, nb / pcie * 1e3, nb / ddr * 1e3

cases = [
    ("Decode B=1 (1 rank)", 64, "base", 0.30),
    ("Prefill 8K (1 rank)", 8192, "base", 5.80),
    ("Prefill 8K (TP=8)", 8192, "tp", 0.80),
    ("Prefill 8K (DP=8)", 8192, "dp", 5.80),
    ("Prefill 100K (1 rank)", 100000, "base", 5.80),
]
for name, t_u, m, shadow in cases:
    mb, tw, tg = sim_ms(t_u, m)
    print(f"{name:22s}: {mb:6.2f}MiB wire={tw:4.2f}ms "
          f"ddr={tg:5.2f}ms shadow={shadow:.2f}ms")
Resource Dimension8B Dense Baseline4B Core + 4B External Lookup
Total Parameters$8\text{B}$Still $8\text{B}$ (relocated, not removed)
Active FLOPs / TokenFull $8\text{B}$ dense GEMMsDrops to $4\text{B}$ core; gate & conv negligible
Inference GPU HBMAll $8\text{B}$ pinned in HBM$4\text{B}$ core in HBM; $4\text{B}$ in Host RAM / Flash
Optimizer State$8\text{B} \times 16\text{ B/param}$Sparse updates, yet full $\mathcal{O}(M d_e)$ AdamW state or CPU async offload
Interactive Timeline · Engram PCIe Wire vs. TP8 Sharding & DP8 Contention
GPU Compute Shadow vs. CPU DDR5 Random Gather + PCIe Gen5 H2D GPU Shadow 300 μs PCIe / NVLink 2.6 μs (0.12 MiB @ 50 GB/s) DDR5 Gather ~12 μs random gather → Total ~15 μs
Unique T_uniq/rank 64 GPU Shadow (μs) 300 Hidden (<5% stall)
Figure 5: Compare TP=8 (shared input_ids split 1/8 + NVLink AllGather) against DP=8 (8 independent requests contending on shared host DDR5).

3. Practical Scope, Engineering Costs, and Open Directions#

Empirical scaling curves and deployment profiles point to two clear niches for static lookup tables: memory-constrained edge models and weight-tied looped Transformers (recovering lexical and entity capacity from Host RAM or Flash without enlarging dense core compute), and GPU-VRAM-limited serving nodes backed by abundant CPU system memory running asynchronous Engram prefetching. Yet scaling conditional memory into frontier pretraining and production serving exposes five concrete costs:

  1. One-Epoch (CTR-style) overfitting and zero weight decay: Massive sparse N-gram tables mirror deep CTR recommendation embeddings—rare slots hit only a handful of documents and lack the law-of-large-numbers averaging of dense weights, causing One-Epoch overfitting as soon as training corpora repeat. Worse, applying weight decay erodes rare factual entries, while turning weight decay off amplifies multi-epoch memorization fragility.
  2. 3-gram long-tail sparsity and placement fragility: 3-gram keys follow a far steeper Zipfian tail than 2-grams, leaving most buckets under-trained; insertion depth is also delicate—too early lacks semantic context for $\alpha_t$ gating, while too late misses early phrase offloading.
  3. Host RAM contention with KV Cache offloading: On production serving nodes, CPU DDR memory is shared with tiered KV offloading systems (Mooncake, LMCache), forcing a 135B–196B parameter Engram table (~270–392 GB in BF16, or 135–196 GB in FP8) to compete directly for host RAM capacity and memory bandwidth.
  4. Literal-miss sensitivity to paraphrasing (and Engram vs. RAG): Modular N-gram hashing triggers reliably on "New York Times", yet misses "that famous century-old Manhattan daily newspaper" or cross-lingual equivalents completely, forcing backbone attention to reconstruct equivalence from scratch. This also separates Engram from RAG for encyclopedic recall: Engram injects frozen, pretraining-time lexical and phrase priors directly into layer hidden states at sub-millisecond hardware latency without external corpus updates or source provenance, whereas RAG retrieves from a mutable external document index at millisecond-scale I/O cost with live freshness and verifiable citations—making the two complementary rather than interchangeable.
  5. Sparsity allocation U-curve and flattening returns past 30B–40B: Under iso-FLOP and iso-sparse-parameter budgets, DeepSeek-AI's Sparsity Allocation Law reveals a U-shaped validation loss curve where allocating ~75%–80% to routed MoE experts ($\rho \approx 75\text{–}80\%$) and ~20%–25% to static Engram tables beats Pure MoE ($\rho = 100\%$). At the same time, Flash Linear Attention (FLA) community scaling notes observe that once dense/MoE backbones exceed ~30B–40B parameters, FFN capacity already suffices so marginal gains from external N-gram tables flatten—though LongCat 2.0 (135B table), DeepSeek-V4.1-Flash (552B + 196B Engram), and X-GRAM (arXiv:2604.21724, frequency-aware dynamic injection into Value and residual streams) continue testing the frontier.
Original figure (DeepSeek-AI & Peking University, 2026, Fig. 3): Sparsity Allocation Law U-curve over MoE allocation ratio ρ (optimum at ρ≈75%–80%, leaving ~20%–25% to Engram) alongside log-scale slot scaling (arXiv:2601.07372).
Figure 6: Sparsity Allocation Law U-curve over MoE allocation ratio ρ (optimum at ρ≈75%–80%, leaving ~20%–25% to Engram) alongside log-scale slot scaling (arXiv:2601.07372). (Source: DeepSeek-AI & Peking University, 2026, Fig. 3)

In Engram's original Fig. 3 above, the left U-curves at both 2e20 and 6e20 FLOPs reach their minimum near $\rho \approx 75\text{–}80\%$ (the ~20–25% Engram / ~75–80% MoE split) below Pure MoE ($\rho=100\%$), while the right plot shows validation loss dropping log-linearly from $10^5$ to $10^7$ embedding slots ahead of Pure MoE and OverEncoding.

Two adjacent architectural branches target these exact constraints:

Where static lookup tables shine is unmistakable on 3B–4B edge checkpoints and shallow LoopLMs constrained tightly by the ~2 bits/param unique-weight memory ceiling; at 100B+ MoE scale, keeping them competitive against routed experts requires solving host-DDR contention with KV offloading and single-epoch repeat overfitting without breaking the millisecond-zero overlap window.


References#

  1. DeepSeek-AI & Peking University (2026). Conditional Memory via Scalable Lookup: A New Axis of Sparsity for Large Language Models (Engram). arXiv:2601.07372
  2. Ranajoy Sadhukhan, Sheng Cao, Harry Dong et al. (2026). STEM: Scaling Transformers with Embedding Modules. arXiv:2601.10639
  3. Da Yu et al. (2025). Scaling Embedding Layers in Language Models (SCONE). arXiv:2502.01637
  4. Google Developers (2025). Introducing Gemma 3n: The Developer Guide (Per-Layer Embeddings & MatFormer). developers.googleblog.com
  5. Jiale Kang (2026). Memory Attention. arXiv:2609.28399
  6. X-GRAM (2026). arXiv:2604.21724
Cite this note
@misc{liu2026externallookupmemo,
  title  = {{Offloading FFN Memorization to Lookup Tables: PLE, STEM, Engram, and PCIe Prefetch}},
  author = {Feiyang Liu},
  year   = {2026},
  month  = {nov},
  url    = {https://zaychikliu.github.io/blog/2026/external-lookup-memory-ple-engram/}
}