GPU: pipelines off the render thread and cached; indirect execution on

With indirect execution the world's first frame asked for over 1,200
pipelines at once and took more than 30 s, so the title's own GPU
watchdog ended the run. Host pipelines are now made by worker threads: a
first use waits at most 0.5 s per title frame, and that pipeline's draws
are dropped until it is ready. The world presents frames again, and
indirect execution is the default (the switch is gone).

Pipelines are cached across runs:
- every host pipeline goes into a pipeline library saved under the cache
  folder (named by a hash of the translated code, our root signature and
  the state; a blob the device rejects starts an empty library);
- the pipelines drawn with are remembered and started during loading on
  the next run.
One cold and one warm run: the last pipeline was ready 38 s after the
world's first frame cold, 1.4 s warm; the first world frame took 3.2 s
cold, 0.37 s warm.

Also:
- Copy-backs of shader-written ranges return only the bytes the GPU
  changed; they used to overwrite what the title's CPU wrote meanwhile,
  which crashed the title.
- Indirect dispatch records are bounded (group counts were not), and the
  console's single-dispatch argument type runs as a dispatch.
- Per-shader counts of dropped draws in the diagnostics log; a switch
  that submits and times each list alone.

Not working yet: the world shows no geometry, and runs end on a GPU page
fault after at most about 55 s.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
MarvisandClaude Fable 5.2 committed 2026-11-24 01:02:11 +01:00
1 parent b9aff99b98
commit 62b737a69b
13 files changed
+1018 -101

No files matched your search

+170 -15
View File
@@ -254,8 +254,16 @@ pub(crate) struct HostList {
/// data without marker texts), with the host GPU range a copy reads.
#[cfg(feature = "diagnostics")]
notes: Mutex<Vec<Note>>,
/// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
/// and at the end, and where they are read back.
#[cfg(feature = "diagnostics")]
stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
}
/// Timestamps per list (diagnostics); commands past them are not timed.
#[cfg(feature = "diagnostics")]
const STAMPS: u32 = 4096;
/// A marker's text and the host range its command reads (diagnostics).
#[cfg(feature = "diagnostics")]
type Note = (String, Option<(u64, u64)>);
@@ -274,6 +282,15 @@ pub(crate) fn dred_on() -> bool {
})
}
/// Whether each list of a submission runs and is timed on its own, slow
/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
/// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
#[cfg(feature = "diagnostics")]
fn timing() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
}
/// Names a host object for the device-removed report, which names the
/// allocations a page fault hit (only with device-removed data on).
pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
@@ -412,42 +429,77 @@ impl Host {
budget: OnceLock::new(),
#[cfg(feature = "diagnostics")]
notes: Mutex::default(),
#[cfg(feature = "diagnostics")]
stamps: OnceLock::new(),
})
}
}
/// Runs closed lists and waits for them.
pub(crate) fn execute(&self, runs: &[&HostList]) {
// One submission at a time from preparation to copy-back: snapshots
// and the ranges shaders write are per host copy, not per submission.
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
let started = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::Submissions, 1);
let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
// Where each run's lists start in `lists`.
let mut firsts = Vec::with_capacity(runs.len());
let mut batch = Batch::default();
for list in runs {
list.run_deferred(&mut batch);
firsts.push(lists.len());
if let Some(prelude) = list.prelude() {
lists.push(Some(prelude));
}
lists.push(list.list.cast().ok());
}
batch.flush();
let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
*submitted += 1;
let prepared = std::time::Instant::now();
// SAFETY: closed lists; the fence and event are ours.
unsafe {
self.queue.ExecuteCommandLists(&lists);
let waited = self
.queue
.Signal(&self.fence, *submitted)
.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
match waited {
Ok(()) => {
WaitForSingleObject(self.event, INFINITE);
// Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
#[cfg(feature = "diagnostics")]
let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
firsts
.iter()
.zip(firsts.iter().skip(1).chain([&lists.len()]))
.map(|(&a, &b)| &lists[a..b])
.collect()
} else {
vec![&lists[..]]
};
#[cfg(not(feature = "diagnostics"))]
let groups = [&lists[..]];
for (i, group) in groups.iter().enumerate() {
*submitted += 1;
let started = std::time::Instant::now();
// SAFETY: closed lists; the fence and event are ours.
unsafe {
self.queue.ExecuteCommandLists(group);
let waited = self
.queue
.Signal(&self.fence, *submitted)
.and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
match waited {
Ok(()) => {
WaitForSingleObject(self.event, INFINITE);
}
Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
}
Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
}
#[cfg(feature = "diagnostics")]
if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) {
// SAFETY: a plain query.
let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
for (ms, op) in runs[i].slowest(frequency, 6) {
tracing::warn!("slow list command, {ms:.1} ms: {op}");
}
}
let _ = (i, started);
}
let _ = &firsts;
let gpu = prepared.elapsed();
SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
@@ -677,7 +729,92 @@ impl Host {
}
impl HostList {
/// The timestamp heap and its read-back buffer (diagnostics, timing on).
#[cfg(feature = "diagnostics")]
fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
if !timing() {
return None;
}
self.stamps
.get_or_init(|| {
let device = &host()?.device;
let mut heap: Option<ID3D12QueryHeap> = None;
let mut back: Option<ID3D12Resource> = None;
let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: u64::from(STAMPS) * 8,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
// SAFETY: plain object creation.
unsafe {
device
.CreateQueryHeap(
&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
&mut heap,
)
.ok()?;
device
.CreateCommittedResource(
&readback,
D3D12_HEAP_FLAG_NONE,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST,
None,
&mut back,
)
.ok()?;
}
Some((heap?, back?))
})
.as_ref()
}
/// The noted commands that took longest on the GPU, longest first, as
/// (milliseconds, text) (diagnostics, timing on, after the list ran).
#[cfg(feature = "diagnostics")]
fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
return Vec::new();
};
let mut data = std::ptr::null_mut();
let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
// SAFETY: a read-back buffer the finished list resolved into.
let stamps: Vec<u64> = unsafe {
if back.Map(0, Some(&range), Some(&mut data)).is_err() {
return Vec::new();
}
let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
back.Unmap(0, None);
s
};
let mut times: Vec<(f64, String)> = (0..count)
.map(|i| {
let ticks = stamps[i + 1].saturating_sub(stamps[i]);
(ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
})
.collect();
times.sort_by(|a, b| b.0.total_cmp(&a.0));
times.truncate(n);
times
}
pub(crate) fn close(&self) {
#[cfg(feature = "diagnostics")]
if let Some((heap, back)) = self.stamps() {
let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
// SAFETY: an open list, our heap and read-back buffer.
unsafe {
self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
}
}
// SAFETY: our list.
if let Err(e) = unsafe { self.list.Close() } {
fail(format_args!(
@@ -790,6 +927,11 @@ impl HostList {
#[cfg(feature = "diagnostics")]
fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
if dred_on() {
let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
// SAFETY: an open list and our query heap.
unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
}
let what = what();
let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
const UNICODE: u32 = 0;
@@ -1280,16 +1422,29 @@ impl Meter {
});
let dropped = crate::draw::take_dropped() as f64 / frames;
let indirect = crate::list::take_indirect() as f64 / frames;
// Over the same frames as the counts above.
#[cfg(feature = "diagnostics")]
let drops = crate::pipeline::take_drops();
if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
self.logged = std::time::Instant::now();
tracing::info!(
"{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
{copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect"
dropped {dropped:.0} without a host pipeline ({making} being made) and \
{indirect:.0} indirect",
making = crate::pipeline::making()
);
#[cfg(feature = "diagnostics")]
crate::copystat::log(frames);
{
crate::copystat::log(frames);
for (why, n) in drops.iter().take(40) {
tracing::info!(
"dropped {:.1}/frame without a host pipeline: {why}",
*n as f64 / frames
);
}
}
}
if self.caption.is_none() {
// The window's own text, read without a message.