Skip to content

gpu, os: read request rows back into host memory the host wrote first - #755

Merged
juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:dgx-spark-fresh-page-readback
Oct 23, 2026
Merged

juliankang4 merged 4 commits into
midagedev:mainfrom
juliankang4:dgx-spark-fresh-page-readback

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

GB10에서 GPU 결과를 호스트 메모리로 읽어 오는 요청 경로가 아직 쓰이지 않은 페이지에 복사하며 치르던 페이지 폴트 비용을 없앱니다. 큰 readback이 가장 크게 빨라집니다.

Part of #565.

What and why

On a GB10 (the DGX Spark card) the GPU reaches pageable host memory through the host's page tables. A device-to-host copy into pages that no CPU thread has written pays for each page's first touch inside the copy. Request paths hit this whenever a readback lands in a new Vec, such as to_host_vec or vec![0.0; n]. A probe on a GB10 shows it: the same 32 MiB copy takes 12.9 ms into a new allocation and 0.70 ms into memory the CPU has already written.

This PR gives readback destinations one owner, host_filled in crates/gpu/src/tensor.rs (read back with to_host): host memory whose every page the host wrote before the copy. It also stops uploading zero buffers from the host and advises huge pages for large fills. The change has three commits.

  1. Readback destinations. host_filled and to_host replace the fresh Vec at the request readbacks that pay this cost. The fill value is NaN for f32 and u16::MAX for u16, never zero, because a zero fill comes back from the allocator as pages nothing has written. A value no copy overwrote stays visible as the fill. The call sites:

    • the EmbeddingGemma output rows (read into a Vec<f32> that the encoder keeps and grows only when an output is larger), and the dense head, which now reads only the pooled window instead of the whole output buffer;
    • the decision prefill_hidden, which copies each unit straight into one result instead of through a temporary Vec;
    • the vision rows, the Gemma 4 audio output, the Qwen3.8 MTP hidden_row and draft_rows, and the GLM NextN read_rows;
    • the sampling logits row and the DeepSeek V4.1 feature taps;
    • SeqState::save, which already filled its host memory by hand and now uses host_filled.

    The rows field of the EmbeddingGemma encoder's result is removed, because the server path reads only pooled and returning rows cost a host copy on every encoder run. The e2e gate reads the rows through a tap instead; its clauses (d) and (r) change with PIN(2026-10-24).

  2. Zero uploads. DeepSeek V2 reset and seed_cache, and the Qwen3.8 put_draft_rows arena, zeroed their cache from a zero Vec uploaded from the host. They now zero on the card (zero_async) and copy only the rows. reset no longer waits for its stream.

  3. Huge pages. bloomery-os gains advise_huge (madvise(MADV_HUGEPAGE) on Linux, refused by name on macOS). The host benchmark bench_v41_host calls it too, in place of its own copy of the constant and the system call. host_filled calls it for allocations of at least 32 MiB, the size from which glibc maps new memory for each allocation, so the fill faults once for each huge page. A refusal leaves base pages and the fill is the same. bloomery-gpu now depends on bloomery-os.

The step-by-step Head::tokens readback (12 bytes) is unchanged: all four destinations measure the same there.

Release notes: Under the hood: Request readbacks on a GB10 land in host memory the host has already written, and large ones use huge pages, so they no longer pay a page fault for every page they copy into.

Code shape

  • No second copy. host_filled and to_host are the one owner of readback destinations. The one existing copy of that logic, the fill in SeqState::save, now calls it. advise_huge is the one owner of the huge-page advice: the host benchmark's own MADV_HUGEPAGE call now goes through it. The only retained readback vector is the encoder's, held in Encoder where its single consumer is.
  • Model code holds only architecture facts. The owner is in bloomery-gpu and bloomery-os. Model files changed only at their call sites.
  • Dead code is gone. The rows field and the host zero uploads are removed.
  • No silent failure. Every Result goes to the caller with ?. The one result dropped is the huge-page advice, which changes speed and not the fill, so a refusal is not an error.
  • Comments state what is true now. The comments describe the code as it is, with no dates or measured numbers.
  • No relaxed gate. The e2e clauses (d) and (r) read the rows through a tap and carry a PIN. No band or tolerance moved.
  • cargo fmt --all passes. cargo clippy has not been run on this head, so the lint count is unchecked.

Duplication found or removed (path:line): none that is shared logic. advise_huge and advise_populate in crates/os/src/lib.rs share only the madvise call and its return check. Their contracts differ: populate reads pages into any live mapping and has a macOS fallback that reads them, while huge changes the backing of private anonymous memory and has no macOS equivalent. A shared helper would add an unsafe function and block to the unsafe ratchet for five lines.

What I ran

The probes, the A/B and the RTX 5090 gates below ran on this series' three commits on an earlier main. A range comparison of the three commits against this head shows equal patches, and the upstream commits in between change a test profile in a Cargo manifest, one serve test, the dense BF16 and MXFP8 GEMM body, the selected-attention launches and a gate script. None of them touches the readback, zero-fill or huge-page code this PR changes. The unit tests and the GB10 card check at the end of the next section ran on a head with the same patches as this one.

Readback destinations, one GB10 (main behavior against this change)

The probe is a stand-alone CUDA program on a GB10. Each call takes new memory and copies it back from the card, 8 calls per size, and the table shows the median of the whole readback including the fill. main is malloc with no CPU write, which is what to_host_vec did. head is a huge-page advice followed by a CPU fill, which is what host_filled does from 32 MiB up.

Readback destination (ms per readback, median of 8) main head change [derived]
32 MiB 12.925 1.761 -86.4%
64 MiB 22.390 3.522 -84.3%
160 MiB 51.359 8.745 -83.0%

Delta (head against main): readback of 32 MiB 12.925 to 1.761 ms (-86.4%), 64 MiB 22.390 to 3.522 ms (-84.3%), 160 MiB 51.359 to 8.745 ms (-83.0%).

The probe models the destination and is not a request. The advice does not pay below 32 MiB: at 6 MiB advised pages with a fill took 0.377 ms against 0.279 ms for an ordinary fill, so the advice starts at 32 MiB.

A second probe of the destinations the request paths use, run on the same kind of machine, shows the small sizes. A fresh destination pays its page faults on the first call, not the median: the first call of a 360 KiB readback took 4.7048 ms against 0.0131 ms for the median, and a 1 MiB readback took 14.0999 ms against 0.0275 ms. At 16 MiB the first call took 162.79 ms. Into memory the host had written first, the first call takes the same time as the median at those sizes (0.0131 ms, 0.0275 ms and 0.3472 ms). The fill adds 0.0136 ms to 0.3278 ms of CPU time from 360 KiB to 16 MiB. The 12 byte readback of Head::tokens takes 0.0052 ms into a fresh destination and 0.0051 ms into a filled one. Zeroing the DeepSeek V2 cache, 27 layers of 4,718,592 bytes, takes 7.764 ms from a host calloc upload and 0.186 ms with a device memset (last of three rounds).

Output equality and an end-to-end sitting, one GB10

nvidia-smi on the machine, and the build under test:

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |

The model is nvidia/Qwen3.8-Flash-Next-FP4-Local (revision b9ce18a6), served with --parallel 1, context 8192, BLOOMERY_DRAFT=mtp and --cache-ram 363. The two bloomery-serve builds differ (sha256 b0d64b7e… for main and 8e48c633… for head). The sitting started with one discarded warm load, then ran the head and then main, each after its own load. Each arm's read probe (1 GiB, 10 repeats) was within 0.7% of the warm load's (237.75, 237.23 and 236.04 GB/s).

Request Prompt ids main TTFT (ms) head TTFT (ms) text sha, main and head
c 300000 4096 3508.4 3654.6 376cc2ad, same
c 310000 4096 3489.7 3666.8 652ee44b, same
c 320000 4096 3469.4 3680.1 dd07200f, same
r W 4096 3456.6 3616.2 25b7d442, same
r X 4096 3455.9 3660.5 d918947a, same
r W+256 4352 4032.5 4040.3 968e19b1, same

The generated text is identical in all 12 requests of the two arms. The speculative draft counts differ by one to three tokens between the arms in some requests, which is run-to-run variation in the proposals.

This sitting did not show a gain. All five 4096-id requests were slower on the head, with a median difference of 177 ms (5.1%) [derived], and the 4352-id request differed by 8 ms (0.2%) [derived]. The path this change takes in a Qwen3.8 request adds only the 40 KiB hidden_row readback and no synchronization, so I do not read the difference as a cost of the change, but I did not run the arms in the opposite order to check. The changed paths with the largest destinations did not run: --cache-ram 363 is below the 389,313,536 bytes of one 4096-id state, so every request logged cache skip and the synchronous snapshot and the resume put_draft_rows never ran. The probe above is the evidence for those paths.

Unit tests and gates

GB10 card tests on the series before the fix round (tensor::tests:: and checkpoint::saved::, RUST_TEST_THREADS=1, built for sm_121): 15 passed, and cargo test -p bloomery-os huge_page on the same machine: 1 passed.

test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 384 filtered out; finished in 9.63s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 18 filtered out; finished in 0.00s

cargo test -q -p bloomery-os on an x86 Linux machine with transparent huge pages set to madvise: 19 passed, on the head before the fix round.

test result: ok. 19 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Fail-first: with FILL set to 0.0 and the retained reader set to allocate on every call, the run of the two new tests (host_filled_memory_holds_the_fill_not_zero and hw_a_readback_keeps_its_memory_and_returns_each_read_whole) exited 101 on an RTX 5090 machine. With the code restored, 9 tests passed. I ran this on an earlier commit of this series, before the retained reader moved into Encoder; the card check below repeats the reuse test on the current code. The failing assertion text was not saved, so the evidence is the exit code and the restored pass.

test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 389 filtered out; finished in 18.93s

GB10 card check on a head with the same patches as this one (the huge-page test, then the Encoder reuse test with and without a mutant that reallocates on every pass, then the owned readback test):

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
test tests::the_huge_page_advice_is_taken_where_the_platform_has_it ... ok
assertion `left == right` failed: the shorter pass reuses its memory
FAIL-first-encoder-reallocation: rc=101
test pass::tests::hw_a_readback_keeps_its_memory_and_returns_each_read_whole ... ok
test tensor::tests::hw_an_owned_readback_returns_each_read_whole ... ok
gpu-check: PASS

The huge-page test accepts a Linux kernel without transparent huge pages: it passes when the advice returns EINVAL, and when the advice is taken it requires the hg flag on the mapping in /proc/self/smaps. On a Linux machine with transparent huge pages, the test passes with the real advice and fails (exit 101) when the call is replaced by a no-op. An injected EINVAL from the advice passes, and the old assertion that required the advice fails (exit 101) under it. No kernel without transparent huge pages was booted.

FAIL-first-no-op: rc=101, expected_success=False
FAIL-first-required-THP: rc=101, expected_success=False
host-check: PASS

The host benchmark's call to advise_huge is checked by a source check that rejects its removal, and by cargo check -p bloomery-model --bin bench_v41_host, cargo fmt --all -- --check and the unsafe-pin check, which passed. cargo check --workspace --all-targets with all features passed on an RTX 5090 machine on the head with these patches (rc 0). The benchmark was not run against a model.

GPU Evidence

Card 1 is the GB10 above (driver 595.84, CUDA 13.3), with its card check above. Card 2 is an RTX 5090, driver 595.99.02, CUDA 13.2:

NVIDIA GeForce RTX 5090, 595.99.02
| NVIDIA-SMI 595.99.02              Driver Version: 595.99.02      CUDA Version: 13.2     |

On the RTX 5090, just gate-gpu-gemma-embedding2-e2e and just gate-gpu-gemma-embedding2-serve ran on the measured series with BLOOMERY_ARCH=sm_120. The e2e clause (d) (a rerun's pooled vector and rows bit for bit) and every (r) clause passed, and the serve gate passed all its main checks. Both recipes exited 1 for a reason outside this change: the machine's reference data folder has no MANIFEST.tsv for the Hugging Face reference (clause (h)), the image inputs (clause (i)) or the audio server run, so those clauses and the serve --audio run did not execute.

just gate-gpu-gemma-embedding2-e2e
(d) cases/66: 1734 ids, a rerun's pooled vector and rows bit for bit PASS
(r) cases/66: after the refusals the rows bit for bit PASS
e2e: 95 PASS lines, 3 FAIL lines, rc=1
just gate-gpu-gemma-embedding2-serve
check concurrent_greedy_same: PASS
serve: 193 PASS lines, 0 FAIL lines, rc=1

Not run: the (h) and (i) clauses and the serve --audio run (missing reference data), an exact-head workspace cargo check on the final head, and cargo clippy. cargo check --workspace --all-targets with all features passed on the RTX 5090 machine for the measured series with no error or warning. The recipe's exit code 255 there comes from a remote-copy step that cannot resolve a host name, not from the check.

Hardware

A GB10 machine (kernel 6.17, 4 KiB pages, transparent huge pages madvise) for the probes, the GB10 card tests and the A/B, an RTX 5090 machine for the gates and the workspace check, and an x86 Linux machine (kernel 7.0, transparent huge pages madvise) for the bloomery-os tests.

What I ran into

This does not block the PR.

  • The A/B sitting above did not exercise the largest changed paths, and its 4096-id requests were slower on the head. The 4352-id request was not.
  • The fail-first run of the first two new tests on the earlier commit kept only its exit code; the Encoder reuse test's failing assertion is saved in the card check above.
  • cargo test -p bloomery-os was not re-run in full on this head; the huge-page test and the host check above were.
  • Two GB10 attempts of the A/B harness did not complete before the sitting above: a server load that exited during startup, and a head build that stopped when two builds ran in one tree at once. Neither reproduced after the builds ran one at a time.

AI help

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

…u-glm5next: read request rows back into host memory the host wrote first

A device-to-host copy on GB10 reaches pageable memory through the host's
page tables, so it faults on each 4 KiB page it is the first to write.
cuda-core's to_host_vec copies into a Vec::with_capacity nothing has
written, and a large vec![0.0; n] comes from calloc as the same untouched
pages. On GB10 (driver 595.84, CUDA 13.3) a fresh destination cost
4.7 ms for 360 KiB and 14.1 ms for 1 MiB on the first call, and 13.6 ms
for 32 MiB, 24.7 ms for 64 MiB and 53.9 ms for 160 MiB on every call,
against 0.69, 1.38 and 3.43 ms into memory kept across calls. Below
32 MiB the allocator mostly hands back memory it already wrote, so there
the cost falls on the first request and on an occasional later one.

tensor.rs now owns the destination: host_filled gives memory the host has
written (NaN for f32, u16::MAX for u16, never zero, so a value no copy
wrote stays visible), to_host reads a buffer into it, and Readback keeps
one across reads and grows it to the longest. SeqState::save takes its
fill from host_filled.

The request paths go through it. The embedding encoder reads its output
rows into a Readback it keeps, and its dense head reads its n_out pooled
values instead of the whole output buffer; Pass drops rows, which no
server path read, and the e2e gate reads them as the result_embd tap. The
decision model copies each unit's hidden rows straight into one filled
vector instead of a new vector per unit. The image encoders' and
Gemma4a's outputs, Qwen3.8's MTP hidden row and draft rows (now the held
rows only, not the whole arena), GLM's NextN rows, the sampling logits row
and the DSpark feature taps land in filled memory.
DeepSeek V2's reset uploaded a host vector of zeros the size of each
layer's cache, and its depth seed did the same around the seeded rows.
Qwen3.8's draft-row resume built a zeroed host copy of each arena around
the rows it puts back. Each now zeroes the buffer on the card and copies
only the rows it holds, and the reset no longer waits on the stream. On
GB10, zeroing 27 cache planes of 4.5 MiB took 7.7 ms as uploads of
calloc'd host memory and 0.19 ms as device memsets.
host_filled writes every page of a device-to-host destination before the
copy. A new allocation of 32 MiB or more, which glibc maps fresh each
time, made the fill itself fault once each 4 KiB page. host_filled now
asks the kernel for huge pages over the allocation's whole 2 MiB pages
first (madvise(MADV_HUGEPAGE), a new bloomery-os call), so the fill
faults once each 2 MiB. Where the kernel refuses the advice the fill
takes base pages as before.

On GB10 (transparent huge pages on madvise), filling new memory and
copying into it took 8.6 ms for 32 MiB, 17.4 ms for 64 MiB and 43.6 ms
for 160 MiB with base pages, and 1.8, 3.5 and 8.7 ms with the advice.
SeqState::save's synchronous snapshot and the large request readbacks
take their memory from host_filled.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card 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: CLEAN: No reachable production failure or blocking quality defect was found.

Non-blocking

⚠ Check fresh data when reusing the encoder buffer: crates/gpu-gemma-embedding2/src/pass.rs:677.
A mutant that copies only when the buffer grows passes: the second call compares two views of stale data.
Insert enc.readback.fill(f32::NAN); before this call. This makes a missed refresh fail while the reuse contract is being introduced.

⚠ Exercise the large request paths: crates/gpu/src/checkpoint/saved.rs:591.
The reported A/B logged cache skip, so it did not exercise snapshot or resume; its fixed arm order also leaves the slowdown unresolved.
Run an interleaved A/B with enough cache memory, and attach owning-gate results and both measured git hashes. This establishes the request cost before publishing the speed claim.

⚠ Keep the diagnostic reproducible: crates/gpu/src/tensor.rs:342.
The first-touch fix has tests, but the standalone readback probe is absent from the diff. Preserve its source in the existing probe tooling, or explain how to reproduce the diagnosis with an existing tool.

Optimization headroom

  • G. Per-launch and per-sync fixed cost: crates/gpu-glm5next/src/nextn.rs:829. Queue both held pair-row copies through the existing dtoh_2d machinery before waiting. This removes one stream wait per snapshot with two held pair rows.

Checked

Duplicates: both dryer pairs share syscall/result shape but have different advice contracts; extracting them would add elements.
Complexity: pass_inner 50→54 adds retained-buffer handling; prefill_hidden 18→19 adds a checked slice. Existing orchestration growth; neither needs a new decision owner.
Silent failure: 1 discarded-result site followed. Rejected huge-page advice leaves base pages; the host fill and copy still run. Copy errors propagate.
Tests, static mutation analysis: zero FILL, omitted owned copy, unconditional encoder reallocation, and no-op OS advice on THP fail assertions; skipped reuse copies survive as noted. Wrong embd/pooled bits fail the changed e2e comparisons.
Gates: dated PINs cover clauses (d)/(r) and both unsafe ratchets; no numerical band moved.
Escape catalog: C1–C4 do not match.

Notes

Static review only; builds and GPU tests were not run here. Complete GPU evidence is absent: measured base/head git hashes are missing, and both reported gate recipes exited 1.

Card check: needs-gpu. This pull request changes crates/gpu-deepseek41/src/body.rs, crates/gpu-deepseek41/src/body/prefill.rs, crates/gpu-gates/src/bin/bloomery_chat.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)

enc.pass(&[0, 1], true)?;
assert_eq!(enc.readback.len(), 2 * hp.n_out);
let at = enc.readback.as_ptr();
let pass = enc.pass(&[1], true)?;

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.

Poison the retained buffer so a skipped refresh makes this test fail.

Suggested change
let pass = enc.pass(&[1], true)?;
enc.readback.fill(f32::NAN);
let pass = enc.pass(&[1], true)?;

@juliankang4

Copy link
Copy Markdown
Collaborator Author

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

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 model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant