Skip to content

D3D12.X: sparse tiles outside the GPU heaps can live in system memory - #2987

Open
treybertram06 wants to merge 1 commit into
xcl-dev:nvidia-devfrom
treybertram06:nv-sparse-sysmem
Open

treybertram06 wants to merge 1 commit into
xcl-dev:nvidia-devfrom
treybertram06:nv-sparse-sysmem

Conversation

@treybertram06

Copy link
Copy Markdown
Contributor

Target: nvidia-dev. Part of #2688. Related: gefydev's planned budget-triggered L0 sparse pools (#2688), and #1702 (texture pages in system memory).

With XCL_COHERENT_HEAPS=sparse the title's GPU heaps live in the sparse windows instead of the coherent window. These heaps are committed memory with a PAGE_GRAPHICS_* protection, about 4.5 GB in a retail title. Shaders read and write them every frame. In the coherent window (system RAM, read over PCIe), one retail compute program took 1,364 ms per frame on an RTX 3080; with the heaps in video memory it falls under 33 ms (XCL_GPU_TIMES). An RTX 4080 report on #2688 found the same factor. But with the heaps in video memory, the sparse windows hold about 7.5 GB of tiles. On a 10 GB card the device runs out of budget: 19 GB in use against 8.9 GB, removed at 659 s.

XCL_SPARSE_SYSMEM=1 (off by default) keeps the GPU heaps' tiles in video memory and puts every other sparse-window tile in system memory:

  • kernelx registers a GPU heap's range as hot (sparse::alloc_as) before its commit maps its tiles;
  • other tiles take pool tiles in system-memory pool heaps (custom heaps, MEMORY_POOL_L0, write-back), which the GPU reads over PCIe.

gefydev's plan moves new pools past the budget. This one decides by what a range holds, so the heaps the shaders depend on are never the ones moved.

What is in it

  • D3D12.X: sparse tiles outside the GPU heaps can live in system memory (hle/d3d12x/sparse.rs, hle/kernelx.rs):
    • note_hot / is_hot / alloc_as mark the hot ranges;
    • system-memory pools (SysPools, pool index tagged with SYS) with their own free and cooling lists;
    • pool_heap resolves either kind.
  • New test the_title_gpu_heaps_are_hot_and_nothing_around_them.

Tested

  • RTX 3080 10 GB (driver 621.40), Ryzen 9 5900X, 64 GB RAM, Windows 11 26300, NVIDIA profile with the 2 GiB shader heap for xcl.exe (xcl run: xcl nvprofile puts xcl.exe in an NVIDIA profile with a bigger shader heap (#2403) #2590). Debug tests, release title runs.
  • cargo test --workspace --no-fail-fast -- --test-threads=4, with XCL_DXC_DIR set to DXC 1.9, at this PR's head 6c5904f9: 1822 passed, 11 failed, 48 ignored.
  • cargo test -p xcl --lib the_title_gpu_heaps_are_hot: 1 passed.
  • Retail title, this PR's head, release build, 610 s, XCL_COHERENT_HEAPS=sparse XCL_SPARSE_SYSMEM=1 XCL_TEXTURE_LEVEL_PAGES=1 XCL_PREPARE_WORKERS=6, scripted presses. Over the 400 s after the menus: 0.72 presents/s, video memory 15.1 GB local / 5.0 GB non-local (budget 9.2 GB), commit 41.5 GB, no device removal.
    • The same title with level pages only (heaps in the coherent window): 0.28–0.42 presents/s.
    • Heaps in video memory without this switch: 0.98 presents/s, but 19 GB of video memory and a device removal at 659 s.
    • Rates come from single runs over different stretches of the title (cutscene loading varies), so treat them as rough.
  • XCL_GPU_TIMES with the heaps in the coherent window: the top program cs 10eaefe801508781 took 1,364 ms per frame. With them in video memory, the top program is under 70 ms.

Regression run
Base, a commit of main: b49be183, the last main commit before #2555's launch preparation gate, which takes hours with this title on this card. The switch is off in both runs.

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 3080
title: 4ba6c38e
seconds: 60
exit: 0x0
frames shown: 1415 (PresentX 1415)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15557 MB

This PR's head:

xcl-smoke v1
commit: 6c5904f9426ffdfd4772399c92bfa84ddf29f6e2
gpu: NVIDIA GeForce RTX 3080
title: 4ba6c38e
seconds: 60
exit: 0x0
frames shown: 1535 (PresentX 1535)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 17388 MB

Not tested

AI use

  • Claude Code with Claude Opus 5.5. It measured the placement, wrote the code, the test and this description, and ran the tests and title runs. The author reviewed the diff.

With XCL_COHERENT_HEAPS=sparse the title's GPU heaps (committed memory with
a PAGE_GRAPHICS_* protection, ~4.5 GB in a retail title) live in the sparse
windows. Those are the data the title's shaders read and write every frame;
in the coherent window (system memory, read over PCIe) one retail compute
program took 1,364 ms a frame on an RTX 3080, under 33 ms in video memory.
With them in video memory the windows hold ~7.5 GB of tiles and the device
ran out of its budget (19 GB in use against 8.9 GB, removed at 659 s).

XCL_SPARSE_SYSMEM=1 (off by default): kernelx registers a GPU heap's range
as hot before its commit maps its tiles (sparse::alloc_as); every other
sparse-window tile takes a pool tile in system-memory pool heaps (custom
heaps, L0, write-back), which the GPU reads over PCIe. A pool tile of those
heaps has SYS in its pool index; freed ones cool in their own lists.

RTX 3080, retail title, 400 s of its world after the menus: heaps in video
memory alone 0.98 presents/s and 19 GB of video memory; with this and the
texture-level counterpart 1.70 presents/s, 12.7 GB, no device removal in
900 s. An RTX 4080 report on xcl-dev#2688 found the same with a port of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@thehollowedone

Copy link
Copy Markdown
Contributor

Independent RTX 3080 Ti check of 6c5904f9: with XCL_SPARSE_SYSMEM=1, the eager path places a cold control tile in the system-memory pool, but a lazy cold tile receives a default video-memory pool tile at its first CPU write. The lazy materialization path calls take_tile() directly, bypassing the cold/hot choice in ensure_mapped. This undercuts the VRAM saving when XCL_SPARSE_LAZY=1 is used.

I extended the existing synthetic lazy first-write test to first verify L0 support with an eager control tile and then assert the lazy tile's pool class. On Windows 11 build 26300, RTX 3080 Ti (621.35), Ryzen 7 9800X3D, Rust 1.99.1 MSVC, I set XCL_SPARSE_SYSMEM=1 and XCL_REQUIRE_GPU=1 and ran cargo test --offline --locked -j 4 -p xcl --lib a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them -- --nocapture --test-threads=1. It failed on the PR head (0 passed, 1 failed, 0 ignored, no GPU skip; lazy pool class was video). Sharing the selection in take_tile_for(t) made the same test pass (1 passed, 0 failed, 0 ignored, no GPU skip), including its existing 64-KiB GPU readback. This is a local candidate, not a committed change or a full title validation.

Candidate fix and focused regression diff
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..4f161733 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1301,6 +1301,11 @@ impl State {
         Some(((h, 0), false))
     }
 
+    /// Choose backing by the title reservation that owns this tile.
+    unsafe fn take_tile_for(&mut self, t: usize) -> Option<((u32, u32), bool)> {
+        if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() }
+    }
+
     /// The heap of pool index `h` (video memory, or a system-memory pool with `SYS`).
     fn pool_heap(&self, h: u32) -> ID3D12Heap {
         if h & SYS != 0 {
@@ -1607,7 +1612,7 @@ impl State {
             if self.mapped.get(&t).is_some_and(|e| e.pool == LAZY) {
                 let at_hand = !self.free.is_empty() || cooled(&self.cooling, std::time::Instant::now()) || !self.retired.is_empty();
                 let wait = left > 0 || (!force && self.short_of_memory() && !at_hand);
-                match if wait { None } else { self.take_tile() } {
+                match if wait { None } else { self.take_tile_for(t) } {
                     Some((tile, used)) => {
                         if let Some(e) = self.mapped.get_mut(&t) {
                             e.pool = tile;
@@ -1665,7 +1670,7 @@ impl State {
                     self.to_zero.insert((t, TILE));
                     unparked = true;
                 } else {
-                    let got = if sysmem_tiles() && !is_hot(t) { self.take_sys_tile() } else { self.take_tile() };
+                    let got = self.take_tile_for(t);
                     let Some((tile, reused)) = got else { break };
                     self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
                     early_add(&mut self.runs, t, t + TILE);
@@ -6083,7 +6088,10 @@ mod tests {
     fn a_lazy_tile_gets_memory_at_its_first_bytes_and_keeps_them() {
         let lazy = Lazy::on(true);
         unsafe {
-            let Some((base, mut s, queue)) = lazy_state(2) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
+            let Some((base, mut s, queue)) = lazy_state(3) else { return crate::gpu::recomp::runner::skip_test("no GPU with tiled resources tier 2") };
+            let cold_control = base + 2 * TILE;
+            s.ensure_mapped(cold_control, TILE, |_| 0);
+            assert_ne!(s.mapped[&cold_control].pool.0 & SYS, 0, "eager cold tile uses system memory on this adapter");
             s.commit_range(base, 2 * TILE);
             assert_eq!(s.mapped[&base].pool, LAZY, "committed: listed with no video memory");
             assert_eq!(s.mapped[&(base + TILE)].pool, LAZY);
@@ -6092,6 +6100,7 @@ mod tests {
             let dirty = write_tile(base, 7);
             s.before_execute_on(&queue, &dirty, PAGE);
             assert_ne!(s.mapped[&base].pool, LAZY, "its first bytes gave it a pool tile");
+            assert_ne!(s.mapped[&base].pool.0 & SYS, 0, "lazy cold tile also uses system memory");
             assert_eq!(s.mapped[&(base + TILE)].pool, LAZY, "the tile never written has none");
             let cpu = std::slice::from_raw_parts(base as *const u8, TILE).to_vec();
             assert!(window_bytes(&mut s, base, TILE) == cpu, "the bytes reached the GPU");

The broader policy still needs the lazy path's at_hand/low-memory decision to consider ready system-pool tiles, plus reservation-lifetime handling when an address changes between hot and cold. Those cases were not exercised by this focused test. No game files were used. AI use: Codex (GPT-6.2 Sol) ran the red/green GPU test and wrote the local candidate; Codex (GPT-6.2 Astra) reviewed the sparse allocation paths.

@3L1A5-1

3L1A5-1 commented Nov 27, 2026

Copy link
Copy Markdown

8 GB VRAM / 16 GB RAM data point with XCL_SPARSE_SYSMEM=1 alone (no hot heaps, which an 8 GB card can't hold): local video memory is cut from ~4.1 GB to ~1.1 GB over budget, and it stays under budget until title ~180 s. The cost is system memory, roughly one-for-one, and on 16 GB the run still ends on host memory. One run with the switch. The comparison is against single runs of the same stack without it, and the local over-budget peak was stable at +3.7 to +4.5 GB across 8 runs of this base with and without the other PRs.

Tested

Results

without (same stack) XCL_SPARSE_SYSMEM=1
Local VRAM vs ~7.24 GB budget, title 60 / 120 / 180 / 240 s −1.1 / +0.3 / +2.4 / +2.8 GB −3.4 / −2.7 / −0.0 / +0.4 GB
Local VRAM peak 11.3 GB (+4.1 GB) 8.3 GB (+1.1 GB)
Video-memory sparse pools, peak 3.97 GB 1.22 GB
System-memory pool heaps – 2,048 MB by title 26 s (64 MB heaps)
Non-local video memory, peak 2.7–3.4 GB 6.75 GB
Process commit peak / free RAM min 29.3 GB / 42 MB 29.5 GB / 131 MB
fps, title 100 s → end 2.1 2.4 (0.4–0.8 in the world phase in both)
End Close E_OUTOFMEMORY at title 439.9 s Close E_OUTOFMEMORY at title 399.3 s, no device-removed line
  • 0 no system-memory pool heap warnings. The end time difference is within the 340–440 s spread I see between single runs of this stack, so I'm not reading a gain or loss from it.
  • So on this class of machine the switch moves the overcommit from VRAM into system memory. That helps a lot on the VRAM side, but with 16 GB RAM the host side becomes the limit at about the same point. GPU reads over PCIe didn't cost visible fps here, but the world phase was already below 1 fps.

Not tested: repeats, XCL_COHERENT_HEAPS=sparse (no room in 8 GB), 32 GB RAM, AMD.

AI use: build, run and log analysis by Claude Code agents (Claude Sonnet 5.5), report written and checked against the run logs by Claude Code (Claude Opus 5.5).

@SzczepanGrela

Copy link
Copy Markdown

RX 9070 / Wine: an eager sparse-window system-memory readback works in a focused native GPU fixture at 6c5904f9426ffdfd4772399c92bfa84ddf29f6e2. Both copies and a wave64 compute shader preserve the expected contents through the mixed pool mapping.

Tested

RX 9070 16 GB, RADV GFX1201 / Mesa 26.3.1, Ryzen 7 7700, CachyOS 7.3.0-5, GE-Proton11-12 / Wine 11.0 Staging, vkd3d-proton 8293130ebe370b1+ with local asserts-disabled build, DXC/DXIL 1.9.2602.17, Rust 1.97.1 Windows-GNU release. Explicit adapter, network off, private enabled caches. Owned tests were appended to source copies; production functions and original assertions were unchanged.

Compared the exact head with its actual parent a5e2d851a503fc0e04609f773ea53f2d2c4e3269; the target nvidia-dev had advanced to e0821b12.

cargo test --offline --locked --release --target x86_64-pc-windows-gnu -p xcl --lib --no-run, then the resulting PE under Wine:

  • Head's original hle::d3d12x::sparse::tests::the_title_gpu_heaps_are_hot_and_nothing_around_them --exact --nocapture --test-threads=1 and =4: 1 passed, 0 failed each.
  • Owned hle::d3d12x::sparse::workflow_sysmem_native::workflow_cold_system_tiles_and_hot_video_tiles_read_back --exact --nocapture --test-threads=1: three fresh full processes per source/switch combination, plus one pilot each. XCL_SPARSE_SYSMEM=0 and =1 were tested in separate processes. Each harness passed; zero ignored or skipped tests.

The fixture maps eagerly through ensure_mapped, with XCL_SPARSE_LAZY unset. It uses a 16-tile reserved buffer, with 6 tiles marked hot and 10 cold. It calls production new_state, ensure_mapped, flush_pending and upload_dirty, registering hot ranges directly through note_hot on head.

Source / switch Hot tiles Cold tiles
Parent, either switch DEFAULT pool DEFAULT pool
Head, switch off DEFAULT pool DEFAULT pool
Head, switch on DEFAULT pool CUSTOM, WRITE_BACK, MEMORY_POOL_L0

These are actual pool tags and native ID3D12Heap::GetDesc results. All cold tiles in the enabled head used the system-pool path; no fallback to DEFAULT was counted as coverage.

Every window word was checked after CPU upload, after partial native GPU writes with untouched regions retained, and after an owned wave64 shader loaded, transformed and stored every word through the same window. A separate width buffer verified lane count 64 and its 15 untouched guards.

Independent Python verification checked all 10,223,872 readback words, including 39 MiB of window payload, across 64 native readbacks and 16 wave64 dispatches. Data, guards and shader containers match across sources, switches and fresh repeats. No device removal occurred.

Not tested

Lazy first-write materialization, including the bypass already reported here, the full kernelx VirtualAlloc / alloc_as caller, hot-range free/reuse lifecycle, title workload, smoke, full suite, native Windows, physical residency, budget reduction or performance. Heap properties and GPU data correctness do not establish those measurements. Main 83b00818 was not integrated or built: the three-way file application conflicts in sparse.rs and kernelx.rs; no manual repairs were made.

AI use

OpenAI Codex (GPT-6; exact serving variant not exposed) reviewed the public change, wrote and ran the fixture and independent verifier, and drafted this report. Publication authorized by the account owner.

@thehollowedone

Copy link
Copy Markdown
Contributor

New, separate finding on #2987 head 6c5904f9, following my earlier lazy-placement report: a cold tile can be decommitted into parked, then immediately recommitted at the same address after that address becomes a title GPU heap. ensure_mapped takes the parked tuple before checking is_hot, so the new hot heap inherits system-memory backing. This is distinct from the lazy first-write path.

I added a synthetic one-tile GPU regression that commits cold, flushes the mapping, verifies the SYS pool bit, decommits, calls note_hot for the same address, and recommits. On Windows 11 build 26300, RTX 3080 Ti (621.35), Ryzen 7 9800X3D, Rust 1.99.1 MSVC, with XCL_SPARSE_SYSMEM=1 and XCL_REQUIRE_GPU=1, cargo test --offline --locked -j 4 -p xcl --lib a_parked_cold_tile_does_not_back_a_new_hot_heap -- --nocapture --test-threads=1 failed on the PR head (0 passed, 1 failed, 0 ignored, no GPU skip; pool index retained the SYS bit). The candidate below passed the same test (1 passed, 0 failed, 0 ignored, no GPU skip).

The candidate acquires a video-memory replacement before touching the parked mapping, then unmaps and quarantines the old tile behind the existing queue fences. It leaves pinned tiles on their existing backing so placed-buffer aliases remain intact. It is a focused local candidate, not a full proof of safe retirement under every queue schedule; the author should review and extend the pinned/blocked-queue tests before merging.

Candidate correction and regression diff
diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs
index 979b4d04..cae3e6a3 100644
--- a/crates/xcl/src/hle/d3d12x/sparse.rs
+++ b/crates/xcl/src/hle/d3d12x/sparse.rs
@@ -1658,8 +1658,26 @@ impl State {
         let mut t = first;
         while t < end {
             if !self.mapped.contains_key(&t) && !self.mirror_src.contains_key(&t) && self.window_index(t).is_some() {
-                // still mapped there: no new mapping, what it held is cleared
-                if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
+                // A new GPU heap at this address cannot inherit a parked system-memory tile.
+                // Acquire its replacement first; keep the old mapping if video memory is unavailable.
+                if let Some(old) = self.parked.get(&t).copied().filter(|tile| is_hot(t) && tile.0 & SYS != 0 && !self.pinned.contains_key(tile)) {
+                    let Some((tile, reused)) = self.take_tile() else { break };
+                    let wi = self.window_index(t).expect("mapped window");
+                    let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone());
+                    self.unmap_tiles(&r, b, &[t]);
+                    TILE_WORK[2].fetch_add(1, Ordering::Relaxed);
+                    self.signal();
+                    self.quarantine_tiles(vec![old]);
+                    self.parked.remove(&t);
+                    self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
+                    early_add(&mut self.runs, t, t + TILE);
+                    if reused {
+                        self.to_zero.insert((t, TILE));
+                    }
+                    self.pending.push(t);
+                    new = true;
+                } else if let Some(tile) = self.parked.remove(&t).or_else(|| self.kept.remove(&t)) {
+                    // still mapped there: no new mapping, what it held is cleared
                     self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t)));
                     early_add(&mut self.runs, t, t + TILE);
                     self.to_zero.insert((t, TILE));
@@ -5506,6 +5524,38 @@ mod tests {
         assert_eq!(system.0 & !SYS, video.0);
     }
 
+    #[test]
+    fn a_parked_cold_tile_does_not_back_a_new_hot_heap() {
+        use windows_sys::Win32::System::Memory::MEM_RELEASE;
+
+        if !sysmem_tiles() {
+            return crate::gpu::recomp::runner::skip_test("XCL_SPARSE_SYSMEM=1 required");
+        }
+        let _lazy = Lazy::on(false);
+        unsafe {
+            let (base, mut s) = test_state_with_reserved(1);
+            s.commit_range(base, TILE);
+            s.flush_pending();
+            let cold = s.mapped[&base].pool;
+            if cold.0 & SYS == 0 {
+                s.wait_for(s.value);
+                drop(s);
+                assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+                return crate::gpu::recomp::runner::skip_test("system-memory pool unavailable");
+            }
+            s.decommit_range(base, TILE);
+            assert_eq!(s.parked.get(&base), Some(&cold));
+            note_hot(base, TILE);
+            s.commit_range(base, TILE);
+            assert_eq!(s.mapped[&base].pool.0 & SYS, 0, "a hot heap must use video memory");
+            s.flush_pending();
+            s.wait_for(s.value);
+            drop(s);
+            HOT.lock().unwrap().retain(|&(a, n)| a != base || n != TILE);
+            assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
+        }
+    }
+
     #[test]
     fn aligned_tile_addresses_spread_across_hash_buckets() {
         use std::hash::BuildHasher;

Separate test-coverage note: with XCL_SPARSE_SYSMEM=1, the broader parked filter still has two existing failures because those tests expect released tiles in the video-memory s.cooling queue. The candidate does not change them. With the feature unset, that filter completed 6 passed, 0 failed, with the new SYS-only case reporting a skip; those six passes are not six SYS-mode coverage cases.

No game files or title executable were used. AI use: Codex (GPT-6.2 Sol) wrote and ran the red/green test and candidate; Codex (GPT-6.2 Astra) checked the mapping and fence sequence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants