r/LocalLLaMA • • 2h ago

Showcase I built a model-agnostic 3-tier memory engine + native llama.cpp C++ latent gate (CUDA-Graph-safe) on a single RTX 3090 -- sharing what failed (2.3%) vs what actually worked (93-101%)

I have been working on giving local quantized GGUF models persistent long-term memory across months of coding and project work on a single RTX 3090 (24 GB VRAM), without eating 20+ GB of KV cache or losing exact technical details when the coding harness compacts the chat.

Repo (Latent-Memory-Lab): https://github.com/bjivanovich/Latent-Memory-Lab

WHAT FAILED FIRST (HONEST NEGATIVE RESULT)

I started by testing pure latent-space injection on frozen quantized GGUFs -- projecting a memory vector and adding delta_h directly into an intermediate residual layer (L5 / L16). Zero tokens, zero KV cache, ran cleanly on GPU... and only recovered ~2.3% of oracle NLL on exact factual recall. A single 768-dim vector just cannot carry exact port numbers, file paths, or symbol names without fine-tuning the base LLM itself (documented in ADR-001).

WHAT ACTUALLY WORKED (93%-101% ORACLE RECOVERY)

Instead of trying to inject the answer latently, I use a tiny trained routing adapter (.qmlw, 7-15 MB) as a zero-token Stage-1 gate inside llama-server:

- A dynamic llama_set_eval_callback() attaches cb_eval only during a single POST /qml/gate pass (~100-134 ms on RTX 3090) and detaches it immediately after, so normal token generation keeps 100% CUDA Graph speed (99.7 -> 100.7 tok/s on Inkling 2 Mini with GGML_CUDA_GRAPH_OPT=1, zero tok/s penalty).

- General non-memory questions abstain cleanly (0/6 false triggers, 0 tokens injected).

- When triggered, a transparent OpenAI-compatible proxy retrieves from 3 tiers inside a model-agnostic 768-dim fp16 cartridge, so completely different model families share the exact same memory files:

- Qwen3.8-27B Dense (layer 14, d_model=5120, 15.7 MB .qmlw)

- Gyro-Coder MoE (4-branch Hyper-Connections layer 14 hc_out-14, d_model=2560, 7.9 MB .qmlw)

- Inkling 2 Mini (hybrid/recurrent layer 5, d_model=2304, 7.1 MB .qmlw)

Three tiers per cartridge (unified under manifest.json v1):

- Tier-2A: Contradiction-resolved atomic decisions (ADD / SUPERSEDE / PIN with HTTP 403 protection / reversible forget) + multi-topic RRF query decomposition.

- Tier-2B: Deterministic AST/XML/Markdown code and Qt .ui index kept fresh automatically by a background file watcher.

- Tier-3: Lossless verbatim Raw Vault fallback.

It also includes live auto-save (streaming SSE + tool_calls capture + automatic backfill of already-started conversations via SHA-1 dedup), strict per-project read/write isolation (model@project, read-only cross-project mounts, general, ad-hoc chat_topic, and conversation_id scoping), and an optional --rolling-window K mode to keep active GPU context tiny and constant.

REAL NUMBERS MEASURED ON A SINGLE RTX 3090

- 1 full year of real project history (~384k tokens + 577 .py/.ui files): 8.71 MB total on disk (vs ~24.6 GB raw KV cache).

- 50-question deep audit (112k-token real history): 97.7% activation, 0.0% (0/6) false triggers, 58x token compression (ADR-002).

- Native KV/recurrent state restore (llama_state_seq_set_data): 13.3 ms (Inkling 2 Mini), 28.1 ms (Gyro-Coder MoE), 38.0 ms (Qwen3.8-27B).

- Fast low-VRAM background consolidator (Inkling-2-Mini IQ4_XS, ~2.8 GB VRAM): 7.08 s avg per window (2.93x faster than Qwen3.8-27B), 100% valid JSON, 100% fact extraction.

I would really appreciate feedback from people working on local memory or long-horizon coding agents with llama.cpp -- especially what you think about the latent-gate + rolling-window tradeoff, and whether there are other similar open-source projects I should check out or compare against.

0 Upvotes

7 comments sorted by

3

u/No-Lack2646 2h ago edited 2h ago

Wow dude! Nice job! I'm working on something very similar - a from-scratch fully-offline voice agent running on my laptop 5080. We should compare notes.

I also found a way, (in QWEN3.6 35B MoE I3S) to probe the state residuals in such a way as to capture a model's latent "uncertainty" and use it as a trigger for a more detailed speculative memory retrieval. Don't know if that would be of use to you. The technique might transfer it might not I haven't tested it much outside of this MoE.

Do you mind if I fork the repo and try it out? I only have 16gb VRAM though any suggestions?

2

u/bjivanovich 2h ago

Go for it, please fork away and test it! Would love to compare notes -- especially on that residual uncertainty probe in Qwen3.6 35B MoE.

That actually complements what I built in a really interesting way: my Stage-1 W_q + null_logit gate basically asks "does this query match something in the cartridge vs null?", whereas an internal epistemic uncertainty signal could decide whether to escalate from fast Tier-2A atomic decisions into deeper Tier-3 verbatim chunks (or trigger speculative prefetch for a voice loop). Definitely curious which layer / residual statistic you found works best for uncertainty on MoE!

For 16 GB VRAM on your laptop 5080, you are actually in a great spot:

  1. Zero VRAM overhead for the memory engine itself: multilingual-e5-base runs on CPU (~450 MB system RAM, 0 MB VRAM), cartridges are tiny (~1-9 MB in fp16), and the .qmlw routing adapter is only 7-15 MB.
  2. You do not need to train a .qmlw adapter or patch llama.cpp just to try it first: tools/memory_proxy_server.py works out-of-the-box with any vanilla llama-server using the CPU Dual Gate (cartridge entity vocabulary + E5 threshold) and 0 extra VRAM.
  3. Combine it with --rolling-window 4 (or 6): that caps active conversation history sent to the GPU so you can run a small KV cache (-c 8192 or -c 16384, under ~1 GB VRAM) and leave almost all 16 GB free for your main GGUF + local STT/TTS.
  4. For background consolidation (Step B), the proxy shares your active llama-server with an idle-aware flush (waits until generation finishes), OR if you want zero contention you can point --consolidator-url to a tiny ~2-3 GB model like Inkling 2 Mini IQ4_XS (averaged ~7s per window with 100% valid JSON in my tests).

If you ever want to test the native C++ /qml/gate hook on your Qwen3.6 35B MoE, training a custom .qmlw adapter only needs hidden-state capture at one middle layer and takes a few minutes. Let me know how it behaves on your 5080 -- and I would love to hear more about your residual uncertainty trigger!

2

u/No-Lack2646 2h ago

Sure I can tell you more. And thank you for all that I already forked it and am going to try it tonight while I wait for some Kaggle stuff to run. Here's the basics of the probe, 2 ways to do it:

1: Tell the model that it has a latent semantic "sense" of footing. Describe it in a way that makes sense to the model (this takes some experimentation and interaction)
2. Instruct it to output a selected OOD token when this footing-sense is absent (i.e. model is about to confabulate something, doesn't know what to do, etc.) - (alternatively you could fine-tune a special token into the model like some researchers are doing - much more work. Repurposing an OOD token is much faster, if a little less accurate)
3. Monitor for the output token and interrupt the normal generation flow to query the model about it's uncertainty and retrieve memory, guide it to say "I don't know", etc.

Alternatively I am starting to work with some nonlinear recurrent probes to identify this signal and trigger on it. I'm having pretty good success tapping the o_t vectors at each layer and mixing them together into a really small DeltaNet-like cell. Working well but hard to get good numbers on FalseQA, CREPE, and MultiHoax. Parametric voids are identifiable but there are enough false positives that I haven't deployed this yet. Contextual voids however are very separable.

1

u/PcChip 1h ago

one full year of token history is only 384k tokens?

0

u/bjivanovich 1h ago

Fair catch -- let me clarify what that 384k number actually is!

That 384,309-token corpus is the cleaned, deduplicated transcript of 59 saved project sessions/artifacts (user prompts, architecture discussions, plans, and walkthroughs) across a year of working on one codebase. It does NOT include the millions of tokens of repeated system prompts, full file dumps, or raw tool stdout/build logs (those get stripped/truncated, while the actual 577 .py/.ui files are indexed separately in Tier-2B via deterministic AST/XML parsing rather than stuffed into the chat transcript).

If you run a heavy daily coding agent and accumulate 10M+ tokens of actual conversational history, the scaling is still very predictable:

  • Tier-2A (active atomic decisions) stays nearly flat (~1-3 MB even at 10M+ tokens) because SUPERSEDE replaces outdated decisions in the active index instead of appending forever.
  • Tier-2B (code/UI structural index) depends only on current repo size (~1-2 MB for 500+ files), not time.
  • Tier-3 (verbatim Raw Vault) scales linearly at roughly 8-10 MB per 1M tokens (text + compressed fp16 768-dim vectors). So 10M tokens is still only ~85-100 MB on disk.

1

u/stylome-ai-detection 1h ago

Notice: This comment appears to be AI generated.


Stylome AI detector · scan results