Skip to content

serve: keep a finished request's cache save off the next request's path - #706

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:fix-serve-seal-evict-until-fit
Oct 23, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:fix-serve-seal-evict-until-fit

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

요청이 끝난 뒤 prompt cache 저장이 다음 요청을 2초가량 붙잡던 문제를, 저장 공간을 더 비우고 남는 동기 저장을 빠르게 해서 없앴습니다.

Part of #565. Fixes the staging pool item in #699.

What and why

When a request ends, Slot::seal saves its state for the prompt cache before the next request is admitted. The save copies into a pinned staging pool. When that pool is fragmented, the old code gave up one landed entry, retried once, and then fell back to a synchronous snapshot. On a DGX Spark with --parallel 1, that fallback took about 2 s and the next request waited for it.

This PR has two commits:

  1. Slot::seal now gives up landed entries one at a time until the asynchronous copy fits. An entry whose copy is still running stays protected, and a state larger than the whole pool still goes straight to the synchronous path.
  2. The synchronous save that remains now writes its host arrays before the device-to-host copies. GB10 reads the host page table directly, so a copy into pages nobody has written yet raises a GPU fault on every 4 KiB page. On 363 MiB, a single-row copy into fresh pages took 0.57 to 0.68 s and a 16-row 2-D copy took 3.63 to 3.67 s; into pages the host had already written, either copy took about 8.5 ms. dtoh_2d's Safety comment asked for page-locked memory although SeqState::save always passed pageable memory. It now states the real requirement.

Release notes: Fixed: a finished request no longer delays the next request by about 2 s when the prompt cache staging pool is fragmented.

Code shape

  • No second copy. Slot::seal reuses evict_for_room and evict_oldest_landed. SeqState::save is the one synchronous save that both Qwen3.8 and GLM-5.3 call.
  • Model code holds only architecture facts. The change is in the shared serve loop and the shared checkpoint owner.
  • Dead code is gone. The two test builders for a pooled slot are one async_slot with an optional cell count.
  • No silent failure. Cells the copy does not overwrite show up as NaN or 0xFFFF instead of a plausible zero.
  • Comments state what is true now.
  • No relaxed gate. No band or tolerance moved.
  • cargo fmt is clean on what I touched. cargo clippy was not run on this head.

Duplication found or removed (path:line): none.

What I ran

GPU, driver and CUDA lines of the card the GPU tests and the A/B ran on:

NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
NVIDIA GB10, 595.84, 63, 26.69 W, 1989 MHz, 3003 MHz, [N/A], P0, [N/A], [N/A]

The new test fails on the old seal and passes on this head (host test, cargo test -p bloomery-serve --lib):

test genloop::cache_tests::a_fragmented_pool_gives_up_landed_states_until_the_copy_fits ... FAILED
test result: ok. 345 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 6.15s
test record::tests::checked_in_schemas_are_current ... ok

just gate-gpu-lib not run: I ran only its checkpoint test filter on the GB10 card, which covers the changed save path:

test checkpoint::saved::tests::hw_an_async_save_is_the_sync_saves_state_in_one_call_a_store ... ok
test checkpoint::saved::tests::hw_a_state_goes_and_comes_back ... ok
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 372 filtered out; finished in 12.62s

Request sequence A/B

Qwen3.8 FP4-Local on one DGX Spark, bloomery-serve --parallel 1 --ctx-size 8192, draft off, requests one at a time: R1 2,500 tokens, R2 and R3 4,096 tokens, R4 4,096 tokens sent as soon as R3 ends. Each asks for 128 tokens with greedy sampling and ignore_eos. --cache-ram 1024 makes the pool fragmented after R3. The first four numbers are R4. "Remainder" is the client's TTFT minus the server's prompt_ms and cache_ms.

Metric (ms unless noted) main this PR
R4 TTFT 5,894.6 3,847.7
R4 remainder 1,997.5 11.3
Save at the end of R3 1,994 (fragmented) 11.6 (none)
Decode, server tok/s 28.0 to 29.2 29.5 to 29.7

A second head arm with --cache-ram 363 keeps the synchronous fallback because the pool cannot hold a 4,223-position state. Its three saves took 120.8, 130.2 and 132.3 ms, against 1,994.4 ms for the same state on main, and its decode ran at 29.9 to 30.0 tok/s.

The server, the model and the card were the same for every arm, with other GPU processes absent. The clock cap stayed on, which does not matter for a difference of seconds.

Copy probe

A standalone CUDA program copies 363 MiB in 121 device-to-host calls into five kinds of destination (two rounds each):

Destination Copy into pages (ms)
calloc, pages not yet written 566.0 and 675.4
malloc then memset 8.5 and 8.6

The probe reports pageableMemoryAccess=1 and pageableMemoryAccessUsesHostPageTables=1 for the GB10.

What I ran into

None of this blocks the PR.

  • Giving up a second landed entry means a later request that would have reused it prefills again. On main the following save evicted that same entry anyway.
  • After the fix, a request that follows another on the same slot still waits about 17.5 ms for the previous copy to land (land). That is the existing behavior and a separate change.

Hardware

DGX Spark (GB10), driver 595.84, CUDA 13.3. Model: nvidia/Qwen3.8-Flash-Next-FP4-Local.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve labels Oct 23, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: MUST_FIX: consolidating the fixture builders leaves an unneeded wrapper.

Must fix

1. Inline the remaining fixture wrapper

crates/serve/src/genloop.rs:3266 Removing pooled_slot leaves noted_slot with exactly one caller, async_slot. It only wraps the mock and packages the return values. This violates the fewest-elements rule.
Inline it during this consolidation; no other caller needs its interface. Replace async_slot with this definition and delete noted_slot:

fn async_slot(
    slots: usize,
    copy: Duration,
    cells: Option<usize>,
) -> (Slot, Arc<SaveStats>, Arc<Mutex<Vec<CacheNote>>>) {
    let (mock, stats) = MockEngine::new(4096)
        .with_slots(slots)
        .with_cache_ram(1 << 20)
        .with_async_snapshots(copy);
    let mock = match cells {
        Some(cells) => mock.with_staging(CELL, cells),
        None => mock,
    };
    let notes = Arc::new(Mutex::new(Vec::new()));
    let engine = Noted {
        inner: mock,
        notes: Arc::clone(&notes),
    };
    (Slot::with_slots(Box::new(engine), slots), stats, notes)
}

Non-blocking

⚠ Price retries with drafting enabled: crates/serve/src/genloop.rs:857 repeats Qwen's blocking arena reads at crates/gpu/src/arch/qwen3moe/body38.rs:3002 before each staging lend. Each additional attempt adds two readbacks totaling 4 * (1 + PASS_ROWS) * STREAMS * HIDDEN bytes per request [derived]. The supplied A/B has drafting off. Add a fragmented-pool A/B with drafting on to price the additional copies; reuse prepared snapshot data across retries if this work dominates.

⚠ Preserve the page-fault reproducer: crates/gpu/src/checkpoint/saved.rs:566. Reverting both fills to zero still satisfies the checkpoint equality assertions. Retain the standalone copy probe under tools/, including fresh-page versus written-page output. This gives the performance fix a reproducible regression check.

Checked

Duplicates: 3 new items checked; no duplicate owner. The dryer pair tests one eviction versus repeated eviction, distinct contracts.

Complexity: crapper flagged no functions. The retry loop replaces the existing retry branch.

Silent failure: 2 paths followed. NoRoom names the synchronous fallback; copy errors propagate after synchronization.

Tests (static mutation check): skipping eviction at seal:853 fails the full-pool assertions; replacing while with if fails fragmentation; permitting pending eviction fails the fallback assertions; removing need <= held fails oversize eviction assertions. Four fixture-only edits retain their wait, hazard and prefix checks. The zero-fill mutant is discussed above.

Gates: no tolerance or threshold moved. The fragmentation test now requires an asynchronous save; fallback behind a pending copy remains covered.

Performance: request-end saves; the new fills write 2R + 4C host bytes per synchronous save, for R row values and C recurrent values [derived]. No per-token work was added.

Adversarial paths: oversized states stop before eviction; pending copies cannot be evicted; whole-save strips cover the initialized arrays, and failed copies return errors. Qwen and GLM share the changed save owner.

Escape catalog: no C1–C4 patterns matched.

Notes

The GPU output lacks both tested commit hashes, exact gate/A/B commands and the model filename required by CONTRIBUTING.md. GPU evidence is incomplete. Tests were not run during this review.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs, crates/gpu-gates/src/record.rs, crates/gpu/src/checkpoint/saved.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

A request's end begins its state's copy into the engine's pinned staging
pool. When the pool had no extent for it, seal gave up the oldest landed
state and asked once more; if the room that state gave back lay apart
from the rest that was free, the state was snapshotted on the request
path instead, and the worker admits the next request only after that
snapshot. A fragmented pool, first fit in 2 MiB grains, reaches that
case whenever the oldest state is shorter than the one being saved.

seal now gives up landed states, oldest first, and asks again after each
until the copy is begun. A state whose copy still runs is still never
given up, a state that passes the whole pool still gives up nothing, and
only a pool that has no landed state left takes the snapshot on the
request path, its Save naming the pool full or fragmented as before.

On GB10 with Qwen3.8 FP4-Local, --parallel 1 and --cache-ram 1024, a
2,500-id request, then 4,096-id ones back to back: the third save fell
back as fragmented (1,994 ms) and the fourth request's first token came
1,997 ms after its prompt pass and cache time; now two states leave, the
copy is begun (11.6 ms) and that gap is 11 ms.
SeqState::save copies a state into pageable vectors that vec![0; n]
took from the allocator as pages nothing had written yet. On a card that
reads the host's page tables, a device-to-host copy faults on each such
page as it reaches it, one 4 KiB page at a time: copying 363 MiB on
GB10 took 0.57 to 0.68 s as one-row copies and 3.6 s as 16-row 2-D
copies into fresh pages, against 8.5 ms once the host had written them.

The vectors are now filled with u16::MAX and NaN, values the copies
overwrite, so the host writes every page before the device does; a zero
fill would come back as unwritten pages again. dtoh_2d's contract asked
for page-locked memory, which this caller never passed: it now asks for
writable memory, and says what a pageable destination costs and needs.

On GB10 with Qwen3.8 FP4-Local, a 4,223-position state (380 MB) saved
on the request path took 1,994 ms before and 121 to 132 ms now.
@juliankang4
juliankang4 force-pushed the fix-serve-seal-evict-until-fit branch from 465c814 to b253d70 Compare October 23, 2026 08:25

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Since the last review:
Must-fix 1 fixed: crates/serve/src/genloop.rs:3253 inlines noted_slot and removes the wrapper.

Verdict: CLEAN: the blocking wrapper is removed, and the interdiff preserves fixture behavior.

Non-blocking

⚠ Draft retry cost, still open: crates/serve/src/genloop.rs:857 repeats the blocking draft reads at crates/gpu/src/arch/qwen3moe/body38.rs:3002. Each additional attempt adds two readbacks totaling 4 * (1 + PASS_ROWS) * STREAMS * HIDDEN bytes per request [derived]. Fragmentation multiplies this request-end cost. Add a fragmented-pool A/B with drafting enabled; reuse prepared snapshot data if the repeated reads dominate.

⚠ Copy probe, still open: crates/gpu/src/checkpoint/saved.rs:566. Restoring both zero fills still passes the checkpoint equality assertions. Preserve the standalone CUDA probe under tools/, including fresh-page versus written-page output, so the page-fault slowdown remains reproducible.

Checked

Duplicates: 0 new items in the interdiff. The dryer pair was read: one eviction versus repeated eviction, distinct contracts.

Complexity: crapper flagged no functions. The interdiff only inlines fixture construction.

Silent failure: 0 new sites; 2 existing error paths rechecked. NoRoom selects the named fallback; copy errors propagate after synchronization.

Tests: static mutation check: replacing the retry loop at seal:853 with one retry fails the fragmentation assertions; dropping the fixture's staging setup fails the no_room counts. No assertions changed in the interdiff.

Gates: no pins, thresholds or cases moved.

Adversarial paths: pending entries cannot be evicted; each successful eviction removes an entry, bounding retries.

Escape catalog: no C1–C4 patterns matched.

Notes

GPU evidence remains incomplete: the body lacks both tested commit hashes, exact gate/A/B commands and the model filename. Review validation was static; no build or GPU tests were run.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bind.rs, crates/gpu-gates/src/record.rs, crates/gpu/src/checkpoint/saved.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit 7cc05a2 into midagedev:main Oct 23, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app needs-gpu Changes code a card must check, and carries no gate run on a card serve The HTTP server: crates/serve

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant