Architecting a Zero-Cloud Agent Memory Lab: vLLM, pgvector, and a Context Budget That Never Blows Up
For most of 2024 my agents lived on other people's computers. Every experiment with memory, every "what happens if I keep the last fifty turns instead of twenty", went out over HTTPS and came back as a line on an invoice. That is a terrible way to do research. When each mistake costs money, you stop making mistakes on purpose, and making mistakes on purpose is the whole job.
So in October I took a 48 GB workstation card and an old 24 GB card out of a cupboard and built what I started calling the Agent Memory Lab: a box under my desk where an agent can remember, forget, summarise and contradict itself as much as it likes, and the only thing it costs is electricity. No cloud API anywhere in the loop. This post is the full write-up: the stack, the Python memory engine, and the three fights that took most of my evenings. Those were context compaction, moving from Ollama to vLLM, and quantization maths.
It is long. Get a coffee.
What the lab is for
The question I wanted to answer was narrow: how should an agent manage its own history so that it stays correct over a long session without the prompt growing until the GPU chokes?
An agent is not a chatbot. A chatbot answers once. An agent runs a loop:
Steps two to five repeat. Each pass adds the model's thought, the tool call and the tool's output to the context. A ten-step task does not send one prompt. It sends ten, and each one is longer than the last. Whatever the agent fails to remember, or remembers wrongly, it carries into every later step.
That compounding is the part people underestimate:
P(task succeeds) = p^n
0.85^10 ≈ 0.197 0.95^10 ≈ 0.599 0.99^10 ≈ 0.904
An agent that gets each step right 85 percent of the time finishes a ten-step task correctly about one time in five. Memory is a big part of that per-step number. A step that works from a stale fact, or from a summary that quietly dropped the one constraint that mattered, is a failed step even if the model reasoned perfectly. Moving p from 0.85 to 0.95 triples the success rate of the whole task. That is why I think memory is not a feature. It is the reliability budget.
The workload: a tutor that has to remember
I needed a test workload where memory errors are obvious. I picked tutoring, inspired by research prototypes like this one, where students learn by teaching an LLM "virtual peer":
The idea is lovely and brutal on memory. If the student explained in turn 4 that a 3:2 ratio means splitting the total into five parts, the peer must not make the same mistake again in turn 30. If the student says in turn 12 that they prefer the recycling theme, the peer should not switch to space rockets in turn 40. If the student corrects themselves ("wait, I said 300 tons, I meant 360"), the old number has to die.
I wrote a scripted student that runs 60-turn sessions with planted facts, preferences and two deliberate contradictions per session. After each session I ask the agent twelve questions about what happened. That gave me a memory score I could actually compare between setups, instead of a feeling.
Part 1: the local stack
Hosting: vLLM, not a wrapper
I started on Ollama because everyone does. It is a great way to run one model for one person. It is the wrong tool for an agent lab, for two reasons I will put numbers on later: it handles parallel requests poorly, and it gives you little control over how the KV cache is reused between steps. vLLM has three features I consider non-negotiable for agent loops:
- PagedAttention. The KV cache is stored in fixed-size blocks, like virtual memory pages, instead of one contiguous slab per request. No space is reserved for tokens that never get generated, so far more sequences fit in the same VRAM.
- Continuous batching. New requests join the running batch at the next decoding step instead of waiting for the whole batch to finish. When eight agents fire tool-result prompts at random moments, nobody waits in a queue behind a long generation.
- Automatic prefix caching. If two requests start with the same tokens, the KV blocks for that shared prefix are computed once and reused. For an agent that resends its system prompt and history on every step, this is the single biggest win. More on it in battle two.
Models
My first choice was Gemma 2 27B. It is a strong model, but its context window is 8k tokens, and a memory lab with an 8k ceiling is a lab about truncation and nothing else. I switched to Qwen2.5-32B-Instruct in its AWQ 4-bit build, which handles 32k tokens natively. That is the main "thinking" model, on the 48 GB card.
The 24 GB card runs Llama 3.1 8B Instruct (AWQ INT4) as the helper: it extracts facts, writes summaries and judges conflicts. Background work like that does not need the big model, and keeping it on a separate card means compaction never competes with the agent for VRAM.
Embeddings come from bge-small-en-v1.5: 384 dimensions, runs on the CPU, fast enough that I never thought about it again.
Serving
# main model, 48 GB card
CUDA_VISIBLE_DEVICES=0 vllm serve Qwen/Qwen2.5-32B-Instruct-AWQ \
--quantization awq_marlin \
--max-model-len 32768 \
--gpu-memory-utilization 0.92 \
--kv-cache-dtype fp8 \
--enable-prefix-caching \
--port 8000
# helper model, 24 GB card
CUDA_VISIBLE_DEVICES=1 vllm serve hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4 \
--max-model-len 16384 \
--gpu-memory-utilization 0.90 \
--enable-prefix-caching \
--port 8001
Both expose an OpenAI-compatible API, so the rest of the code uses the normal openai client pointed at localhost. Nothing in the engine knows or cares that there is no cloud.
The database
Postgres 16 with pgvector, in Docker. Supabase's local stack is the same Postgres with pgvector underneath if you prefer that tooling; I wanted fewer moving parts.
docker run -d --name memlab-db -p 5432:5432 \
-e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab -e POSTGRES_DB=memlab \
-v memlab-data:/var/lib/postgresql/data \
pgvector/pgvector:pg16
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE memories (
id bigserial PRIMARY KEY,
session_id text NOT NULL,
kind text NOT NULL CHECK (kind IN ('fact', 'preference', 'summary')),
content text NOT NULL,
embedding vector(384) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
superseded_by bigint REFERENCES memories (id)
);
CREATE INDEX memories_embedding_idx ON memories USING hnsw (embedding vector_cosine_ops);
CREATE INDEX memories_live_idx ON memories (session_id) WHERE superseded_by IS NULL;
superseded_by is the column that makes the conflict sentinel possible. Old facts are never deleted, just marked as replaced, so I can always ask what the agent believed at any point in a session.
The API layer, and why it is MCP-shaped
At first the engine was just a Python module my test harness imported. Then I wanted my editor to use the same memory, and then a small web UI, and I could feel myself about to write three integrations. The Model Context Protocol, which Anthropic published at the end of November, is the shape I am moving the engine to:
The memory engine becomes one MCP server with three tools, recall, remember and compact. Any MCP-capable client gets the same memory without me writing glue. For this post I will stay at the Python level, because that is where the interesting decisions are.
Part 2: the memory engine
Three tiers, each with one job:
| Tier | What it holds | Where it lives | Lifetime |
|---|---|---|---|
| Ephemeral | the last few turns, verbatim | in the prompt | until compacted |
| State paragraph | a running summary of everything older | in the prompt, right after the system prompt | rewritten on each compaction |
| Semantic | individual facts and preferences, embedded | Postgres + pgvector | permanent, superseded not deleted |
The rule that ties them together: the prompt only ever contains the state paragraph, the recent turns, and the handful of facts relevant to the current question. Everything else stays in the database until it is asked for.
Clients and token counting
# memory_lab/clients.py
from openai import OpenAI
from transformers import AutoTokenizer
MAIN_MODEL = "Qwen/Qwen2.5-32B-Instruct-AWQ"
HELPER_MODEL = "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4"
main = OpenAI(base_url="http://localhost:8000/v1", api_key="local")
helper = OpenAI(base_url="http://localhost:8001/v1", api_key="local")
tokenizer = AutoTokenizer.from_pretrained(MAIN_MODEL)
def count_tokens(messages: list[dict]) -> int:
"""Exact token count, chat template included, the way vLLM will see it."""
return len(tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True))
def ask_helper(system: str, user: str, max_tokens: int = 300) -> str:
reply = helper.chat.completions.create(
model=HELPER_MODEL,
messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
max_tokens=max_tokens,
temperature=0,
)
return reply.choices[0].message.content.strip()
Count tokens with the real tokenizer and the real chat template. I lost a whole evening to a character-based estimate that was off by 30 percent on code-heavy turns, which meant my "safe" prompts were silently overflowing.
The semantic store
# memory_lab/store.py
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5", device="cpu")
conn = psycopg.connect("postgresql://lab:lab@localhost:5432/memlab", autocommit=True)
register_vector(conn)
def embed(text: str):
return embedder.encode(text, normalize_embeddings=True)
def insert(session_id: str, content: str, kind: str = "fact") -> int:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO memories (session_id, kind, content, embedding) "
"VALUES (%s, %s, %s, %s) RETURNING id",
(session_id, kind, content, embed(content)),
)
return cur.fetchone()[0]
def search(session_id: str, query: str, limit: int = 5, max_distance: float = 0.35):
"""Live memories closest to the query, dropping anything too far away to help."""
q = embed(query)
with conn.cursor() as cur:
cur.execute(
"SELECT id, kind, content, embedding <=> %s AS distance FROM memories "
"WHERE session_id = %s AND superseded_by IS NULL AND kind <> 'summary' "
"ORDER BY embedding <=> %s LIMIT %s",
(q, session_id, q, limit),
)
return [row for row in cur.fetchall() if row[3] <= max_distance]
def supersede(old_id: int, new_id: int) -> None:
with conn.cursor() as cur:
cur.execute("UPDATE memories SET superseded_by = %s WHERE id = %s", (new_id, old_id))
The max_distance cut is not decoration. Without it, limit=5 always returns five memories, even when none of them are relevant, and irrelevant memories in the prompt are worse than none: the model tries to use them. With normalised bge vectors, cosine distance above roughly 0.35 was noise in my sessions. Your number will differ. Log the distances and look.
Battle 1: the dark art of context truncation and dynamic prompt compaction
The snowball
The default approach is to append every turn to the prompt until it hits the context limit, then panic. In an agent loop this is worse than it sounds, because prefill cost grows with prompt length and the agent pays it on every step:
tokens processed over a session ≈ Σ (P0 + k·t) for t = 1 … T
= T·P0 + k·T(T+1)/2
P0 is the fixed part, the system prompt and tools. k is the tokens added per step. The second term is quadratic in the number of steps. My scripted 60-turn tutoring session added about 450 tokens per turn. With a 1,500-token system prompt that is roughly 90,000 tokens for the fixed part and over 820,000 for the growing part. The model spends most of its compute rereading the past, the past is mostly redundant, and by turn 40 the session hit the 32k wall anyway.
I wrote about the general techniques in an earlier post on truncation and compaction. Here is how they fit together in the lab.
Tier 2: compaction into a state paragraph
When the ephemeral window gets too long, the oldest turns are folded into the state paragraph by the 8B helper model:
# memory_lab/compaction.py
from .clients import ask_helper
COMPACT_PROMPT = """You maintain the STATE of a tutoring session as one paragraph.
Merge the NEW TURNS into the CURRENT STATE. Keep: facts the student stated, corrections
(keep only the corrected value), what the peer has already been taught, open questions,
and the student's preferences. Drop greetings, repetition and anything already resolved.
Never invent details. Maximum 180 words. Output only the paragraph."""
def compact(state: str, old_turns: list[dict]) -> str:
transcript = "\n".join(f"{t['role']}: {t['content']}" for t in old_turns)
return ask_helper(
COMPACT_PROMPT,
f"CURRENT STATE:\n{state or '(empty)'}\n\nNEW TURNS:\n{transcript}",
max_tokens=320,
)
Three lessons from tuning this prompt:
- "Keep only the corrected value" is the most important sentence in it. Early versions kept both: "the student said 300 tons, later 360 tons". The main model then used whichever number came first about half the time.
- A word limit beats a token limit. Small models respect "180 words" far better than "under 250 tokens".
- The summariser must never see its own output as ground truth for new facts. Facts go to the semantic tier separately, so a bad summary costs some context, not the facts themselves.
The conflict sentinel
Compaction handles the prompt. The database needs its own guard, because the semantic tier happily stores "the student's school is in Delhi" on Monday and "the student's school is in Pune" on Wednesday, and retrieval will return both. So every new fact passes a sentinel before it is stored:
# memory_lab/sentinel.py
from .clients import ask_helper
from .store import insert, search, supersede
EXTRACT_PROMPT = """Extract durable facts and preferences about the user from the message.
One per line, each a short standalone sentence starting with 'The student'.
Prefix preferences with 'PREF: '. If there are none, output NONE."""
JUDGE_PROMPT = """Compare a NEW statement with an OLD memory about the same student.
Reply with exactly one word:
SAME - they say the same thing
UPDATE - NEW replaces OLD (a correction or a change over time)
UNRELATED - they are about different things"""
def extract_facts(message: str) -> list[tuple[str, str]]:
out = ask_helper(EXTRACT_PROMPT, message)
if out.upper() == "NONE":
return []
facts = []
for line in filter(None, (l.strip() for l in out.splitlines())):
kind = "preference" if line.startswith("PREF:") else "fact"
facts.append((kind, line.removeprefix("PREF:").strip()))
return facts
def write_memory(session_id: str, content: str, kind: str = "fact") -> int:
for mem_id, _, old, _ in search(session_id, content, limit=3, max_distance=0.25):
verdict = ask_helper(JUDGE_PROMPT, f"OLD: {old}\nNEW: {content}", max_tokens=3).upper()
if verdict.startswith("SAME"):
return mem_id
if verdict.startswith("UPDATE"):
new_id = insert(session_id, content, kind)
supersede(mem_id, new_id)
return new_id
return insert(session_id, content, kind)
The sentinel only compares against near neighbours (distance under 0.25), so it costs one tiny helper call per new fact and usually zero, because most facts have no close neighbour. On my scripted sessions it caught 19 of the 24 planted contradictions. The five misses were all changes phrased so differently ("lives near the station" against "moved to the hills") that the embeddings did not consider them neighbours. That is a retrieval problem, not a judging problem, and I have not solved it.
Deciding how much to compact: a controller, literally
My first compaction trigger was a threshold: when the prompt passes 75 percent of the budget, compact the oldest ten turns. It oscillated. One huge tool output would trigger a big compaction, the next few steps would run on a thin prompt with little recent detail, then it would grow back and trigger again. Anyone who has tuned a motor knows this shape.
The mapping is almost one to one. The reference is the target fill level of the context budget. The plant is the conversation, which grows on its own. The sensor in the feedback path is the tokenizer. The controller output is how many old turns to fold into the state paragraph this step.
e(t) = used(t) / budget − target
u(t) = Kp · e(t) + Ki · Σ e(τ) turns to compact = max(0, round(u(t)))
# memory_lab/controller.py
class CompactionController:
"""PI controller that keeps the prompt near a target share of the token budget."""
def __init__(self, target: float = 0.60, kp: float = 14.0, ki: float = 2.5):
self.target, self.kp, self.ki = target, kp, ki
self.integral = 0.0
def turns_to_compact(self, used: int, budget: int) -> int:
error = used / budget - self.target
self.integral = max(0.0, self.integral + error) # anti-windup: never bank negative error
return max(0, round(self.kp * error + self.ki * self.integral))
The proportional term reacts to a sudden jump, like a 3,000-token tool output. The integral term handles the slow creep of ordinary turns that the P term alone would tolerate forever, just under the threshold. Clamping the integral at zero is the anti-windup: after a quiet stretch with lots of headroom, the controller must not bank "negative debt" and then refuse to compact when it finally matters.
With target 0.60, the prompt for my tutoring sessions settled between 55 and 68 percent of the budget instead of swinging between 40 and 95. The memory score went up too, because the recent-turn window stopped getting wiped in big chunks.
Tuning was a needle in a sphere
Kp, Ki, the target, the retrieval distance cut, and the number of verbatim turns to keep all interact. I swept them on a grid overnight and coloured the results, and the shape reminded me of a figure I had saved from a maths paper:
The paper's figure is about counting real solutions as parameters move across a sphere, and the striking thing is how small the region of the maximum is compared to the rest. My sweep was the same. Most combinations gave a memory score between 6 and 8 out of 12. One small region gave 10 to 11: target around 0.6, Kp between 10 and 16, a distance cut of 0.3 to 0.35, and six verbatim turns. A hand-picked "sensible" config scored 7. If you build something like this, do not trust the first configuration that seems to work. Sweep.
The gatekeeper
Everything above meets in one function. It is the expanded version of the sketch I started the project with:
# memory_lab/gatekeeper.py
from dataclasses import dataclass, field
from .clients import MAIN_MODEL, count_tokens, main
from .compaction import compact
from .controller import CompactionController
from .sentinel import extract_facts, write_memory
from .store import search
SYSTEM_PROMPT = open("prompts/tutor_peer.md", encoding="utf-8").read()
@dataclass
class Session:
id: str
state: str = ""
turns: list[dict] = field(default_factory=list)
controller: CompactionController = field(default_factory=CompactionController)
def build_messages(session: Session, memories: list, user_query: str) -> list[dict]:
"""Stable content first, volatile content last, so vLLM's prefix cache keeps hitting."""
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
if session.state:
messages.append({"role": "system", "content": "SESSION STATE:\n" + session.state})
messages += session.turns
if memories:
facts = "\n".join(f"- {content}" for _, _, content, _ in memories)
messages.append({"role": "system", "content": "RELEVANT MEMORIES:\n" + facts})
messages.append({"role": "user", "content": user_query})
return messages
def strict_context_truncation(session: Session, memories: list) -> list:
"""Last resort: drop the oldest verbatim turn, then the weakest memory. Never the state."""
if len(session.turns) > 2:
del session.turns[:2] # one user/assistant pair
elif memories:
memories = memories[:-1] # search() returns closest first
else:
raise ValueError("prompt does not fit even with no history; raise the budget")
return memories
def manage_agent_context(session: Session, user_query: str, max_tokens: int = 24_000) -> str:
# 1. Pull only the memories that are close enough to matter.
memories = search(session.id, user_query, limit=5)
# 2. Let the controller decide how much old history to fold into the state paragraph.
used = count_tokens(build_messages(session, memories, user_query))
n = min(session.controller.turns_to_compact(used, max_tokens), max(0, len(session.turns) - 6))
n -= n % 2 # compact whole user/assistant pairs
if n:
session.state = compact(session.state, session.turns[:n])
del session.turns[:n]
# 3. Hard guarantee: never send more than the budget.
messages = build_messages(session, memories, user_query)
while count_tokens(messages) > max_tokens:
memories = strict_context_truncation(session, memories)
messages = build_messages(session, memories, user_query)
reply = main.chat.completions.create(
model=MAIN_MODEL, messages=messages, max_tokens=800, temperature=0.3
).choices[0].message.content
# 4. Write back: verbatim turns to the ephemeral tier, durable facts through the sentinel.
session.turns += [{"role": "user", "content": user_query}, {"role": "assistant", "content": reply}]
for kind, fact in extract_facts(user_query):
write_memory(session.id, fact, kind)
return reply
Notice max_tokens=24_000 on a model served with a 32k window. The budget covers the prompt. The other 8k is headroom for the reply and for the occasional tool output that arrives between my count and the call. Budgeting the prompt to the full window is the most common bug I see in people's agent code.
In production I run step 4 in a background task so the user never waits on fact extraction. The helper card is idle most of the time anyway.
Battle 2: VRAM strategy, migrating from Ollama to vLLM
People treat the local runner as a black box: model goes in, tokens come out. For a single chat that is fine. For agents, the runner's scheduling and cache behaviour decides whether a step takes a tenth of a second or eight seconds.
The benchmark
Same model on both, Llama 3.1 8B Instruct at 4-bit (Ollama's Q4_K_M, vLLM's AWQ INT4), on the 24 GB card. The prompt is a realistic agent step of about 6,000 tokens, of which about 5,200 are a shared prefix: system prompt, state paragraph and history. Only the tail changes between steps. Ollama has an OpenAI-compatible endpoint too, so one script measures both:
# bench_ttft.py
import statistics
import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI
def time_to_first_token(client, model, messages) -> float:
start = time.perf_counter()
stream = client.chat.completions.create(model=model, messages=messages, max_tokens=64, stream=True)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
ttft = time.perf_counter() - start
stream.close()
return ttft
raise RuntimeError("no tokens returned")
def run(base_url, model, prompts, parallel):
client = OpenAI(base_url=base_url, api_key="local")
with ThreadPoolExecutor(max_workers=parallel) as pool:
times = list(pool.map(lambda m: time_to_first_token(client, model, m), prompts))
return statistics.median(times), statistics.quantiles(times, n=20)[18] # p50, p95
# Ollama: run("http://localhost:11434/v1", "llama3.1:8b-instruct-q4_K_M", prompts, 8)
# vLLM: run("http://localhost:8001/v1", "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4", prompts, 8)
My numbers, each the median of five runs:
| Scenario | Ollama | vLLM |
|---|---|---|
| 1 agent, cold prompt, TTFT | 1.9 s | 0.7 s |
| 1 agent, next step on a warm prefix, TTFT | 0.41 s | 0.12 s |
| 8 agents in parallel, TTFT p50 | 7.8 s | 0.9 s |
| 8 agents in parallel, TTFT p95 | 14.2 s | 1.6 s |
| 8 agents, total generation speed | ~105 tokens/s | ~690 tokens/s |
The single-agent rows are a fair fight, and vLLM wins mostly on prefill speed. The eight-agent rows are not close. Ollama processes a limited number of requests at once (OLLAMA_NUM_PARALLEL), and the rest queue. Raising that number helps, but each parallel slot gets its own share of the context, so you trade queueing for shorter windows. vLLM's continuous batching just adds each new request to the running batch.
Your numbers will differ with hardware, versions and prompt shapes. Run the script on your own box before you migrate anything. The shape of the result, similar for one user and very different for many, has held on every setup I have tried.
Why prefix caching matters so much for agents
Look at the agent loop again. Step 7 sends everything step 6 sent, plus one thought, one tool call and one observation. Without caching, the server recomputes the key and value tensors for all of it, every step. With automatic prefix caching, vLLM hashes the prompt in blocks of 16 tokens. Any block whose hash, including everything before it, is already in VRAM is reused instead of recomputed. Only the new tail is prefilled.
prefill work per step ≈ (prompt tokens − cached prefix tokens)
For my tutoring agent that turned a typical step from about 6,000 prefilled tokens into about 800.
There is a catch, and it is why build_messages orders things the way it does. The cache only matches a prefix. One changed token early in the prompt invalidates everything after it. My first version put retrieved memories right after the system prompt, because that felt logical. Since retrieved memories change on almost every query, the cache hit rate was close to zero. Moving them to the end, just before the user message, so that the stable parts come first, took the hit rate from about 5 percent to about 85 percent:
[system prompt] never changes -> always cached
[state paragraph] changes on compaction -> cached between compactions
[verbatim turns] append-only -> cached up to the newest turn
[retrieved memories] changes every query -> recomputed, but small
[user message] new -> recomputed
This also explains why the PI controller helps speed and not only quality. Every compaction rewrites the state paragraph, which invalidates everything after it. Fewer, smaller compactions mean the cache survives longer. vLLM exposes prefix cache hit rates in its metrics endpoint, so you can watch this happen rather than guess.
Battle 3: quantization maths for huge context windows
Where the VRAM goes
A model in VRAM is two things: weights, which are fixed, and the KV cache, which grows with every token of every sequence in flight. Weights first:
weight memory = parameters × bytes per parameter
27B at 16-bit: 27 × 10^9 × 2 bytes ≈ 54 GB
32B at 16-bit: 32.8 × 10^9 × 2 bytes ≈ 65 GB
32B at 8-bit: 32.8 × 10^9 × 1 byte ≈ 33 GB
32B at 4-bit: 32.8 × 10^9 × 0.5 byte ≈ 16.4 GB, plus scales and unquantized layers ≈ 19 GB
A 27B model in 16-bit needs about 54 GB before it has seen a single token. On a 48 GB card it does not load at all. Qwen2.5-32B in 16-bit does not even fit on two of my cards combined.
Now the KV cache. For every token, every layer stores a key and a value vector for each KV head:
KV bytes per token = 2 × layers × KV heads × head dim × bytes per value
Qwen2.5-32B has 64 layers, 8 KV heads (it uses grouped-query attention, so many query heads share each KV head) and a head dimension of 128:
16-bit KV: 2 × 64 × 8 × 128 × 2 bytes = 262,144 bytes = 256 KiB per token
32,768 tokens × 256 KiB = 8 GiB for one full-length sequence
8-bit KV: 128 KiB per token, 4 GiB for one full-length sequence
The budget on the 48 GB card
usable = 48 GB × 0.92 (gpu-memory-utilization) ≈ 44.2 GB
weights ≈ 19.3 GB (AWQ 4-bit)
activations ≈ 2.5 GB (CUDA graphs, temporary buffers)
KV cache ≈ 44.2 − 19.3 − 2.5 ≈ 22.4 GB ≈ 20.9 GiB
16-bit KV: 20.9 GiB / 256 KiB ≈ 85,000 tokens ≈ 2.6 full 32k sequences
8-bit KV: 20.9 GiB / 128 KiB ≈ 171,000 tokens ≈ 5.2 full 32k sequences
vLLM prints the number of KV blocks it allocated when it starts. Check it against your own maths. When mine disagreed, it was because I had forgotten the activation memory.
That is the whole argument in one line: 4-bit weights turn a model that cannot load into one that loads with over 20 GB left for context. With an 8-bit KV cache, that is five agents each holding a full 32k window at the same time on one card. Context, not weights, is where an agent lab needs its memory.
What AWQ and GPTQ actually do
Both store weights as 4-bit integers in groups, typically 128 weights per group, each group with its own scale and zero point:
s = (max(w) − min(w)) / (2^b − 1) z = round(−min(w) / s)
q = clamp(round(w / s) + z, 0, 2^b − 1) ŵ = s · (q − z)
With b = 4 that is 16 levels per group. Rounding every weight to the nearest level naively costs real quality. The two methods differ in how they decide what to protect.
GPTQ quantizes one column at a time and, after each column, adjusts the remaining unquantized weights to compensate for the rounding error. It uses second-order information, an approximate inverse Hessian built from calibration data, so the layer's output stays as close as possible to the original. Think of it as error diffusion for weight matrices.
AWQ (activation-aware weight quantization) starts from an observation: a small fraction of weight channels, around one percent, matter far more than the rest, and you can find them by looking at activation magnitudes rather than weight magnitudes. Instead of keeping those channels in high precision, which is awkward for hardware, AWQ scales them up before quantization and scales the matching activations down by the same factor. The maths is unchanged but the important weights get more of the quantization grid:
y = W·x = (W · diag(s)) · (diag(s)^−1 · x) s_j = (mean |x_j|)^α, α searched per layer
In practice both give 4-bit models within a point or two of the 16-bit original on most benchmarks. AWQ is usually faster to produce and, with vLLM's Marlin kernels (--quantization awq_marlin), fast to run. On my tutoring sessions the AWQ Qwen scored 10.4 out of 12 against 10.7 for the 8-bit build I tested on a borrowed card. I will take 0.3 points for three times the context.
The other quantization: the KV cache
--kv-cache-dtype fp8 halves the KV cache, and it is a different trade from weight quantization. Weight errors are fixed. KV errors are spread across every past token the model attends to. In my sessions fp8 KV cost nothing measurable on the memory score, but I run retrieval-heavy evaluations with fp8 on and off before trusting it for a new model. Some models are more sensitive than others.
What I would tell myself in October
| Problem | What fixed it |
|---|---|
| Prompt snowballs, every step slower than the last | Three tiers: verbatim window, state paragraph, semantic store |
| Old and new values of the same fact both in memory | Conflict sentinel with superseded_by, corrections kept as only the new value |
| Compaction oscillates, recent detail wiped in chunks | PI controller on prompt fill level, with anti-windup |
| Irrelevant memories confuse the model | Distance cut-off on retrieval, not just limit=5 |
| Prompt overflow despite "counting" | Count with the real tokenizer and chat template, budget below the window |
| Parallel agents queue for seconds | vLLM continuous batching instead of Ollama |
| Prefix cache never hits | Stable content first, retrieved memories last |
| 27B to 32B model will not load, or loads with no room for context | AWQ 4-bit weights plus fp8 KV cache |
| "Sensible" settings score badly | Sweep the parameters; the good region is small |
The lab cost me two old GPUs and a lot of evenings. In return I can now run a thousand-session experiment overnight, look at every token the agent saw, and change one line of the compaction prompt without thinking about a bill. If you are building agents and all of your memory experiments go through a paid API, I think you are learning much slower than you could. Most of what I learned this year came from runs I would never have paid for.
Next on the list: the MCP server wrapper, and fixing the five contradictions the sentinel still misses.