VICTORY_CARD_AWAKE: the card's clocks kept up between submissions

A captured frame whose lists take 28.6 ms sent in one go takes 37.8 ms with
1.2 ms between its submissions, as the game sends them; with one group of
threads counting on a compute queue it takes 28.6 ms again, and nothing
changes when sent in one go (36.1 against 36.3 ms with its copies).
=turns: 20 s on, 20 s off, to compare in one run. Replay: --awake,
--no-restore makes no copies to restore from.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 04:00:22 -06:00
1 parent 26b15e8fe3
commit 86694b5ad2
5 files changed
+224 -3

No files matched your search

+4
View File
@@ -85,6 +85,9 @@ pub(crate) struct Replay {
/// idle between them, as it does while the title prepares the next.
#[arg(long, default_value_t = 0.0)]
pace: f64,
/// Keep the card's clocks up meanwhile (VICTORY_CARD_AWAKE=1).
#[arg(long)]
awake: bool,
/// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light).
#[arg(long)]
breadcrumbs: bool,
@@ -263,6 +266,7 @@ pub(crate) fn run(r: Replay) -> Result<()> {
wait_all: r.wait_all,
wait_lists: r.wait_lists,
pace: r.pace,
awake: r.awake,
only,
until,
skip_shaders: r.skip_shader,
+2
View File
@@ -3167,6 +3167,7 @@ fn late_line(frames: f64) {
}
}
pub(crate) mod awake;
mod card_steps;
mod place;
mod send;
@@ -5030,6 +5031,7 @@ impl Host {
self.queue.ExecuteCommandLists(&lists);
self.queue.Signal(&self.fence, *submitted)
};
awake::sent(&self.device);
self.card_sent();
if let Err(e) = signalled {
fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
+204
View File
@@ -0,0 +1,204 @@
//! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off
//! by default). The card stands idle half of every frame, some thirty times for
//! a millisecond or two each, while the CPU prepares the next submission. The
//! driver takes that for a light load and lowers the clocks, and what comes
//! next starts slow: a captured frame whose lists take 30 ms sent in one go
//! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions
//! (`victory replay --pace`).
//!
//! One group of 64 threads counts on a compute queue, over and
//! over: it takes one or two of the card's few thousand wave slots, and the
//! card is never idle. Nothing is sent once no submission has gone out for a
//! while (a menu at 30 fps, a minimized window).
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
/// About 2 ms at full clocks: 500 sends a second.
const COUNT: &str = r#"
#define RS "UAV(u0)"
RWByteAddressBuffer sum : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
uint x = id.x;
[loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u;
sum.Store(id.x * 4u, x);
}
"#;
/// Quiet this long after the last submission.
const QUIET_MS: u64 = 250;
fn now_ms() -> u64 {
static START: OnceLock<std::time::Instant> = OnceLock::new();
START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
}
/// When a submission was last sent ([`now_ms`] plus one; 0: never).
static LAST: AtomicU64 = AtomicU64::new(0);
fn wanted() -> bool {
let (last, now) = (LAST.load(Ordering::Relaxed), now_ms());
last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1)
}
/// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off.
const TURN_MS: u64 = 20_000;
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Off,
On,
/// On and off by turns, to compare the two in one run (the log says when).
ByTurns,
}
fn mode() -> Mode {
static MODE: OnceLock<Mode> = OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() {
Ok("1") => Mode::On,
Ok("turns") => Mode::ByTurns,
_ => Mode::Off,
})
}
/// A submission of the title's goes to `device`'s drawing queue.
pub(super) fn sent(device: &ID3D12Device) {
if mode() == Mode::Off {
return;
}
let now = now_ms();
let before = LAST.swap(now + 1, Ordering::Relaxed);
if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS {
tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns");
}
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
// Runs as long as the process does.
std::mem::forget(start(device, wanted));
});
}
/// The thread that keeps the card busy; it ends when this is dropped.
pub(crate) struct Awake {
stop: std::sync::Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Awake {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
/// Keeps the card of `device` busy while `wanted`.
pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option<Awake> {
let stop = std::sync::Arc::new(AtomicBool::new(false));
let (device, ended) = (device.clone(), stop.clone());
let thread = std::thread::Builder::new()
.name("victory-card-awake".into())
.spawn(move || {
if let Err(e) = run(&device, &wanted, &ended) {
tracing::warn!(error = %e, "the card is not kept awake");
}
})
.ok()?;
Some(Awake {
stop,
thread: Some(thread),
})
}
fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> {
let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?;
// SAFETY: plain object creation; the code lives through the calls, the
// root signature is inside it. Two closed lists, sent in turn, whose
// objects live until what was sent last has run.
unsafe {
let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?;
let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})?;
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COMPUTE,
Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0,
..Default::default()
})?;
let mut sum: Option<ID3D12Resource> = None;
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
},
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 256,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
None,
&mut sum,
)?;
let sum = sum.ok_or_else(windows::core::Error::empty)?;
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?;
let mut lists = Vec::new();
for _ in 0..2 {
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?;
list.SetComputeRootSignature(&root);
list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress());
list.Dispatch(1, 1, 1);
list.Close()?;
lists.push(Some(list.cast::<ID3D12CommandList>()?));
}
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let event = CreateEventW(None, false, false, None)?;
let mut value = 0u64;
let mut result = Ok(());
while !stop.load(Ordering::Relaxed) && result.is_ok() {
if !wanted() {
std::thread::sleep(Duration::from_millis(2));
continue;
}
// Never more than two on the way.
if value >= 2 && fence.GetCompletedValue() + 2 <= value {
result = fence.SetEventOnCompletion(value - 1, event);
if result.is_ok() {
WaitForSingleObject(event, 1000);
result = device.GetDeviceRemovedReason();
}
continue;
}
queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]);
value += 1;
result = queue.Signal(&fence, value);
}
if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() {
WaitForSingleObject(event, INFINITE);
}
let _ = CloseHandle(event);
result
}
}
+12 -2
View File
@@ -87,6 +87,8 @@ pub struct Options {
/// Milliseconds the sender waits after each submission, as a title does
/// that prepares the next one meanwhile: the card stands idle.
pub pace: f64,
/// The card kept awake meanwhile (`crate::host::awake`).
pub awake: bool,
/// Run only these lists (by their place in the frame).
pub only: Option<(u32, u32)>,
/// The last command that runs (list, command); after it only barriers.
@@ -123,6 +125,7 @@ impl Default for Options {
wait_all: false,
wait_lists: false,
pace: 0.0,
awake: false,
only: None,
until: None,
skip_shaders: Vec::new(),
@@ -158,6 +161,7 @@ impl Options {
one_submit: false,
wait_all: false,
wait_lists: false,
awake: false,
only: None,
skip_shaders: Vec::new(),
..self.clone()
@@ -582,7 +586,7 @@ impl Player {
step("descriptors", &mut at);
player.load_contents()?;
step("contents", &mut at);
player.make_masters(options.buffers)?;
player.make_masters(options.buffers, options.restore)?;
step("copies to restore from", &mut at);
let steps: Vec<String> = steps
.iter()
@@ -1566,7 +1570,7 @@ impl Player {
}
/// Copies of what the frame changes; and the states it leaves.
fn make_masters(&mut self, buffers: Buffers) -> Result<()> {
fn make_masters(&mut self, buffers: Buffers, wanted: bool) -> Result<()> {
let mut states = States::default();
for r in &self.frame.resources {
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
@@ -1699,6 +1703,11 @@ impl Player {
})
.collect();
ids.sort_unstable();
// Without restoring they are of no use, and their room may be what
// the frame itself lacks.
if !wanted {
ids.clear();
}
let mut total = 0u64;
let mut in_pc = 0u64;
for id in ids {
@@ -2962,6 +2971,7 @@ impl Player {
/// Runs the frame as the options say.
pub fn run(&mut self, o: &Options) -> Result<Report> {
let mut made = self.prepare(o)?;
let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None };
let mut stamps = Vec::new();
for _ in 0..o.loops.max(1) {
stamps = self.once(o, &mut made)?;
+2 -1
View File
@@ -69,8 +69,9 @@ with the presented one.
| `--only 3..7` | runs these lists; of the others only barriers |
| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
| `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
| `--no-restore` | leaves what a loop changed |
| `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) |
| `--pace <ms>` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one |
| `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) |
| `--breadcrumbs` | the system's breadcrumbs (`VICTORY_D3D12_DRED=light`) |
| `--debug-layer` | D3D12's debug layer; its errors in the report |