# Can 16 memory tokens carry the one fact that matters? A work report on Memorilla's token path

Date: 2026-11-24
URL: https://blog.nenkoru.com/posts/memorilla-token-path/

> TL;DR: Memorilla packs each stored fact about a user into 16 memory tokens for Qwen3-8B. On fact types it never trained on, the best pipeline on those tokens acts on the one relevant fact in 44% of answers; a perfect picker would reach 80%, and a 27B judge reading the facts as text reaches 68%. The gaps are finding the fact among 48+ others and a reader that mostly uses it only when it comes first; the next step, teaching the token rater from the 27B judge, is ready to run. Done mostly by an AI agent (Claude) under the author's direction.

## How to read this

- **Humans:** the TL;DR above is the whole story. The section "What worked and what didn't" has the lessons.
- **Agents picking up the work:** read "State of the work" first, then "What to try next". Section names are stable anchors. Numbers are from one seed; see "Benchmark and noise" before comparing anything.
- **AI use:** this work was largely AI-run; the section "AI use" at the end says exactly what was done by which model.
- **Code:** not public yet. File and script names below refer to the project's `experiments/` folder (scripts and docs), `mport/` (a small package) and `work/` (data, checkpoints, logs).

## State of the work

- **Goal.** Make Memorilla's 16-token memory act on the one stored fact about a user that should change an answer (the "buried clue"), on fact types it never trained on.
- **Best result off the token path.** A 27B model rates each fact as text; the 8B answers. Held-out "acts": 0.68 at 8 facts, 0.53 at 48 (test 41). A perfect picker gives about 0.80.
- **Best result on the token path.** A LoRA rater reads each fact's 16-token block. Acts: 0.44 for top 1 of 8, 0.30 for top 4 of 48 (test 43). It is capped by its 8B teacher.
- **Bottleneck 1: picking at 48+ facts.** The clue is ranked first of 48 in 0.35 of profiles by the 27B, 0.16 by the 8B, and 0.09 by the block rater.
- **Bottleneck 2: the reader.** It acts on the clue 0.76–0.79 when the clue is the first block, but 0.40–0.60 when it is shown further down.
- **Last experiment.** A GRPO pilot on the reader (test 44), stopped at step 19 of about 50 with no learning signal yet. Inconclusive, not negative.
- **Next.** Check 4c (a 27B teacher for the block rater) needs a GPU server with about 64 GB of VRAM. On a laptop, evaluate the saved GRPO checkpoint or try write-time salience.

## Background

### Memorilla

- [Memorilla](https://github.com/snap-stanford/memorilla) (Apache 2.0; used at commit 6864db7) reads a document collection and gives a frozen LLM 16 query-dependent memory tokens.
- **Core.** The "pv4" `MemoryModule` for Qwen3-8B, about 194M parameters (370 MB). 16 learned slots cross-attend to the request embedding, then 2 cross-attention blocks attend over the document embeddings, then a projection maps 2560 to 4096 dimensions, into the decoder's embedding space.
- **Encoder.** `Qwen/Qwen3-Embedding-4B` (2560-d). Every fact and request is embedded once and cached.
- **Decoder.** `Qwen/Qwen3-8B`. Memory tokens replace `<|memory|>` placeholder embeddings in the prompt.
- **Frozen throughout.** The core, the encoder and the decoder base weights. Only LoRAs, small maps and probes are trained.

### The token path

Each stored fact goes through the untouched core alone, conditioned on the request, and comes out as one 16-token block. The k picked blocks are concatenated into 16·k memory tokens.

```
stored facts (a profile of 8 / 16 / 48 / 192)
   |  each fact + request --> frozen core --> 16-token block
   v
picker: rate each block alone ("does this fact change a good reply?") --> keep top k
   v
reader (Qwen3-8B + LoRA) with k blocks in memory --> "Relevant fact: ..." + answer
```

The reader is Qwen3-8B with a LoRA (rank 16, alpha 32, on q/k/v/o of all 36 layers), `lora_lsort.pt`. It was trained on blocks sorted best-first and writes `Relevant fact: …` before the answer.

### Glossary

| Term | Meaning |
| --- | --- |
| clue | the one stored fact that should change the answer |
| profile | the clue plus 7, 15, 47 or 191 other users' facts (distractors) |
| block | the 16 memory tokens of one fact |
| rater / picker | scores each fact for a request; the top k go to the reader |
| text rater | a decoder rating the fact given as plain text (off the token path) |
| block rater | a decoder plus LoRA rating the fact from its block (on the token path) |
| acts | the regex rubric says the answer acts on the clue (the main metric) |
| held-out types | health, no_car, toddler, flying: never trained on |

## Benchmark and noise

- **Types.** 12 fact types. Trained: diet, pet, schedule, mobility, alcohol, budget, studio, hay_fever. Held out: health, no_car, toddler, flying. Each type has 3 questions, 2–4 values, and hand-written `acts` and `mentions` rubrics (deliberately not LLM-generated).
- **Pairs.** 252 (clue, question) pairs: train 120, val 60, test 72.
- **Eval set.** 318 rows: 288 held-out-type questions (72 test pairs plus 9 extra questions per held-out clue) and 30 trained-type val questions. Distractors are other users' facts of other types, seeded by the pair id.
- **Laptop standard.** Every third row, 106 rows (96 held-out).
- **Metric.** Strict pass: every `all_of` group needs a word-boundary regex hit and no `none_of` term may appear. Scored on the text after the `Relevant fact:` line.
- **Floors.** flying and no_car pass in about 20–36% of answers with no clue at all. health and toddler are the clean types. Every answer table has a clue-removed control. About 2% of rows contain another row's clue, so "clue first" tops out near 0.98.
- **Noise.** One seed everywhere. On 106 rows, one standard error is about 5 points at acts 0.4. **Differences under about 10 points on the laptop subset are not conclusive.**

## Results

### Ceiling and where things are (acts, held-out types)

| Condition | 8 facts | 48 facts | Test |
| --- | --- | --- | --- |
| Clue alone (perfect picker) | 0.80–0.83 | – | 41 |
| Whole profile as text, plain decoder | 0.53–0.58 | 0.32–0.35 | 31, 41 |
| 8B text rater, best top k | 0.60 | 0.47 | 38b, 41 |
| **27B text rater ("wrong" wording), best top k** | **0.68** | **0.53** | 41 |
| Block rater (16 tokens, LoRA), top 1 / top 4 | 0.44 | 0.30 | 43 |

### Where each rater ranks the clue

| Rater | Top 2 of 8 | First of 48 | Top 8 of 48 |
| --- | --- | --- | --- |
| Plain decoder on the block, "change" wording | 0.46 | – | 0.38 |
| Block rater, 90 min int8 training | 0.60 | 0.09 | 0.55 |
| 8B text rater (the block rater's teacher) | 0.75 | 0.16 | 0.72 |
| 27B text rater, "wrong" wording | 0.84 | 0.35 | 0.82 |

The "wrong" wording: "Could a typical reply to this request be wrong, unsafe or unsuitable for this user because of the fact? Answer Yes or No." The score is the Yes/No logit difference.

### Picking: what was tried

| Test | Idea | Result |
| --- | --- | --- |
| 17–22, 26 | Learned map (request × fact embedding) | Good on topical types (flying, no_car). Fails health and toddler. 2.7× more pairs: flat |
| 30 | Write-time "standing" score, request-independent | Hand-written category lists fix health at 8–16 facts, but only for what the list names. Label-free scores miss health |
| 32 | The 8B quotes which facts matter | False: quotes the clue in 49% at 8 facts, 22% at 48 |
| 35b, 35c | **Rate each fact alone with a yes/no, keep the top k** | **True**: beats the map and the whole profile. Wording matters per type |
| 36 | Distil the rating into an embedding scorer | False: below plain cosine on held-out types |
| 37, 38, 38b | Attention as the selector; rate all facts in one pass | False as a substitute: rates by topic in a crowd. Attention + rating: top 8 of 48 at 0.48 acts |
| 39 | Shortlist, then think or compare | +2 points at 5× the cost. Comparing in a group loses health |
| 40 | LoRA rater, listwise, hard labels | **False**: learns the training types; health falls to 0 at 192 facts |
| 41 | **27B rates each fact as text** | **True, the biggest gain.** Lifts every type. An 8B shortlist re-rated by the 27B keeps most of it at 25–33% of the cost |
| 43 | Rate from the 16-token block: plain decoder; draft-then-judge; LoRA distilled from the 8B text rater | Picking improves but the student is capped by its teacher. Answers gain 2–6 points |
| 43 | Abstain (skip memory) when the top score is low | False: AUC 0.51–0.61 (8B), 0.59–0.75 (27B) |

### Reading: what was tried

| Test | Idea | Result |
| --- | --- | --- |
| 19, 23, 27, 29 | Restate the relevant fact first, then answer; blocks sorted best-first; trained with distractors | Became the current reader |
| 31 | No picker: whole profile as text, reader trained to restate | The plain decoder with the whole profile beat the picker of that time (0.58 vs 0.39) |
| 33 | Self-distillation: the fact-only decoder teaches the whole-profile one | False: it learned the teacher's style |
| 34 | Token weights (learn only the tokens the fact changes) | No gain |
| 44 | GRPO on the reader | Stopped at step 19, no signal yet |

## What worked and what didn't

1. **A stronger general judge beats any narrow trained one** (test 41 vs 36 and 40). Training on 8–100 generated fact types teaches those types, not "what matters".
2. **Rate each fact alone.** In a crowd, a model rates by topic, and that is exactly where non-topical facts such as health get lost (35b vs 32, 37, 38).
3. **Distillation is capped by its teacher** (43). Longer training on the same teacher adds 1–6 points.
4. **The reader is its own bottleneck** (41, 43, 44). It leans on the clue being the first block, and it restates and follows wrong picks that look relevant.
5. **An int8 laptop setup is good enough for screening.** Int8 ratings match bf16 at Spearman 0.993, and first answers are identical word for word.

## The GRPO pilot (test 44)

- **Why RL.** It removes the teacher cap, because the reward is what the benchmark measures. The reader was chosen over the rater because rewarding the rater mostly means "picked the known fact", which is test 40's signal, and that failed on new types.
- **Data.** Only the 120 trained-type pairs. Held-out types and val pairs are never seen.
- **Contexts.** 1, 2, 4 or 8 blocks (weights 1:2:2:1). With p = 0.75 the clue is included, at a random place. The other blocks are other users' facts of other types, half of them look-alikes by cosine to the request.
- **Reward.** Clue shown: 1 if the answer acts on it. Clue not shown: 1 if the answer does not act as if it were there.
- **Algorithm.** Dr. GRPO: 8 contexts × 4 samples per step at temperature 1 (no top-k or top-p). Advantage = reward − group mean, no std division, no KL. One update per batch, so the policy ratio is 1 and needs no clipping. AdamW, lr 2e-5, grad clip 1.0, 200 new tokens. Log-probs are recomputed from the sampled ids: prompt embeddings concatenated with the embeddings of the generated ids.
- **Fitting it in about 15 GB (Apple M3 Pro, int8 decoder).** Gradient checkpointing (non-reentrant, train mode only), freeing the generation cache before backward, micro-batch 1, and the LM head applied only to the answer positions with `gather − logsumexp` instead of a full log-softmax. About 1.8 min per step.

| Steps | Reward, clue shown (acts) | Reward, clue not shown | Groups with any spread |
| --- | --- | --- | --- |
| 1–10 | 0.28 | 0.89 | 3.1 / 8 |
| 11–19 | 0.29 | 0.87 | 3.2 / 8 |

- **Reading.** There was no sign of learning in about 600 samples. Only about 40% of groups give a gradient; in the rest, all 4 samples ignore the clue. Per-step noise is ±0.2.
- **Baseline.** With the clue at a random place among up to 8 blocks, the reader acts on it in about 28% of samples. That is lower than greedy decoding in test 43 (0.40–0.60 shown but not first). Two confounds: temperature-1 sampling vs greedy, and 200 vs 300 tokens. A greedy run on the same contexts would separate them.
- **Saved.** The step-10 checkpoint, `lora_grpo_s10.pt`, not yet evaluated.

## What to try next

Ranked by expected value per hour.

### 1. Check 4c: a 27B teacher for the block rater

This is the cheapest test of whether the teacher cap is the whole story. If it passes, the 27B's judgement survives distillation onto 16-token blocks, and inference still needs only one 8B.

1. Serve the 27B with vLLM.
2. Have it rate the block rater's training pairs (`poc_rate27train.py --requests 1000`, about 25k pairs, giving `rater_train27.json`).
3. Train: `poc_tokrater.py --data rater_train27.json --minutes 45 --out lora_tokrater27.pt`.
4. Rate: `poc_tok.py rate --lora lora_tokrater27.pt --raters tokL --tag 27 --wordings change`.
5. Answer: `poc_tok.py answer --tables tokL27_change --conds "top+1+from+8,top+1+from+48,top+2+from+8,top+4+from+48"`.

**Promotion bar:** the clue ranked first of 48 ≥ 0.20, and top 1 of 8 acts ≥ 0.50.

### 2. GRPO v2 on the reader

- G = 8–16 samples per context, so more groups have spread.
- A denser reward: partial credit when the `Relevant fact:` line restates the clue, even if the answer doesn't act on it.
- Reward a `Relevant fact: none` note when the clue is absent, to penalise following a wrong pick.
- Curriculum: the clue first or second at the start, then random places.
- 32 contexts per step and 300+ steps (about 10k samples), with vLLM sampling on a GPU server.
- Evaluate checkpoints on the val pairs, then run the held-out answer test on the best one. The clue-removed control must not rise.
- **Risk:** the reward comes from 8 narrow types, the same narrowness that sank tests 36 and 40.
- **Cheap first step (about 40 min on a laptop):** run the held-out answer test on `lora_grpo_s10.pt` to rule out damage.

### 3. Write-time salience judged by a model

Test 30 showed that an always-on set of "facts that matter whatever the topic" fixes health. But its scores came from hand-written lists, and the label-free scores failed. The untried version asks a model once per fact, at write time, how broadly the fact matters. The top few stay in context, and the per-request rating fills the rest. On the token path, the 8B reads the block. No training is needed.

### 4. A small fast judge

The block rater already has the shape of a "System-1" judge: one forward pass, with the Yes/No logits as the score. A smaller decision model would be faster, not better, unless it is trained on better labels. If check 4c passes, a ~400M bidirectional cross-encoder trained on the 27B labels is worth a look. It reads text, so it leaves the token path.

### 5. Lower priority

- Abstention trained on purpose (the untrained version fails).
- A fact-update test (an old fact replaced by a new one).
- A general-ability check of the reader LoRA, on vs off.
- Tighter flying and no_car rubrics, to remove the floor.
- More seeds and the full 288-row set for the main comparisons, before any paper.

## Constraints the work kept to

- **Stay on the 16-token path.** Text runs are one-off controls only.
- **Do not retrain the core,** and do not fine-tune the encoder or the base decoder. LoRAs and small modules only.
- **Nothing hand-designed as the solution.** No category lists and no rules about which facts matter.
- **Screen cheaply first.** Fast reduced checks on a laptop with an int8 decoder; only winners go to the GPU server.

## Compute

- **Laptop:** Apple M3 Pro, 36 GB, MPS. The int8 weight-only decoder (`torch._weight_int8pack_mm` in a custom autograd function, so a LoRA still trains) is capped at about 15 GB. Typical times on 106 rows: rating 15–36 min; an answer run 24–33 min; 90 min of rater training is 218 steps.
- **GPU server:** 2 × V100 32 GB, fp16 (no bf16, no FlashAttention-2). 27B rating ran at about 14 ratings/s on both cards; 8B at 55–90/s per card. vLLM generated 318 answers in 66 s, against 281 s for HF generate.

## Known traps

- **Old score tables.** Some early score tables keyed scores by request+clue, which collides on 84 of 288 rows. That was fixed in test 41. Key per fact or per row.
- **MPS memory.** Overruns are out-of-memory errors, not swapping. Variable-length batches fragment the cache, so call `torch.mps.empty_cache()`.
- **`.npz` access.** `z["v"]` re-reads the whole array on every access. Read it once.
- **V100.** fp16 training needs a loss scaler. vLLM with `--enable-lora` crashed on the build used and needed an in-memory patch.
- **Rubric floors.** flying and no_car pass without the clue about 20% of the time. Watch health and toddler.

## Project files (for whoever continues)

| File | Role |
| --- | --- |
| `experiments/AGENTMEM_HYPOTHESES.md` | every test 1–44 with full tables |
| `experiments/REPORT_2026-11-24_token_path.md` | the internal version of this report, with run commands |
| `experiments/poc_tok.py` | rate / answer / dry on the token path |
| `experiments/poc_tokrater.py` | train the block rater |
| `experiments/poc_grpo.py` | the GRPO pilot |
| `experiments/poc_rate27train.py` | 27B teacher data for check 4c |
| `experiments/poc_clue.py` | benchmark and rubrics |
| `experiments/q8.py` | int8 decoder loader |
| `work/runs/poc/synth.json` | the benchmark: 252 pairs with rubrics |
| `work/runs/agentmem/lora_lsort.pt` | the current reader |
| `work/runs/agentmem/lora_grpo_s10.pt` | GRPO step 10, not evaluated |

## AI use

This work was done mostly by AI, under human direction. Read the results with that in mind.

| Part | Who did it |
| --- | --- |
| Goals, constraints, which ideas to pursue, what to publish | the author |
| Experiment design, most of the code, running the experiments, analysis | Claude (Anthropic), working as a coding agent in Claude Code, directed by the author |
| Some routine code, including this blog's site generator | a local Qwen model, given a written spec, with Claude checking the output |
| This report and post | written by Claude from the experiment logs, reviewed by the author before publishing |
| Benchmark clue chats | generated by an LLM and checked by regex; filler chats come from Memorilla's demo data |
| Benchmark questions and rubrics | fixed config and regular expressions written during the AI-assisted sessions; no model judges answers at eval time |
| Rater training labels and teacher answers | generated by the 8B and 27B models (that is the method, not a shortcut) |

The models under test (Qwen3-8B, Qwen3-Embedding-4B, a 27B Qwen-family model, and the Memorilla core) are research subjects, not authors.
