[pr-fix][memory][RAYTRACING] hwrt: segregate BLAS heaps by size class, prefer fullest-fit, and release empty heaps #318
Loading…
Reference in a new issue
No description provided.
Delete branch "Deyzrakc/Darner:fix/blas-heap-fragmentation"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Refs #290
Contributor role (optional)
What it changes
hwrtplaces all BLAS allocations into a single shared pool of 64 MiBID3D12Heaps using a first-fit scan and never releases empty heaps. Onmain(f3840d7), two city driving runs ended with:1,851 MBBLAS in use across3,072 MBallocated (48 × 64 MiBheaps) →1,221 MB(39.7%) empty fragmentation waste1,799 MBBLAS in use across3,264 MBallocated (51 × 64 MiBheaps) →1,465 MB(44.9%) empty fragmentation wasteThis change updates
crates/darner-gpu/src/hwrt.rsto:1unit (≤ 64 KiB),16 MiBheaps, with atrailing_zerossingle-unit fast path2..=8units (128–512 KiB),16 MiBheaps9..=32units (576 KiB–2 MiB),16 MiBheaps33..=256units (> 2–16 MiB),32 MiBheapsfree_units: AtomicUsizescan per heap. Packing nearly full heaps first lets LRU-draining heaps finish emptying instead of being refilled, while keeping empty spare heaps untouched until needed.BLAS_HEAP_SPARE = 1per class whenSlotReturn::dropreturns the last slot of a heap. Lock ordering is alwaysblas_heaps -> heap.used, and theID3D12Heapis dropped outside the pool lock.blas_heap_line().How it was tested
Tested revision:
9e6c112(based onorigin/mainf3840d7)Commands and results:
cargo test --locked --offline -p darner-gpu --lib -- hwrt::→ 29 passed; 0 failed (including the 4 new BLAS heap tests)cargo build --release --locked --offline -p darner --bin darner→ passedChanges a default: yes, for all setups using Hardware RT (
hwrtBLAS placed-resource heap allocation).A/B result (ABBA order: A1, B1, B2, A2 — 4 runs on the same city driving route, shared pre-warmed
v2026.12.03.02cache of 76,582 pipelines, 2 GiBnv-profile, 0 errors in all 4 runs):f3840d7)f3840d7)9e6c112)9e6c112)Gates run on that revision:
cargo clippy --workspace --all-targets --locked --offline -- -D warnings -A deprecated→ passed (-A deprecatedused only for pre-existingAtomic::fetch_updatedeprecation warnings in untouched files on localrustc 1.100.0vs pinned1.98.1)cargo clippy --workspace --all-targets --all-features --locked --offline -- -D warnings -A deprecated→ passedcargo xtask policy→asset policy: 555 files okGameplay: NVIDIA GeForce RTX 5070 Ti (16 GB VRAM), Xbox Series X profile, 1440p, DLSS Balanced, 2x DLSS Frame Generation, High textures, Hardware Ray Tracing enabled, 2 GiB NVIDIA shader heap profile (
darner.exe nv-profile --mb 2048).Shader wave sizes tested: N/A (CPU/D3D12 heap allocator only; no shader changes).
Hardware dependence: likely general across all D3D12 GPUs using Hardware RT (
hwrt); only benchmarked on RTX 5070 Ti 16 GB.Coverage gaps: Not tested on AMD/Intel GPUs or with pinned
rustc 1.98.1(tested withrustc 1.100.0).Checklist
main.docs/asset-policy.md.Checked for overlap
crates/darner-gpu/src/hwrt.rs, unrelated TLAS/Backlog/MeshletCache code)Independent Windows build, gate, and code-read review of head
9e6c1120c02d7855c6b3497ca92782ea3d6944be, based onmainf3840d73d3504c30218debfbc8795b9225447317. Not run in-game.Environment
x86_64-pc-windows-msvc), MSVC 19.44.35230.Measured results
cargo clippy --workspace --all-targets --locked -- -D warnings): PASS.cargo clippy --workspace --all-targets --all-features --locked -- -D warnings): PASS.cargo xtask policy: PASS (asset policy: 555 files ok).cargo test --locked -p darner-gpu --lib hwrt::: PASS (29 passed; 0 failed; 0 ignored).Code-read audit
first_free_run's one-unit path searches only the active bitmap words;try_takerechecks available units and contiguous space underusedbefore marking and publishing the updated free count (crates/darner-gpu/src/hwrt.rs:2533-2627). Class-specific capacities are multiples of 64 units, andtake_existingtreats the atomic count as a candidate hint, with the bitmap mutex as the allocator's final authority (hwrt.rs:2643-2694).take_existingsearches the correct size class, prefers the partially used heap with the least free space that fits, retries other partially used heaps when fragmentation blocks a run, and only then consumes an empty spare (hwrt.rs:2643-2694).create_blas_bufferbounds placement to 16 MiB and falls back to committed resources if placement fails (hwrt.rs:2896-2958).SlotReturn::dropreleases the per-heap lock before taking the pool lock; pool operations consistently useblas_heaps -> heap.used. Empty heaps beyond one spare are removed under the pool lock, while the retainedArcs are dropped outside it (hwrt.rs:2717-2776,2787-2795). The resource's private-data interface retains the slot return until the resource itself is released (hwrt.rs:2923-2958).hwrt.rs:6246-6431). These validate allocator bookkeeping, not actual D3D12 heap behavior or the reported VRAM/performance effect.No blocking issue found.
Verdict: PASS.
AI-assisted: yes (GitHub Copilot, Auto mode).
In-game A/B on an RTX 5080 16 GB: same settings, warm caches, one pair.
Setup: RTX 5080 16 GB, driver 621.40; Ryzen 7 9800X3D, 64 GB, Windows 11 (26300). Series X, 2560x1440, DLAA, DLSS frame generation 2x, hardware RT,
darner nv-profile --mb 2048, default BLAS budget (1,490-1,497 MB from the logs). Release builds. A =f3840d7(built from a fork whose only other changes are a launcher script and docs, nothing in darner.exe); B = A plus this PR (9e6c112). Same save and driving route by hand. An earlier pair started with a cold driver shader cache for A and is left out.f3840d7)By eye: distant objects disappeared for a moment more often in A. No new visual problems in B. Neither run lost the device (both were about 6 minutes, so no claim about device losses).
What this does not show: one pair, driven by hand, of different lengths, so part of the frame-time difference may be the route. The card being 2.7 GB over its budget in A against 0.3 GB in B may explain part of it.
One note from the logs: the PR keeps
cardledger::retag(&heap, Kind::AccelStructure)afterCreateHeap.retagonly changes the kind of an allocation the ledger already counts, so the BLAS heaps stay out of it (the gap noted in #290). The "unaccounted" row above moves by about the heap difference.cardledger::heap(&heap, Kind::AccelStructure)would count them, asalias_rtandpagebufdo.🤖 Generated with Claude Code
Test on an RTX 4070 Ti 12 GB: this held 30 minutes with hardware RT and kept the card under its budget, where main ended over it. One run per arm, so treat it as a data point.
nv-profile2048 MiB. Release builds off3840d73and of this PR's head9e6c1120. Standing in one area with a scripted camera turn every 20 s.DARNER_HW_RT_BLAS_HEAPS=0on main: 883 MB live BLAS, card 689 MB under budget.Tested on a different GPU: RTX 5080 16 GB, Ryzen 7 9800X3D, driver 32.0.16.2140, Windows. A/B on the same save/area with the same settings (
DARNER_MENU_RT=hardware, fullscreen, frame gen on): mainf3840d7vs this PR9e6c112.Method: sampled the
hardware RT BLAS buffers:line every 5 s and compared the loaded part of each run (BLAS in use >= 1,500 MB — 44 samples over ~3.7 min on main, 38 over ~3.2 min on the PR). The scenes were not frame-identical, but mean BLAS in use matched closely (2,001 vs 2,020 MB).f3840d79e6c112At comparable live BLAS, allocated heap memory was ~470 MB lower on average and waste roughly halved. At the highest observed load the PR held 109 MB more BLAS in 224 MB less heap. No correctness issues seen: ~10k live BLAS, AS memory 1,478 MB, no device loss.
One caveat on the release path: at the end, BLAS in use fell from 2,390 to 1,876 MB within 5 s, but allocated only went 2,720 -> 2,688 MB and waste rose to ~810 MB — only 1 heap was released. Since a heap is only released once it is completely empty (one spare per class kept), a sudden drop in live BLAS leaves allocated high until heaps drain. Not necessarily wrong, but the release path got little exercise at this load.
Not tested:
DARNER_HW_RT_BLAS_HEAPS=0, other GPUs, and performance (scenes/durations differ, so fps is not comparable).Drafted with AI assistance (OpenCode).
Code review only (read the diff at
9e6c1120), nothing built or run. I agree with lewis499's allocator audit and with 1rascen's ledger note (cardledger::heapinstead ofretag). New points:Refs #290would connect them. It doesn't touch any shader or descriptor code, so it doesn't conflict with #292, which fixes constant reads.SlotReturn::dropnow takesblas_heaps()(when a heap empties) from inside the runtime's release of the placed buffer, whiletake_unitsholds that lock acrossCreateHeap. I can't show a deadlock from code, but making the heap before taking the pool lock would rule one out at little cost.hwrt.rsPRs (#268, #279, this one) merge cleanly together. A run with #268 merged too, watching the "released" count inblas_heap_line(), would show it.Reviewed with Claude Code (AI-assisted); findings checked by a human before posting.
Thank you all so much for the reviews and independent in-game tests — @lewis499, @1rascen, @Remorce, @m3m3dub5, and @iBooM72! Seeing the results across RTX 4070 Ti 12 GB and RTX 5080 16 GB is super helpful.
I addressed the review points in follow-up commit
347b421:take_unitsnow releasesblas_heaps()before callingID3D12Device::CreateHeap, then re-acquires the lock and re-checkstake_existing(dropping any redundant heap outside the lock) soSlotReturn::dropcannot invert lock order withCreateHeap.cardledger::retag(&heap, Kind::AccelStructure)tocardledger::heap(&heap, Kind::AccelStructure)so BLAS heaps are counted directly underAccelStructureinstead of showing up as unaccounted.Refs #290to the PR description.Re-ran on
347b421:cargo test --locked --offline -p darner-gpu --lib -- hwrt::→ 29 passed, 0 failedcargo clippy --workspace --all-targets --locked --offline -- -D warnings -A deprecated→ passedcargo clippy --workspace --all-targets --all-features --locked --offline -- -D warnings -A deprecated→ passedcargo xtask policy→asset policy: 555 files okView command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.