Repository navigation
gpu, os: read request rows back into host memory the host wrote first - #755
Conversation
…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.
There was a problem hiding this comment.
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_2dmachinery 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)?; |
There was a problem hiding this comment.
Poison the retained buffer so a skipped refresh makes this test fail.
| let pass = enc.pass(&[1], true)?; | |
| enc.readback.fill(f32::NAN); | |
| let pass = enc.pass(&[1], true)?; |
|
The review is done and the contribution check passed, so I'm merging this. |
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 asto_host_vecorvec![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_filledincrates/gpu/src/tensor.rs(read back withto_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.Readback destinations.
host_filledandto_hostreplace the freshVecat the request readbacks that pay this cost. The fill value is NaN forf32andu16::MAXforu16, 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: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;prefill_hidden, which copies each unit straight into one result instead of through a temporaryVec;hidden_rowanddraft_rows, and the GLM NextNread_rows;SeqState::save, which already filled its host memory by hand and now useshost_filled.The
rowsfield of the EmbeddingGemma encoder's result is removed, because the server path reads onlypooledand returningrowscost a host copy on every encoder run. The e2e gate reads the rows through a tap instead; its clauses (d) and (r) change withPIN(2026-10-24).Zero uploads. DeepSeek V2
resetandseed_cache, and the Qwen3.8put_draft_rowsarena, zeroed their cache from a zeroVecuploaded from the host. They now zero on the card (zero_async) and copy only the rows.resetno longer waits for its stream.Huge pages.
bloomery-osgainsadvise_huge(madvise(MADV_HUGEPAGE)on Linux, refused by name on macOS). The host benchmarkbench_v41_hostcalls it too, in place of its own copy of the constant and the system call.host_filledcalls 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-gpunow depends onbloomery-os.The step-by-step
Head::tokensreadback (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
host_filledandto_hostare the one owner of readback destinations. The one existing copy of that logic, the fill inSeqState::save, now calls it.advise_hugeis the one owner of the huge-page advice: the host benchmark's ownMADV_HUGEPAGEcall now goes through it. The only retained readback vector is the encoder's, held inEncoderwhere its single consumer is.bloomery-gpuandbloomery-os. Model files changed only at their call sites.rowsfield and the host zero uploads are removed.Resultgoes 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.cargo fmt --allpasses.cargo clippyhas not been run on this head, so the lint count is unchecked.Duplication found or removed (
path:line): none that is shared logic.advise_hugeandadvise_populateincrates/os/src/lib.rsshare only themadvisecall 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
mallocwith no CPU write, which is whatto_host_vecdid. head is a huge-page advice followed by a CPU fill, which is whathost_filleddoes from 32 MiB up.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::tokenstakes 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 hostcallocupload and 0.186 ms with a device memset (last of three rounds).Output equality and an end-to-end sitting, one GB10
nvidia-smion the machine, and the build under test:The model is
nvidia/Qwen3.8-Flash-Next-FP4-Local(revisionb9ce18a6), served with--parallel 1, context 8192,BLOOMERY_DRAFT=mtpand--cache-ram 363. The twobloomery-servebuilds differ (sha256b0d64b7e…for main and8e48c633…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).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_rowreadback 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 363is below the 389,313,536 bytes of one 4096-id state, so every request loggedcache skipand the synchronous snapshot and the resumeput_draft_rowsnever 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::andcheckpoint::saved::,RUST_TEST_THREADS=1, built forsm_121): 15 passed, andcargo test -p bloomery-os huge_pageon the same machine: 1 passed.cargo test -q -p bloomery-oson an x86 Linux machine with transparent huge pages set tomadvise: 19 passed, on the head before the fix round.Fail-first: with
FILLset to0.0and the retained reader set to allocate on every call, the run of the two new tests (host_filled_memory_holds_the_fill_not_zeroandhw_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 intoEncoder; 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.GB10 card check on a head with the same patches as this one (the huge-page test, then the
Encoderreuse test with and without a mutant that reallocates on every pass, then the owned readback test):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 thehgflag 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 injectedEINVALfrom the advice passes, and the old assertion that required the advice fails (exit 101) under it. No kernel without transparent huge pages was booted.The host benchmark's call to
advise_hugeis checked by a source check that rejects its removal, and bycargo check -p bloomery-model --bin bench_v41_host,cargo fmt --all -- --checkand the unsafe-pin check, which passed.cargo check --workspace --all-targetswith 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:
On the RTX 5090,
just gate-gpu-gemma-embedding2-e2eandjust gate-gpu-gemma-embedding2-serveran on the measured series withBLOOMERY_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 noMANIFEST.tsvfor the Hugging Face reference (clause (h)), the image inputs (clause (i)) or the audio server run, so those clauses and the serve--audiorun did not execute.Not run: the (h) and (i) clauses and the serve
--audiorun (missing reference data), an exact-head workspacecargo checkon the final head, andcargo clippy.cargo check --workspace --all-targetswith 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 pagesmadvise) for thebloomery-ostests.What I ran into
This does not block the PR.
Encoderreuse test's failing assertion is saved in the card check above.cargo test -p bloomery-oswas not re-run in full on this head; the huge-page test and the host check above were.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.