Skip to content

[Engine] fix(strata): keep the prefill head at a fixed address - #346

Merged
linyubupa merged 2 commits into
Edge0-AI:mainfrom
regislebrun:fix/prefill-head-alias-fixed-address
Dec 1, 2026
Merged

linyubupa merged 2 commits into
Edge0-AI:mainfrom
regislebrun:fix/prefill-head-alias-fixed-address

Conversation

@regislebrun

Copy link
Copy Markdown
Contributor

What & why

Problem. --prefill-head-alias unloads the output head while each fresh prompt is read (its VRAM is lent to the
prompt path), then reloads it before the first decode window. The reload was a cudaMalloc, which does not promise the
address the block had before. The verify windows' CUDA graphs are captured during the first decode and hold that
address, so a reload that landed elsewhere ended the request with

ERR --prefill-head-alias: the output head was reloaded at another address, so the
captured verify graphs would read freed memory

and the server restarted the engine. I saw it on a 524288-token engine: an elastic K/V growth (--kv-grow) took the
freed range between the unload and the reload, so the head came back somewhere else.

Result. The head keeps its addresses across an unload/load pair, so a reload cannot move and the request
completes. The full report, with the log of the failure and the four-request run that followed, is in #345.

Approach. edge0-strata/include/strata/core/vmm.hpp gains VmmBuffer, a virtual-memory range reserved once for
the process:

  • ensure(bytes) reserves whole chunks of addresses the first time, and only reserves again when a larger range is
    needed;
  • map() takes new physical memory at those addresses; unmap() frees the physical memory and keeps the addresses;
  • release() gives both back.

NativeHead uses one for its weights: load maps the head there, unload unmaps it (that is the lend, and the VRAM
really returns to the pool), load maps it again at the same address. VmmBuffer is the existing VmmRange API with
the unmap/map pair the alias path needs, so the CUDA path and the HIP path (ROCm 6, virtual memory management) share it.

Compatibility: a device without virtual memory keeps the cudaMalloc block, and the --prefill-head-alias start line
now says so instead of failing silently later. The address check in generate.cpp stays as a backstop. The restore
line reports the address, so a log answers "did it move?" without a rebuild.

Limits. This removes the move, not the cost of the lend: reading a prompt still pays the reload (about 0.1 s here)
and the workspace rebuild (about 40 ms). A request that reads a few dozen fresh tokens keeps paying for a 2048-token
chunk; the "skip the swap for short reads" item in docs/PREFILL_HEAD_ALIAS.md is untouched. The range is reserved
for the life of the process, so its addresses are not available to another allocation: that is the point, and it costs
nothing when the engine runs with the flag.

Fixes #345

Area

  • edge0-strata/

How was it tested?

Hardware and software: NVIDIA RTX 4000 Ada Generation Laptop GPU, 12282 MiB, driver 580.173.02 (CUDA 13.0), Linux,
strata 0.1.55, commit 05119ae on top of 2e5d284.

Commands and results:

$ cd edge0-strata && cmake --build build --target strata native_head_alias_test vmm_test --parallel 8
[0/1] no work to do.                                   # the three targets were up to date with the tree

$ ./build/vmm_test
vmm_test: ok

$ ./build/native_head_alias_test
  the addresses are reserved once                                                ok
  the head's physical memory is mapped at them                                   ok
  the head is uploaded and the copy lands                                        ok
  unload frees the physical memory and keeps the addresses                       ok
  the lend returns the VRAM (the prompt path can really use it)                  ok
  another allocation takes VRAM between the unload and the reload                ok
  the reload maps physical memory again                                          ok
  the reload lands on the addresses the verify graphs captured                   ok
  the reloaded head reads back                                                   ok
  the reloaded head is writable by the kernels                                   ok
  a second lend keeps the addresses too                                          ok
  the second lend returns the VRAM again                                         ok
  release gives the addresses back                                               ok
  no CUDA error was left behind                                                  ok
native_head_alias_test: ok

tests/core/native_head_alias_test.cpp is new and registered in CMakeLists.txt next to vmm_test. It performs a real
lend: it uploads a pattern, unmaps the head, has another allocation take VRAM from the freed range, maps the head again,
and checks the pointer, the read-back and a kernel write. It skips cleanly (exit 0) on a device without virtual memory.

End to end, with the bug's own workload: a --max-context 524288 engine (the recipe of #345: --kv int8 --kv-resident 20480 --prefill-head-alias --mtp, yarn x2) served the agent sessions on this machine for 4.7 hours.
The log holds 303 consecutive restore lines, all at 0x302000000, and zero ERR --prefill-head-alias lines:

strata serve: --prefill-head-alias: output head restored in 107.5 ms before decode, at 0x302000000 (the verify graphs' address)
...
$ grep -c "output head restored" <log>                       384   # 81 are from the previous binary, before the rebuild
$ grep -o "at 0x[0-9a-f]*" <log> | sort | uniq -c
    303 at 0x302000000
$ grep -c "ERR " <log>
0

Passed: build of the three targets, vmm_test, native_head_alias_test, 303 reloads under a live 524288 engine.

Failed: none observed.

Not run: HIP (no AMD device here; VmmBuffer uses the same VmmRange API the HIP path already implements) and Metal
(no virtual memory there; the code takes the cudaMalloc branch and the start line says so). Windows was not tested.
The memory-contract test covers the device calls, not a full engine run on those backends.

Checklist

  • Linked an agreed issue, or this PR is documentation-only — Fixes #345, the report that reproduces the failure
  • Related fixes in this area are in this pull request, one commit per fix
  • This is one of at most two open pull requests from me
  • ctest --preset cpu -L "L0|L1" passes locally in edge0-infer/ (engine changes) — not affected: this PR touches
    edge0-strata/ only, and does not build edge0-infer
  • Changes to model computation: ran the local-only answer suites — not applicable (memory management only, no
    change to the computation or to the numerics)
  • Ran the higher test levels this change affects — native_head_alias_test and vmm_test are device tests, plus
    the 4.7 h engine run above
  • Added/updated tests for new behavior — tests/core/native_head_alias_test.cpp
  • Updated relevant docs / READMEs — docs/PREFILL_HEAD_ALIAS.md: the graph-safety section now describes the fixed
    address, the start line's warning where there is no virtual memory, and the open question about a fixed address is
    closed

--prefill-head-alias unloads the output head while each fresh prompt is read
(its VRAM is lent to the prompt path) and reloads it before the first decode
window.  The reload was a cudaMalloc, which does not promise the address the
block had before: the verify windows' CUDA graphs are captured during the
first decode and hold that address, so a reload that landed elsewhere ended
the request with

  ERR --prefill-head-alias: the output head was reloaded at another address,
  so the captured verify graphs would read freed memory

I saw it on a 524288-token engine, where an elastic K/V growth took the freed
range between the unload and the reload.

The head now lives in a VmmBuffer, a virtual-memory range reserved once for
the process: unload unmaps the physical memory and keeps the addresses, load
maps new physical memory at them.  A captured graph or a stored pointer
survives the pair, so the reload cannot move.  Devices without virtual memory
keep the cudaMalloc path, and the start line now says that a reload there may
land elsewhere.  The address check stays as a backstop.

The restore line reports the address, so a log shows where the head went.

Fixes Edge0-AI#345

@linyubupa linyubupa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Read through it — the approach is right (it is exactly what the "Open questions" section of docs/PREFILL_HEAD_ALIAS.md suggested), the docs and the address backstop are consistent, and the 303-reload log is the evidence this needed. Five things, roughly in priority order:

1. VmmBuffer::ensure() can silently invalidate a mapped buffer (the one I would fix before merging).
VmmRange::reserve() starts with release() (vmm.cpp:91), and ensure() calls it whenever bytes grows — so ensure() on an already mapped buffer frees the reserved range and moves base(). Today this is unreachable because NativeHead::load() refuses when the head is loaded, but VmmBuffer is now a general class (the K/V pools use VmmRange too) and that is a footgun with no diagnostic. Please add if (mapped()) return false; (or an assert) and say so in the comment.

2. map() maps every reserved chunk, not the bytes asked for.
range_.map_range(0, range_.chunks(), …) and unmap() reverse it, so a buffer reserved once at a larger size keeps paying for the whole range — the lend would return less VRAM than the head's bytes suggests, and bytes() reports the reserved size, which reads as the head's. Fine while one process holds one fixed-size head; I would still make it map(uint64_t bytes) and map only ceil(bytes / gran).

3. vmm_available() pins the device on first call.
api() resolves a.dev once through cudaGetDevice (vmm.cpp), so the first caller decides which card every later cuMemCreate/cuMemSetAccess targets. The new call site (generate.cpp:6509) is safe only because line 4240 already switched the thread to primary_device. Please either note "call only after the device is chosen" there, or resolve dev on the first map() instead. This one will bite a future call from argument parsing.

4. The test covers VmmBuffer, not NativeHead.
native_head_alias_test drives the class directly, so load → unload → load through the real head (and the cudaMalloc fallback branch) has no automated test — that path is only covered by your 4.7 h run. Not a blocker, but a case asserting "two loads land on the same weights()" (and, where VMM is absent, that they may not) would close it.

5. scratch_ (nit). It is cudaMalloc'd again on every reload, and nothing in the tree calls scratch() — the verify head kernel only takes weights() — so it is not in the captured graphs and does not need the fixed address. Worth a comment saying so, or dropping the allocation, so the next reader does not assume it needs the same treatment.

Unrelated to the fix itself: native_head_alias_test exits 0 rather than using SKIP_RETURN_CODE on a device without virtual memory, so CI cannot tell "skipped" from "passed" (vmm_test does the same, so this is only a note). HIP/Metal/Windows untested is acknowledged in the description; I do not see an interaction problem with --kv-grow, since both sides reserve their own virtual range.

VmmBuffer:

- a mapped buffer refuses to change size: VmmRange::reserve gives the addresses back first, which would move
  base() under a captured graph, so ensure() now says so and keeps them;
- map() maps the chunks the last ensure() asked for, so a buffer reserved at a larger size maps only what it
  uses, and bytes() reports that size instead of the reservation;
- unmap() reports a chunk the driver leaves mapped: the lend then gave back less VRAM than it should.

vmm: the device the ranges live on is picked by the first call that touches device memory, not by
vmm_available(): a query from argument parsing used to pin the process to whichever card was current, and its
granularity with it.  A mapping call from another card is refused, with one line.

NativeHead: fixed_backed is derived from weights_ == fixed_.base() rather than a second flag that unload,
load and both error paths had to keep in step; unload() states that the caller drains the streams that read
the head (cudaFree waits for the block's uses, unmapping and releasing do not); scratch_ is documented as
run()'s buffer, outside the captured graphs, so it needs no fixed address.

tests: native_head_reload_test drives load, unload, load through NativeHead on a synthetic GGUF (same
weights(), the file's bytes again); native_head_alias_test covers the resize refusal and map-what-was-asked.

vmm_test, native_head_alias_test, native_head_reload_test: ok on an RTX 4000 Ada.
@regislebrun

Copy link
Copy Markdown
Contributor Author

Thanks for this — all five points are addressed in 29f1b01, each with a test or a stated reason. Full disclosure: implemented by my coding agent, maximum-effort pass, then built and run here (RTX 4000 Ada).

  1. Taken. ensure() now refuses to change size while mapped and says so; VmmRange::reserve's release path is unreachable from the class. The comment states that a resize after unmap() does move base().
  2. Taken, with one correction. ensure() never held a reservation larger than the last request (it reserved only on growth), and unmap() freed every chunk — so the lend returned slightly more, not less, than bytes. What was really wrong is that bytes() reported the reservation. The buffer now records the chunk count ensure() asked for: map() maps exactly that, bytes() reports it. I kept a single size source rather than map(uint64_t), so the two cannot disagree. The test covers shrink and grow-back-inside-the-reservation.
  3. Fixed at the source. vmm_available() / vmm_granularity() now resolve nothing and keep nothing; the first call that touches device memory binds the device and its granularity, and a mapping call from another card is refused with one line. A query from argument parsing can no longer pin the process. CUDA and HIP both.
  4. Added native_head_reload_test: a synthetic edge0 GGUF with one Q5_K output.weight, then load → unload → load through NativeHead itself, same weights() and the file's bytes after each reload. Stated limit: the cudaMalloc branch still needs a device without VMM (or STRATA_HIP_VMM=0); I did not add a switch only to reach it.
  5. Commented, not dropped: scratch_ is run()'s activation buffer, outside the captured graphs.

Three things the review did not cover, also in the patch:

  • The synchronisation contract changed. cudaFree waited for the head's in-flight uses; cuMemUnmap/cuMemRelease do not. The call sites do drain (ver.wait_commit, the request-end waits, as vmm_test notes), but unload() now states that invariant instead of inheriting it by accident.
  • fixed_backed_ was a second source of truth. Now derived (weights_ == fixed_.base()), instead of a flag set on one load path and reset on two.
  • unmap() could not report a refusal. VmmRange::unmap() returns 0 both for "not mapped" and for a driver failure, so a failed cuMemUnmap could leave a chunk mapped while the log announced a restore. VmmBuffer::unmap() now counts what stayed and says how much VRAM the lend did not return.

vmm_test, native_head_alias_test, native_head_reload_test: ok. HIP and Metal stay compile-only here, as before — CI will say.

@linyubupa

Copy link
Copy Markdown
Collaborator

All five points are addressed and verified in 29f1b01 — the chunks_/gran_ single size source and moving the device binding out of the query are both better than what I suggested. Merging; the per-device binding, a lock/once_flag around bound(), and listing the drained unload() call sites are non-blocking.

@linyubupa
linyubupa merged commit fcf55b0 into Edge0-AI:main Dec 1, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Documentation strata edge0-strata

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Engine] --prefill-head-alias: the output head must come back to the address the verify graphs captured

2 participants