docs: host RAM single-copy and elastic session state design (inventory, sparse-memfd option, lazy parking, tasks)
Design only, CPU-only analysis; nothing measured on the server. Finds that the 55.3 GB sealed memfd is read only for the 16.0 GB of PLE rows and that ~39 GB of it is an unread level-2 re-encoding of shard 0 (estimate, census task T1). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
7e66b9491f
commit
7651822366
@@ -0,0 +1,291 @@
|
||||
# Host RAM on the 5090: one copy of each table, and elastic session state (design, no implementation)
|
||||
|
||||
Date 2026-10-30. Branch `claude/mem-design`. Analyst: design/analysis agent, CPU-only. No GPU job was run and the server was not touched (its root NVMe is unstable); every
|
||||
number below comes from the code in this tree or from a document already in the repository, with the path named.
|
||||
|
||||
Evidence labels: **M** measured (a log or document records it), **S** read from source, **E** estimate (derivation given), **U** unverified / needs a run.
|
||||
Nothing here is a performance claim (AGENTS.md): every speed statement about a future change is an E or U and the tasks in section D carry the paired A/B that would turn it into a result.
|
||||
|
||||
Owner requirements this page answers: (1) "dual use of memory is stupid" on the 5090 profile; (2) session state that moves to RAM must not be reserved at full-window size:
|
||||
allocate on use, hard cap, evict under pressure, compress when parked.
|
||||
|
||||
## 0. Result in ten lines
|
||||
|
||||
1. **The two big host tables are not the same bytes, but the sealed memfd does hold a second copy of the model.** The 55.3 GB memfd is the pinned level-2 KAR archive. The engine reads
|
||||
exactly one thing from it: the PLE n-gram rows (320,001,536 rows x 50 B = 16.0 GB, S). The other 39.3 GB (71 %, E) is a lossy level-2 re-encoding of the same shard-0 tensors
|
||||
(routed experts and dense weights) that the resident bank was built from, and the Original serve path never reads it (S, section A.4). It costs 36.6 GiB of unswappable-by-choice shmem for nothing.
|
||||
2. The resident expert bank (46.84 GiB) is built from GGUF shard 0, not from the memfd, and is read by the VRAM tier fill, the PCIe staging, the CPU expert leg and the prefill ring (S).
|
||||
It is not removable on this profile, and mapping it instead would save ~0 at 256k (the prefill touches the whole bank every chunk, E) while risking speed (section B).
|
||||
3. **Recommended single-copy step: a sparse memfd that holds only the PLE extents** (bits identical, same pages read, no speed risk): host RAM at 256k falls from ~109 GiB to ~72 GiB
|
||||
accounted (E). Everything else in section B is either no gain at 256k or a fallback for smaller hosts.
|
||||
4. Today's inventory at a 245k session: about 109 GiB accounted of ~121 GiB, matching the measured turn-5 picture (anon 55 + shmem 56.5 + file ~7 GiB, MemAvailable 8.6 GiB; section A).
|
||||
5. Session state: the prefix cache **budget** is not reserved, it is a ceiling that the governor sizes to be filled on purpose (75 % of what is left, 5.7-6.1 GiB today, ~31 GiB after step 3 if left on
|
||||
`auto`: a hazard this page flags). The only real reservation is the pinned K/V image (3.094 GiB, allocated whole at open, and it is the live session, not staging).
|
||||
6. The store keeps a second copy of the live session's K/V (blocks are copied out at every grid chunk) although the pinned image already holds it: ~3.5 GiB at 245k (E from 14,208 B/token).
|
||||
Parking on overwrite instead of on every chunk removes it in the single-session case and costs about 0.27 s at the moment of a switch (E from the measured 13-14 GB/s restore).
|
||||
7. Hybrid model: K/V is 12 QSA layers x 1,056 B = 12,672 B/token (14,208 B with the index rows): 3.09 GiB per 256k window; the 36 GDN layers add a constant 112.2 MiB. A parked 256k session is
|
||||
~3.6 GiB raw (S/E).
|
||||
8. CPU compression of parked state is a weak lever: int8 K/V 1.06-1.20x and fp32 GDN ~1.2x by entropy bound on synthetic data (E, section C.5). Cap, lazy parking and idle trimming first; measure
|
||||
real blocks before building a codec.
|
||||
9. A restore beats a re-read by two orders of magnitude: ~0.27 s (E) against ~55-60 s for 245k tokens (M: sum of the five-turn TTFT, 57.3 s). The "10-12 s" figure is the per-turn
|
||||
delta of ~50k tokens, not a full re-read.
|
||||
10. Tasks (section D): archive census, prefix hard cap, sparse memfd (code), the 5090 A/B with identity, lazy parking, then compression measurement.
|
||||
|
||||
## A. Inventory of host RAM at 256k on the 5090 profile
|
||||
|
||||
Profile `deploy/rust-runtime/profiles/rtx5090-32g.json`: `kar_source: memfd`, `expert_source: resident`, `context_tokens: 262144`, `prefill_capacity: 8192`, prefix cache `auto`, tail `reply`,
|
||||
block 8192, lock `try`, heal on. Host: 121 GiB visible (decode-tail doc), 9950X3D, 15 pinned CPU expert workers. All sizes GiB unless marked.
|
||||
|
||||
### A.1 The table
|
||||
|
||||
"Class" is the kernel's view: shmem (memfd and `cuMemHostAlloc` mappings, counted in neither `MemAvailable` nor reclaimable), anon (heap, swappable unless locked), file (page cache, reclaimable).
|
||||
"When": S = at stack open, L = lazy, E = elastic (grows with use).
|
||||
|
||||
| # | consumer | GiB | class | when | source | who reads it |
|
||||
|---|---|---:|---|---|---|---|
|
||||
| 1 | sealed KAR memfd, 55,295,529,472 B | **51.50** | shmem | S | M (`docs/memory-safety.md` 3.1: 52,733.9 MiB; `deploy/src/profile.rs` `ARCHIVE_BYTES`) | PLE row reads only (A.4) |
|
||||
| 1a | of which PLE extents: 320,001,536 rows x (10 B scales + 2 x 20 B planes) | 14.90 | | | S (`model-format/src/kar.rs` `read_rows_chunk`), E for the byte count | `KarPleBinding::read_rows*`, prefill read-ahead `row_reader`, `KarPleCache` misses |
|
||||
| 1b | of which everything else in the archive | **36.60** | | | E (A.4) | nothing on the serve path |
|
||||
| 2 | resident routed-expert bank, 144 tensors of shard 0 (50,292,326,400 B) | **46.84** | anon, registered (page-locked) lazily by `cuMemHostRegister` | S | M (`laptop-profile.md`, `memory-safety.md` 8: RssAnon 49,690 MiB at load) | VRAM tier fill, PCIe staging, CPU expert pool, prefill ring, slot refill (A.5) |
|
||||
| 3 | pinned K/V host image, 12 layers x 276,825,088 B | **3.09** | shmem (device-mapped pinned) | S | M exact (`context/src/geometry.rs`, `memory-safety.md`: plan equals measurement) | QSA layers read pages over PCIe; it is the authoritative copy of the live session |
|
||||
| 4 | native head + embedding mapped host copy (pinned) | 0.31 | shmem | S | M (322 MiB, `vram-footprint-5090.md`) | decode gather over PCIe |
|
||||
| 5 | MTP drafter / verifier pins | 0.26 | shmem | S | M (~266 MiB, `memory-safety.md` 3.1) | drafter |
|
||||
| 6 | dense weights, host side | 1.37 | anon | S | M (+1,403 MiB RSS at the dense stage) | upload source; **may be freeable after upload (U, T12)** |
|
||||
| 7 | MoE arena host side + CPU pool scratch | 0.10 | anon | S | M (74 + 28 MiB) | prompt MoE, CPU pool |
|
||||
| 8 | rings, stager buffers, empty-prompt checkpoints, tokenizer, thread stacks (unattributed) | ~1.5 | mixed | S | E: 3,686 MiB (`OTHER_FIXED_ESTIMATE_RESIDENT`, M from job 945) minus rows 4-7 | various |
|
||||
| 9 | prefix store (blocks 14,208 B/token + node states ~127 MiB each) | 0 -> budget | anon | E | M (`prefix-cache.md`; budget 5.7-6.1 GiB `auto`); use at 245k E: 3.24 blocks + ~0.5 nodes | restore path only |
|
||||
| 10 | conversation checkpoints, 118 MiB each | 0 | anon | E | S (`memory_governor.rs`: 0 when the prefix cache is on; 6 x 118 MiB = 0.69 GiB when it is off) | Original-style conversation cache |
|
||||
| 11 | page cache (logs, binaries, PTX, MTP pack, tokenizer; shards dropped after load) | ~7 | file | L | M (owner, turn 5) | reclaimable |
|
||||
| 12 | gateway, supervisor/holder, kernel structures | ~1-2 | mixed | S | E | |
|
||||
|
||||
Device (VRAM) holds its own, separate inventory (`vram-footprint-5090.md`); the VRAM window of K/V is 251.7 MiB, the rest of the 256k window lives only in row 3.
|
||||
|
||||
### A.2 Totals
|
||||
|
||||
| view | GiB | basis |
|
||||
|---|---:|---|
|
||||
| fixed at open: rows 1-8 | **105.0** | 51.50 + 46.84 + 3.09 + 0.31 + 0.26 + 1.37 + 0.10 + 1.5; cross-check: `resources.rs` plans `ARCHIVE_BYTES + 54 GiB` = 105.5 (S) |
|
||||
| + prefix store at a 245k session (row 9) | ~109 | E |
|
||||
| + page cache and gateway (rows 11-12) | ~117 | E |
|
||||
| measured at turn 5 (owner, 247k): anon 55 + shmem 56.5 + file ~7 | 118.5 | M; MemAvailable 8.6; read as GiB it reconciles with the table: shmem = rows 1+3+4+5 = 55.2 (+~1.3), anon = rows 2+6+7+9 = 54-56 |
|
||||
| vanilla Strata at turn 5 (same card) | anon 54.7, MemAvailable 9 | M (`decode-tail-5090.md` section 4): vanilla also runs near the floor, but its PLE is a file mapping, not a memfd |
|
||||
|
||||
Of the 105.0 GiB fixed, **36.6 GiB (35 %) is never read** (row 1b) and 3.5 GiB more is a duplicate of the live K/V (A.6). That is the real "dual use".
|
||||
|
||||
### A.3 What the planner and governor assume (S)
|
||||
|
||||
* `crates/leleka-memory/src/plan.rs`: `A = MemAvailable` at start; `F` = fixed items still to allocate (resident bank 50.3 GB, pinned K/V, `OTHER_FIXED_ESTIMATE_RESIDENT` 3,686 MiB);
|
||||
the memfd is **inherited, so it is already out of `MemAvailable`** (`KarForm::MemfdInherited`, K = 0). `R = A - F - K` must stay above `soft_floor 4 GiB + reserve 2 GiB`. The remainder
|
||||
`elastic = R - floors` is handed out: resident complement (mapped form only), then the prefix cache `auto` = **75 % of the elastic memory, ceiling 96 GiB, off under 1 GiB**.
|
||||
* `auto_prefix_budget` repeats the rule when the stack opens, from the live `MemAvailable` after the bank is resident; that second value is the one in force (5.7-6.1 GiB on the 5090).
|
||||
* Pressure monitor: `shed` below the soft floor (prefix cache evicts to 3/4 per second, insertions stop at `soft + reserve` = 6 GiB), `reject` below the hard floor (503 `memory_pressure`).
|
||||
* Deploy plan: `resources.rs` computes `footprint = ARCHIVE_BYTES + 54 GiB`; if `available - footprint < target + reserve` it **switches the profile to `kar_source=file` + `expert_source=mapped` with
|
||||
`resident_budget_gib = min(46, (avail - target - reserve - 8 GiB))`** (S: the fallback ladder already exists at plan time, not at run time). `preflight.rs` requires 113 GB available for the profile.
|
||||
|
||||
### A.4 What reads the memfd, and what is in it
|
||||
|
||||
* Reads (S): `InheritedKarArchive` -> `load_pinned_inherited_archive` -> `VerifiedKarPleArtifact` -> `read_rows`/`read_rows_batch`/`row_reader`, whose only I/O is `read_rows_chunk`: three positional reads
|
||||
per PLE row (10 B of scales at `scales + 10*row`, 20 B at `planes + 20*row`, 20 B at `planes + stride + 20*row`). Consumers: `KarPleCache` (decode rows, prefill batches, read-ahead). The governor maps the
|
||||
descriptor only to lock it and count swapped pages (`archive_handle` comment).
|
||||
* Not read (S): the engine args built by `deploy/src/config.rs` contain no KAR expert-source argument, so `kar_expert_source` is `None`; `docs/original-serve.md` states the Original executors
|
||||
"read the pinned model's own mapped routed experts, not a KAR level decode". `qwen4exp_inherited_kar_gpu.rs` is a seal test fixture.
|
||||
* Content (E, two independent derivations that agree):
|
||||
1. The pinned profile (`qwen4exp_kar_ple.rs` `pinned_profile_spec`) has a virtual F32 stream of 707,775,598,080 B; the first PLE part starts at 502,974,615,040 B, so **71.1 % of the stream precedes the
|
||||
PLE parts** and is other tensors (shard 0: routed experts and dense weights). PLE is 204,800,983,040 B of it (28.9 %).
|
||||
2. Level-2 nested coding costs the same per element everywhere: PLE 16,000,076,800 B over 51.2 G elements = 2.50 bits; the remaining 39,295,452,672 B over 125.7 G elements (502.97 GB / 4) = 2.50 bits.
|
||||
`build-validation.md` independently measured a level-2 IQ3_S expert slice at 75 % of its GGUF size.
|
||||
The experiment doc `2026-10-03-kar-ple-ab.md` and `compressed-runtime.md` agree on the purpose: the archive "serves only the PLE tensor from KAR; other model weights remain in the native pack".
|
||||
`laptop-profile.md` calls the level-2 experts lossy (relative L2 ~0.33, no quality gate), so they are not a usable source either.
|
||||
* So the memfd's extra 36.6 GiB is dead weight, not a safety net. **U until T1 prints the archive directory** (a CPU-only read of ~1 MB on the server).
|
||||
|
||||
Can the CPU expert kernels read the memfd directly with the same bits? **No.** The kernels consume GGUF block layouts (IQ3_S/IQ4_NL/IQ2 blocks, `native-cpu-expert`); the memfd holds nested bit-plane KAR coding
|
||||
that is a different, lossy representation. The "mapped" mode of the laptop profile maps **GGUF shard 0** (`load_mapped_expert_source`, `model-format/src/qwen4exp_expert_source_bank.rs`), whose bytes are the verified file's,
|
||||
so a CPU kernel sees the same bits through the mapping as through the resident copy (S: `mapped.len() == descriptor.bytes`, same descriptor, "every consumer sees exactly what the resident copy would hold").
|
||||
|
||||
### A.5 Why the resident copy exists, and who reads it
|
||||
|
||||
Built by `Qwen4ExpArtifact::load_resident_expert_source`: for each of 48 x 3 expert tensors, `shards[0].load_resident_tensor` copies the raw bytes into anonymous memory (admission against `MemAvailable`,
|
||||
cap 52 GiB, no finite scan; the shard page cache is dropped afterwards by `drop_file_cache`). Readers (S):
|
||||
|
||||
| reader | what it reads | frequency | cost of a pageable source |
|
||||
|---|---|---|---|
|
||||
| VRAM tier fill and `refill_lent` | expert bytes by profile rank, one blocking copy per slot (11,280 slots = 21.5 GiB) | at open; the lent prompt slots (2,238, ~4.2 GiB) refilled after every prefill, 307-419 ms (M) | page faults and a staged copy |
|
||||
| prefill ring (`moe.ring`) | every expert the arena cache does not hold, by DMA straight from the registered bank | every chunk: 15,534 ring entries per 8192 chunk (M, `upstream-port-plan.md`), ~34 GB per chunk at the 2048 shape, ~45 GB/s (M, `prefill-throughput.md`) | pageable banks take the `Stager` path (helper threads copy into pinned buffers); measured only on the laptop |
|
||||
| decode PCIe share | missed experts DMA'd to staging slots (13-60 per window, seed off, M) | every window | pageable DMA is slower; the code refuses PCIe staging for a pageable bank unless `pcie_frac` is set explicitly (laptop: 6.7 vs 10-12 tok/s, M) |
|
||||
| decode CPU leg | missed experts computed in place by the 15-worker pool (23-79 per window, ~3.9 ms of a ~15 ms round) | every window | the same bytes, read through page cache instead of anon |
|
||||
|
||||
The bank is page-locked (`cuMemHostRegister`) because registered memory is what lets the copy engine DMA from it without a bounce buffer; that, plus the whole-bank prefill sweep, is the reason the 5090
|
||||
profile asks for `resident`.
|
||||
|
||||
### A.6 The duplicate of the live K/V
|
||||
|
||||
The pinned K/V image (row 3) is the live session's whole 256k K/V. After every grid chunk the prefix store may copy the new cells into immutable blocks (`PrefixStore::consider`, 14,208 B/token) so that a
|
||||
different session can later overwrite the positional buffer without losing them. In the single-session case those copies are never read (the live buffer is continued, "copies no K/V at all",
|
||||
`prefix-cache.md`), yet they occupy 3.24 GiB (245k) of the budget. Nodes (GDN images, 127 MiB each) are the part that cannot be reconstructed from the live buffer.
|
||||
|
||||
## B. Options for a single copy
|
||||
|
||||
Premise correction first: option 3 as phrased ("drop the memfd after building the resident copy") does not apply, because the resident copy is **not** built from the memfd. The real options:
|
||||
|
||||
| option | RAM saved at 256k (E unless noted) | risk | speed risk | changes | test |
|
||||
|---|---|---|---|---|---|
|
||||
| **B0 sparse memfd: only the PLE extents are filled, the rest are holes** | **36.6 GiB** (row 1 51.5 -> 14.9); MemAvailable at turn 5 from 8.6 to ~45 | low: same rows, same pages, same bits; the verification model changes (below) | none expected (reads hit the same pages; a hole is never read) | `deploy/src/sealed.rs`: fill a range list instead of `0..total`; `model-format/src/kar.rs`: pinned digest of the extents, refuse reads outside them; `leleka-memory` `guard_archive`: lock and heal **only the extents** (`mlock`/`MADV_POPULATE_READ` on a hole would allocate it); `KarForm` bytes and deploy `ARCHIVE_BYTES`/`min_ram_available` use the extent size | rows through the sparse memfd equal rows through the file (property test over random rows incl. partition seam 200,000,000); greedy-id identity and A/B on the 5090 (T4) |
|
||||
| B0' PLE-only archive file (new pin, 16 GB) | same RAM; also 39 GB less disk and hashing | medium: new archive digest, provenance, receipts | none | offline repack tool, new constants everywhere the 55.3 GB archive is pinned | CRC and row identity against the old archive |
|
||||
| B1 `expert_source: mapped`, nothing pinned | ~0 in steady state at 256k: one 180k request already touched ~46 GiB of the mapped bank (M, job 911, `memory-safety.md` 3.1); the bytes only become reclaimable | high | prefill: pageable `Stager` instead of direct DMA (E: material loss of the 34 GB/chunk stream, never measured on the 5090); decode PCIe share off or slow; after a 40 GiB competing reader evicted part of the file-mapped bank, the first two requests decoded at 11 tok/s against 17-19 (M, 5090 job 917, `memory-safety.md` 5.5; old small-tier config, so the ratio, not the rate, is the evidence) | none (exists) | only as a measured negative control |
|
||||
| B2 hybrid `mapped` + `resident_budget_gib` | up to 21.5 GiB become reclaimable if the pinned budget is the VRAM-complement only (13,296 experts x ~1.95 MiB = 25.4 GiB, E); not a hard saving | medium: the unpinned part is file-backed and the model volume is the unstable disk | PCIe share of unpinned misses and the 4.2 GiB refill read pageable pages; `LELEKA_PCIE_LOCKED_ONLY` and `pcie_frac` exist to bound it | none for the mechanism: `pin_resident_complement` pins by profile rank, clamped to `MemAvailable - 4.25 GiB`; only valid with `mapped` (guards at `original_serve_residency.rs:1144`, `memory_governor.rs`) | T10: arms at 100 %, 60 %, 0 % of the complement pinned |
|
||||
| B3 drop the memfd after building the resident copy | n/a: the memfd is not a build input and PLE needs it for the life of the process | | | | |
|
||||
| B4a PLE as an ordinary file (`kar_source: file`, stamps skip the hash) | 14.9 -> page cache of the touched rows; E: 1M distinct rows after ~250k tokens (decode-tail 4) x up to 3 pages = 4-12 GiB | medium: random 4 KiB reads on the model volume; no sealed immutability (weaker form, `qwen4exp_kar_ple.rs` doc) | cold row reads on prefill; `window.ple` today 0.1-0.2 ms | none (laptop form) | T14 |
|
||||
| B4b native PLE from shard 1 (IQ4_NL, 90 B/row, direct I/O) | 14.9 -> ~0.1 | high: **not ported to the Original serve path** and different numerics than KAR L2 (A/B showed matching outputs only on short suites) | unknown | large | not planned |
|
||||
| B4c free the host copy of the dense weights after upload | up to 1.4 GiB | low | none | verify first that it is retained for a reason | T12 |
|
||||
|
||||
### Recommendation
|
||||
|
||||
**B0, in that order of care: T1 (census) -> T3 (code) -> T4 (A/B).** It removes the only copy that is never read, keeps every consumer on exactly the bytes it reads today, and needs no model-quality gate because
|
||||
nothing a kernel reads changes. Keep `resident` for the expert bank on the dedicated profile. Keep the existing plan-time fallback to `mapped` + budget for smaller hosts and treat B2 as the measured
|
||||
version of that fallback rather than as a default.
|
||||
|
||||
How B0 keeps the fail-closed property. Today the engine hashes the whole archive on a memfd unless the parent "attested" the copy (`verify_stamp::set_attested_archive`, `kar.rs` `attested_memfd`); the
|
||||
supervisor verifies the file (stamp or full hash) before copying. With holes, the engine cannot hash the archive. Instead: (a) the supervisor copies only the extents of the two PLE parts plus the header, directory
|
||||
and the book words (a handful of ranges, ~16.0 GB); (b) a **pinned SHA-256 of the extent bytes** (computed once from the pinned archive, T1) is checked by the engine on the memfd, ~16 GB, a few seconds, instead of
|
||||
55 GB; (c) the reader refuses any offset outside the extents (they are all derived from `VerifiedPart`, so a bug cannot read a hole silently); (d) the provenance digest check stays.
|
||||
|
||||
Interaction hazards found while reading (all in the change list above): `guard_archive` maps the descriptor and `mlock`s it in chunks, and heal uses `MADV_POPULATE_READ`; both would instantiate the holes
|
||||
(55 GB of zero pages) if pointed at the whole mapping. The deploy preflight and `resources.rs` constants (`ARCHIVE_BYTES`, `min_ram_available_bytes 113e9`) must use the extent size or the profile
|
||||
will keep refusing hosts that now fit.
|
||||
|
||||
Projected host picture at 256k after B0 (E): PLE 14.9 + bank 46.84 + K/V 3.09 + other 3.6 = **68.4 GiB fixed**, plus a capped prefix store (D, T2: 6 GiB now, 8 later) = ~74-77 GiB of 121; the 8.6 GiB of
|
||||
MemAvailable at turn 5 becomes ~40-45 GiB.
|
||||
|
||||
**Hazard created by B0 alone:** `auto` would then size the prefix cache from the freed memory (75 % of ~40 GiB = ~30 GiB). Without a cap the freed RAM would be refilled "on purpose" by cached blocks.
|
||||
T2 (an explicit cap in the profile) must land before or with T3.
|
||||
|
||||
## C. Elastic session state
|
||||
|
||||
### C.1 How it is budgeted today (S unless marked)
|
||||
|
||||
| state | where | sizing | allocated | released |
|
||||
|---|---|---|---|---|
|
||||
| live K/V (12 QSA layers) | pinned host image, 3.094 GiB | whole serving context | at open, `cuMemHostAlloc` | process exit |
|
||||
| VRAM K/V window | 251.7 MiB, `--kv-resident 32768` | fixed | at open | exit |
|
||||
| GDN state (36 layers) | device, 112.2 MiB (`gdn_state_bytes` 117,669,888, golden from the C++ `conversation_state_sizes`), PLE history 360 KiB | fixed | at open | exit |
|
||||
| prefix store blocks | pageable heap, 14,208 B/token | ceiling = `auto` budget (A.3) | per insertion, after each grid chunk (and at request end with tail `reply`) | evict by score (expected tokens saved per byte), TTL 60 min, shed on pressure + `malloc_trim` (`heap.rs`) |
|
||||
| prefix store nodes | ~127 MiB each (GDN/PLE images, draft ring snapshot, index tails) | counted in the same budget | with the node | with the node |
|
||||
| conversation checkpoints | 118 MiB each, `--prompt-cache 6` | only when no prefix cache | at request boundaries | LRU, root pinned |
|
||||
| `Policy.prefix_cap` | 96 GiB (24 laptop) | no env knob | | |
|
||||
|
||||
What "plans fullness on purpose" means in the code: `auto_prefix_budget` = 75 % of `available - (soft_floor + reserve)`; `plan()` subtracts the fixed items and then hands the cache the share of what is left,
|
||||
so the thresholds (shed at 4 GiB, admit stop at 6 GiB) are chosen so that a **full** cache is survivable (`memory-safety.md` section 8: "the plan designed a minimum of 7 GiB available with the cache full").
|
||||
The memory is not committed up front; it is committed by use and the plan assumes use will reach the ceiling. Only the pinned K/V (and the fixed items) are true reservations.
|
||||
|
||||
### C.2 Real sizes from the model geometry (S, `crates/context/src/geometry.rs`, `qwen_forward/original_serve_stack.rs`)
|
||||
|
||||
Qwen3.8-Flash-Next here has 48 layers: **12 QSA (attention) + 36 GDN (recurrent)**. Only the QSA layers carry a per-token cache.
|
||||
|
||||
| quantity | per token | at 245k | at 262,144 (256k window) |
|
||||
|---|---:|---:|---:|
|
||||
| K/V int8 + scales (K 512 B, V 512 B, K scales 16 B, V scales 16 B per cell per layer = 1,056 B) x 12 layers | 12,672 B | 2.89 GiB | **3.094 GiB** (= 12 x 276,825,088 B, the pinned image, M) |
|
||||
| pooled index rows (128 B per cell per layer) x 12 | 1,536 B | 0.35 GiB | 0.375 GiB |
|
||||
| block in the prefix store (K/V + index) | **14,208 B** | **3.24 GiB** | **3.47 GiB** |
|
||||
| GDN state + PLE history + index tails + draft ring snapshot, per node | constant | ~127 MiB (M) | ~127 MiB |
|
||||
| **a parked 256k session, one node** | | ~3.4 GiB | **~3.6 GiB** |
|
||||
|
||||
For scale: the same window on a dense 48-attention-layer model of this width would be 4x the K/V (~12 GiB); the hybrid layout is why parking is affordable at all. The GDN state does not grow with context, so
|
||||
it is paid per node, not per token. A thinned session keeps the frontier, the previous one or two, and a geometric spread of older nodes (`prefix-cache.md`), i.e. ~3-6 nodes: 0.4-0.8 GiB.
|
||||
|
||||
### C.3 Session multiplexing: what exists
|
||||
|
||||
* One generation at a time (`parallel 1` is the vanilla launch shape too, `s0-7-vanilla-arms.md`; the store "needs no locking").
|
||||
* Switching conversations already works through the prefix store: a session returning after another one finds its nodes by hash chain, writes back **only the blocks the other session overwrote**
|
||||
into the pinned image (`import_parked`), installs the GDN/PLE images and re-anchors the draft ring. Measured on the 5090: 98k tokens (1.4 GB) in 101 ms, 172-180k tokens (2.4-2.6 GB) in 175-194 ms (13-14 GB/s,
|
||||
M, `prefix-cache.md`), against 28-55 s of prefill at that time.
|
||||
* `NO_PARKING` (`original_serve_conversation.rs`) refers only to the Original's *whole-conversation* snapshot cache (`--conversation-cache-mib`), which the prefix store replaces; the six-checkpoint
|
||||
conversation cache remains for the no-prefix-cache path. Upstream's batch-slot parking series (`01e404c1`, `cea3ed40`, `c7a0cef1`, rows B2/B3/R16 of `docs/upstream-review/cpu-and-platform.md`) is for batch mode and was
|
||||
judged "n/a, ours is single-stream"; its parked-K/V-in-VRAM and ready-pool ideas are not wanted here (VRAM is the scarce side).
|
||||
* Upstream's own numbers for parking are a useful bound: restoring a parked 64K conversation 0.97 s against 49 s (P100, `engine/strata/docs/RESEARCH_RUNS.md`), and its stalls were caused by the OS paging the engine
|
||||
while it parked (DETAILS.md): parking must never allocate in a way that competes with the pinned banks.
|
||||
|
||||
### C.4 Cost of a parked 256k session, raw and compressed, and restore against re-read
|
||||
|
||||
| | raw | compressed (E) |
|
||||
|---|---:|---:|
|
||||
| blocks, 245k tokens | 3.24 GiB | 2.7-3.1 GiB at 1.06-1.2x |
|
||||
| one node | 127 MiB | ~105-120 MiB at ~1.1-1.2x |
|
||||
| restore, 245k tokens | **~0.27 s** (E: 3.48 GB at the measured 13-14 GB/s) | + decompress: 3.5 GB raw at ~1-1.5 GB/s per core x 8 cores = 0.3-0.5 s (E, typical zstd -1 speeds; U on this CPU) |
|
||||
| re-read (prefill) of 245k tokens | **~55-60 s**: M, the five-turn TTFT sum is 57.3 s (`upstream-port-plan.md`, rest-full2) for 247k tokens, per chunk 1.68 s at 139k | |
|
||||
|
||||
The "re-prefill of 245k takes ~10-12 s" in the task brief is the per-turn TTFT (10.5-13.2 s, M) of a ~50k-token delta, not of a 245k read. Either way a restore wins by 25-200x, so the decompression budget is
|
||||
generous: even a slow codec leaves the switch under a second. The design question is therefore RAM, not latency.
|
||||
|
||||
### C.5 Compression: what to expect
|
||||
|
||||
Measured here on synthetic data only (`scripts/memory/entropy_bound.py`, absmax-int8 quantization of 128-wide vectors, 0-order entropy and zlib-1 as a stand-in for LZ; E, not a measurement of the model):
|
||||
|
||||
| data | entropy bits per byte | ideal entropy coder | zlib-1 |
|
||||
|---|---:|---:|---:|
|
||||
| int8 codes of Gaussian vectors | 7.53 | 1.06x | 1.05x |
|
||||
| int8 codes of Laplace vectors | 7.01 | 1.14x | 1.12x |
|
||||
| int8 codes of heavy-tailed (Student-t-like) vectors | 6.65 | 1.20x | 1.17x |
|
||||
| fp32 Gaussian state, raw / byte-plane shuffled | b0..b3: 8.0, 8.0, 7.97, 2.6 | 1.20x | 1.08x / 1.16x |
|
||||
|
||||
Reading: a byte-oriented LZ (lz4) finds almost nothing in quantized K/V; an entropy stage (zstd, level 1-3) gets 5-20 %; fp32 GDN gains only after a byte shuffle. Real K/V has outlier channels (absmax scaling
|
||||
leaves the other channels on few levels), so the real ratio may be better than the synthetic bound (U): that is exactly one measurement, T8. A lossy shrink (fp16/bf16 GDN state, q4 K/V, which the session
|
||||
policy has switches for) would halve a part but changes numerics, so it stays an experimental, quality-gated mode (AGENTS.md) and is out of scope.
|
||||
|
||||
CPU contention is real: the 15 expert workers sit on 15 physical cores and the CPU leg is ~3.9 ms of every ~15 ms round, so compression threads must run **only while no request is active** (or at idle priority on
|
||||
the SMT siblings), never during a window. Compression is therefore a background pass on parked blocks, not part of the request path.
|
||||
|
||||
### C.6 Design: lazy, capped, evicted under pressure, compressed when parked
|
||||
|
||||
1. **Hard cap first.** Replace "fill the elastic share" with `prefix_cache_mib = min(explicit cap, 75 % of elastic)`; the 5090 profile gets an explicit cap (T2: 6,144 MiB = today's `auto`, then sized by sessions, e.g.
|
||||
two 256k sessions + nodes = 8 GiB). The cap, not free RAM, defines "full". Freed RAM stays free.
|
||||
2. **Commit on use, per tier.** Blocks and nodes are already built on insertion; keep that. Do not preallocate anything for sessions. The pinned K/V image stays a fixed reservation (it is the live session);
|
||||
a lazily pinned image (64-256 MiB steps registered over one reserved virtual range) is possible (T13) but saves nothing at 256k and only matters for idle hours.
|
||||
3. **Park on overwrite, not on every chunk.** Nodes (GDN states, 127 MiB) are still admitted at grid points because they cannot be rebuilt. Blocks are copied out of the pinned image only when the next
|
||||
prefill is about to overwrite cells that no stored block covers (the request path already tracks `live`, the cells known to hold the current prompt). Single-session continuation then stores no
|
||||
blocks at all (-3.2 to -3.5 GiB at 245k, E); a switch pays one memcpy of the overwritten tail, <= ~0.27 s (E), instead of nothing on the switch and a permanent copy of every session. Failure behaviour:
|
||||
the live image stays authoritative until the copy completes; a cancelled request parks nothing it did not finish.
|
||||
4. **Evict under pressure in this order:** compressed blocks of the oldest sessions -> raw blocks of the oldest sessions -> nodes of the oldest sessions -> everything but the frontier (the existing
|
||||
`shed` ladder, scoring by tokens saved per byte), with `malloc_trim` after each (existing). Add an idle rule: after N minutes without a request (default 10) compress what is raw; after the retention time
|
||||
(60 min) drop. Admission keeps the `soft_floor + reserve` stop that exists.
|
||||
5. **Compress when parked, in the background, only when idle.** Per block, byte-shuffle for GDN images, zstd level 1-3 (or none when T8 measures < 1.15x). Decompress on restore on the restore threads before the
|
||||
`import_pages` memcpy. A block header carries `{codec, raw_len, crc}` so a corrupt or truncated entry falls back to a re-read (a miss), never to wrong state.
|
||||
6. **Telemetry:** `prefix.store` keeps raw and compressed bytes, bytes parked on overwrite, restores, restore ms and bytes, evictions by reason; `/v1/status` -> `memory` already carries the inventory. Acceptance
|
||||
below uses `scripts/e2e/sample_env.sh` series (RssAnon, RssShmem, VmLck, MemAvailable).
|
||||
|
||||
## D. Tasks (small leaves, ordered by value / effort)
|
||||
|
||||
A/B protocol for every GPU row (charter: paired, same workload, quality result, full record): RTX 5090 server, one heavy job at a time under `/data/leleka-e2e/gpu.lock`; frozen corpus
|
||||
`/data/leleka-e2e/decode/corpus/src/crates` (file-list sha256 `1152f45acaa9a62591e50d8f6807f50ce6fe1249db659cdb9e8e4a041ed119a7`, 14,132,376 chars); `scripts/e2e/long_session.py` five turns
|
||||
(45.8k / 105k / 153k / 199k / 247k prompt tokens, 300 output tokens, greedy); upstream profile `data/expert-profile.bin` (sha `8f59b4aa...388975baf`); shards `4c1eb2ce...`, `316b46f3...`; archive
|
||||
`536d612c...`; production env of the profile; chunk 8192; 3 runs per arm, arms interleaved; record binary sha256, driver 595.99, CUDA 13.2, kernel, page-cache state at start (dropped or not), RSS/shmem/anon/
|
||||
MemAvailable/swap series every 5 s, TTFT and decode tok/s per turn with the distribution, token counts, and the engine log. Identity row = greedy ids equal and top-16 logprobs bitwise equal where the change is
|
||||
declared non-numeric.
|
||||
|
||||
| # | task | GPU? | acceptance gate | estimate |
|
||||
|---|---|---|---|---|
|
||||
| T1 | **Archive census.** Server, read-only, ~1 MB read: dump the KAR directory (`leleka model inspect-kar` or the `KarInspection` records): name, class, bytes per record. Compute the PLE extents and their SHA-256. | no (server read-only; do when the server is back) | PLE extents total 16.0 GB +- header/books; non-PLE records total 39.3 GB; extent list equals the `VerifiedPart` offsets used by `read_rows_chunk` | 1 h |
|
||||
| T2 | **Prefix hard cap in the 5090 profile**: `memory.prefix_cache_mib: 6144` (no change today; protects against T3's freed RAM being refilled). Deploy tests updated. | no | deploy tests green; engine log shows the cap; owner confirms the value | 1 h |
|
||||
| T3 | **Sparse memfd, code**: `ple_extents` from `KarInspection` + `PLE_EXTENTS_SHA256`; `sealed.rs` sparse fill; engine verify-by-extents and refuse outside; governor lock/heal over extents; `KarForm`/`ARCHIVE_BYTES`/`min_ram_available` use the extent size; flag `kar_source: memfd` keeps full copy unless `kar_fill: ple` | no | unit/property tests: random rows (incl. seam at row 200,000,000 and last row) equal through sparse memfd and file; `st_blocks` ~ extents; holes unread; hash mismatch and out-of-extent read fail closed; miri-clean modules stay clean; laptop WSL run on a synthetic archive | 2-3 d |
|
||||
| T4 | **[GPU] Sparse memfd A/B + identity** (arms: full memfd vs sparse, same binary except the flag) | yes | greedy ids identical on all five turns and top-16 logprobs bitwise equal (a lossless repack must be exactly equal, not "within tolerance"); decode tok/s and TTFT per turn within the run-to-run noise (decode-tail: 3-8 %); RssShmem -36 GiB +- 1; MemAvailable at turn 5 >= +35 GiB; zero swap; `window.ple` unchanged | 0.5 d + runs |
|
||||
| T5 | **Store use analysis, offline**: from existing logs (`runs/*/inference.log`, CRM job 945, the 5-turn runs) count bytes of blocks admitted vs bytes ever restored, per session shape | no | a table: share of admitted block bytes ever read back in single-session vs alternating runs | 0.5 d |
|
||||
| T6 | **Park on overwrite** behind `LELEKA_PREFIX_PARK=lazy` (default eager until T7 passes): nodes at grid points, blocks at overwrite; telemetry | no (code/tests) | store unit tests (sharing, refcount, restore of a lazily parked path equals an eager one); `prefix_tail_equivalence.py` equivalence; cancel/failure tests leave no claim over unfinished cells | 3 d |
|
||||
| T7 | **[GPU] Lazy parking A/B**: (a) single session five turns, (b) two sessions alternating at 100k+ | yes | identity: restored state bit-equal to an eager restore (ids + logprobs); (a) anon -3 GiB or more, TTFT unchanged; (b) switch latency within +0.4 s of eager, restore bytes equal | 0.5 d + runs |
|
||||
| T8 | **Real compressibility**: one 245k run with a debug dump of parked blocks and nodes (small hook), then offline `zstd -1/-3`, `lz4`, byte-shuffle + zstd, per component (K codes, V codes, scales, index rows, GDN, ring) | one run | ratios per component; **build the codec only if K/V >= 1.3x or GDN >= 1.3x**; decompress MB/s per core on the 9950X3D | 0.5 d |
|
||||
| T9 | Compressed parking, idle-only background pass, block headers with crc; telemetry | no | round-trip property tests; corrupt block degrades to a miss; no compression thread runs while a window is in flight (log assertion) | 3 d (only if T8 passes) |
|
||||
| T10 | **[GPU] Hybrid fallback A/B** (`mapped` + `resident_budget_gib`): arms resident, 100 %, 60 % and 0 % of the 25.4 GiB complement pinned, one cold-cache run per arm | yes | table of decode tok/s, CPU-leg ms, PCIe-leg ms, TTFT per turn, page-fault counters, MemAvailable; defines the smaller-host ladder; no default change | 1 d |
|
||||
| T11 | **Cap-first planner** in `leleka-memory`: cache = `min(cap, 75 % elastic)`, idle shrink schedule, eviction order of C.6; plan output states cap and expected use separately | no | pure unit tests on fixtures (the 5090 numbers of A.1, a 64 GiB host, an unknown-telemetry host) | 2 d |
|
||||
| T12 | Free the dense host copy after upload if it is retained without a reader (row 6) | GPU for the check | RSS -1.3 GiB, ids identical | 1 d |
|
||||
| T13 | **[GPU] Lazy pinned K/V spike**: reserve the 3.1 GiB virtual range, `cuMemHostRegister` it in 64-256 MiB steps as the position advances | yes | kernels address the sub-ranges (UVA) unchanged; registration cost per step; ids identical | 2 d, low value at 256k |
|
||||
| T14 | **[GPU] PLE as a file (`kar_source: file`)** after T4: touched pages of the archive after the five-turn session, NVMe latency tail | yes, only with owner approval (the model volume's unstable disk) | page cache <= 8 GiB and `window.ple` and TTFT within noise; otherwise keep the sparse memfd | 1 d |
|
||||
|
||||
Value order: T1, T2, T3, T4 (largest, 36.6 GiB, no risk), then T5-T7 (3.5 GiB, removes the live-session duplicate), T11, T8/T9, T10, T12, T14, T13.
|
||||
|
||||
## E. Not verified, and what could change the plan
|
||||
|
||||
* **The 39.3 GB being dead weight** is E until T1. If the directory shows PLE parts at more than level 2 (more planes than the two read), the sparse extents grow and the saving shrinks accordingly; the derivation
|
||||
above (equal 2.50 bits per element in both halves) makes that unlikely.
|
||||
* All speed statements about mapped, hybrid and pageable banks on the 5090 are E; the only measurements are on the laptop (3080, WSL2) and job 911 (file-mapped bank, small VRAM tier).
|
||||
* The owner's "anon 55 GB / shmem 56.5 GB" were read as GiB (they reconcile with the table that way); if they are decimal GB the unattributed row 8 grows by ~3 GiB.
|
||||
* Compression ratios are synthetic bounds; real KV/GDN data was not available on this machine.
|
||||
* Prefill restore/re-read numbers are from `upstream-port-plan.md` runs on the frozen corpus with chunk 8192; a full 245k cold re-read was not run as one request.
|
||||
* Lazy pinning, dense-copy freeing and the 5090 behaviour of a pageable prefill ring are untested ideas, listed as tasks, not as claims.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Synthetic entropy bound of int8 absmax-quantized K/V-like vectors and of fp32 state, for docs/design/memory-single-copy-and-elastic-state.md section C.5.
|
||||
# Offline experiment (Python is allowed offline): NOT a measurement of the model; real parked blocks are measured by task T8. Pure standard library.
|
||||
import random, math, zlib, struct, collections
|
||||
random.seed(1)
|
||||
def H(bs):
|
||||
c = collections.Counter(bs); n = len(bs)
|
||||
return -sum(v/n*math.log2(v/n) for v in c.values())
|
||||
def quant(vecs):
|
||||
out = bytearray()
|
||||
for v in vecs:
|
||||
m = max(abs(x) for x in v) or 1.0
|
||||
s = 127.0/m
|
||||
out += bytes((max(-127,min(127,round(x*s)))&0xff) for x in v)
|
||||
return bytes(out)
|
||||
def gen(kind, n, d=128):
|
||||
vs=[]
|
||||
for _ in range(n):
|
||||
if kind=='gauss': v=[random.gauss(0,1) for _ in range(d)]
|
||||
elif kind=='laplace': v=[random.expovariate(1)*random.choice((-1,1)) for _ in range(d)]
|
||||
elif kind=='t3':
|
||||
v=[random.gauss(0,1)/math.sqrt(random.gammavariate(1.5,2)/3) for _ in range(d)]
|
||||
vs.append(v)
|
||||
return vs
|
||||
print("synthetic int8 absmax-quantized vectors (d=128), 0-order entropy bits/byte, ideal entropy-coder ratio, zlib-1 ratio")
|
||||
for k in ('gauss','laplace','t3'):
|
||||
b = quant(gen(k, 4000))
|
||||
h = H(b)
|
||||
print(f"{k:8s} H={h:5.2f} bits ideal x{8/h:4.2f} zlib1 x{len(b)/len(zlib.compress(b,1)):4.2f}")
|
||||
# fp32 state: gaussian values, byte-plane entropy
|
||||
vals=[random.gauss(0,0.05) for _ in range(300000)]
|
||||
raw=struct.pack('<%df'%len(vals),*vals)
|
||||
planes=[raw[i::4] for i in range(4)]
|
||||
hp=[H(p) for p in planes]
|
||||
print("fp32 gaussian byte-plane entropies (b0 low mantissa .. b3 sign/exp):", [round(x,2) for x in hp], " ideal x%.2f"%(32/sum(hp)))
|
||||
print("zlib1 on raw x%.2f ; zlib1 on byte-shuffled x%.2f"%(len(raw)/len(zlib.compress(raw,1)), len(raw)/len(zlib.compress(b''.join(planes),1))))
|
||||
Reference in New Issue
Block a user