Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
blob is left to the runtime instead of being compiled in the pass — those compiles take tens
of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB`
sets the cap in KiB (0 turns it off).
- **Cold PSO benchmark:** `scripts/cold-pso-bench.ps1 -Shaders <pack-or-folder> -Threads 4,8`
writes a thread-count comparison to `summary.csv`. A missing, empty or malformed timing file
stops the run instead of reporting a zero-cost measurement. After successful preparation, a new
measurement pass removes the old summary and replaces it only when every timing file is valid.
If an old timing file cannot be removed (for example, it is locked or read-only), the run stops
before starting that measurement.
- **Without a command line** (xcl.exe opened from Explorer) XCL shows a small menu: *Choose a
game…* (pick its exe or `MicrosoftGame.config`) or *Run again* (the last one). On an error the
window stays open until Enter.
Expand Down
63 changes: 56 additions & 7 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,7 +1044,6 @@ fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Opt
}

fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option<bool>) -> Result<(), MeasureError> {
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
use MeasureError::{Failed, Unavailable};

Expand All @@ -1056,10 +1055,7 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl
let pipeline = Pipelines::new().map_err(|e| Unavailable(format!("no GPU device: {e}")))?;
// before translating and compiling (tens of seconds for a big program): a machine that
// cannot turn the caches off fails at once
let dev9 = pipeline.dev.cast::<ID3D12Device9>().map_err(|e| Unavailable(format!("ID3D12Device9 is required to disable the driver cache: {e}")))?;
let cache_kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER;
unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) }
.map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?;
disable_implicit_shader_caches(&pipeline.dev).map_err(Unavailable)?;
let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev));
let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?;
let dxc_start = std::time::Instant::now();
Expand Down Expand Up @@ -1137,6 +1133,26 @@ struct Pipelines {
most: usize,
/// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off)
max_dxil: usize,
/// `XCL_PIPELINE_TIMES=<file>`: one `timing_line` per pipeline, for benchmarks of the driver
times: Option<Mutex<std::fs::File>>,
}

/// Turns off the D3D and driver shader caches of `dev` for this process, so a driver compile
/// is timed cold. Needs Windows Developer Mode; without it this fails rather than letting a
/// warm cache pass for a cold build.
fn disable_implicit_shader_caches(dev: &windows::Win32::Graphics::Direct3D12::ID3D12Device) -> Result<(), String> {
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
let dev9 = dev.cast::<ID3D12Device9>().map_err(|e| format!("ID3D12Device9 is required to disable the driver cache: {e}"))?;
let kinds = D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_DRIVER_MANAGED | D3D12_SHADER_CACHE_KIND_FLAG_IMPLICIT_D3D_CACHE_FOR_DRIVER;
unsafe { dev9.ShaderCacheControl(kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) }.map_err(|e| format!("cannot disable the driver cache (Windows Developer Mode is required): {e}"))
}

/// A line of `XCL_PIPELINE_TIMES`: the DXIL's hash and size, what came of it (`made`: compiled
/// by the driver, `reused`: from a driver blob, `refused`), the wait for a compile slot and the
/// time inside `CreateComputePipelineState`, in milliseconds.
fn timing_line(dxil: &[u8], outcome: &str, wait: std::time::Duration, driver: std::time::Duration) -> String {
format!("{:016x},{},{outcome},{:.1},{:.1}", crate::gpu::shader::fnv64(dxil), dxil.len(), wait.as_secs_f64() * 1000.0, driver.as_secs_f64() * 1000.0)
}

/// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no
Expand Down Expand Up @@ -1216,7 +1232,15 @@ impl Pipelines {
let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?;
let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1);
let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024);
Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil })
// `XCL_PIPELINE_CACHE_OFF=1`: every compile cold, or no pass at all
if std::env::var("XCL_PIPELINE_CACHE_OFF").is_ok_and(|v| v.trim() == "1") {
disable_implicit_shader_caches(&dev)?;
}
let times = match std::env::var_os("XCL_PIPELINE_TIMES") {
Some(p) => Some(Mutex::new(std::fs::OpenOptions::new().create(true).append(true).open(&p).map_err(|e| format!("XCL_PIPELINE_TIMES {}: {e}", PathBuf::from(&p).display()))?)),
None => None,
};
Ok(Pipelines { dev, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil, times })
}
}

Expand Down Expand Up @@ -1262,13 +1286,16 @@ impl Pipelines {
drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature));
return;
}
let waited = std::time::Instant::now();
{
let mut n = self.running.0.lock().unwrap();
while *n >= self.most {
n = self.running.1.wait(n).unwrap();
}
*n += 1;
}
let wait = waited.elapsed();
let started = std::time::Instant::now();
let from_cache = cached.as_ref().and_then(|bytes| {
desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() };
// a driver that cannot use the blob may compile from the DXIL itself and still
Expand All @@ -1290,12 +1317,16 @@ impl Pipelines {
drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature));
return;
}
let mut driver = started.elapsed();
let reused = from_cache.is_some();
let r = if let Some(pso) = from_cache {
self.reused.fetch_add(1, Ordering::Relaxed);
Ok(pso)
} else {
desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default();
let cold = std::time::Instant::now();
let pso = unsafe { self.dev.CreateComputePipelineState::<ID3D12PipelineState>(&desc) };
driver = cold.elapsed();
if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) {
if let Ok(blob) = unsafe { pso.GetCachedBlob() } {
let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>();
Expand All @@ -1310,6 +1341,11 @@ impl Pipelines {
*self.running.0.lock().unwrap() -= 1;
self.running.1.notify_one();
drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature));
if let Some(f) = &self.times {
let outcome = if r.is_err() { "refused" } else if reused { "reused" } else { "made" };
use std::io::Write;
let _ = writeln!(f.lock().unwrap(), "{}", timing_line(&c.dxil, outcome, wait, driver));
}
let done = match r {
Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1,
Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1,
Expand All @@ -1331,7 +1367,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on
match Pipelines::new() {
Ok(p) => Some(p),
Err(e) => {
eprintln!("xcl shaders --pipelines: no GPU device: {e}");
eprintln!("xcl shaders --pipelines: no pipelines can be made: {e}");
return 2;
}
}
Expand Down Expand Up @@ -1802,6 +1838,19 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim

#[cfg(test)]
mod tests {
/// `XCL_PIPELINE_TIMES` lines: hash and size of the DXIL, the outcome, then the slot wait and
/// the driver time in milliseconds with one decimal.
#[test]
fn pipeline_timing_lines_name_the_dxil_outcome_and_both_times() {
use std::time::Duration;
let dxil = vec![7u8; 1500];
let line = super::timing_line(&dxil, "made", Duration::from_micros(2_345), Duration::from_millis(9_876));
assert_eq!(line, format!("{:016x},1500,made,2.3,9876.0", crate::gpu::shader::fnv64(&dxil)));
let fields: Vec<&str> = line.split(',').collect();
assert_eq!(fields.len(), 5);
assert!(super::timing_line(&dxil, "refused", Duration::ZERO, Duration::ZERO).ends_with(",refused,0.0,0.0"));
}

/// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the
/// key of a pipeline of that one shader, as `real::shaders_key` makes it.
#[test]
Expand Down
156 changes: 156 additions & 0 deletions scripts/cold-pso-bench.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Cold NVIDIA (or any) driver compile benchmark of compute pipelines, for #2088 workstream 6.
#
# .\scripts\cold-pso-bench.ps1 -Shaders <shaders.rpf or a folder of records> [-Threads 4,8,12]
# [-Limit N] [-Xcl .\target\release\xcl.exe] [-Out <folder>] [-ClearNvCache]
#
# One `xcl shaders --precompile --only cs` pass fills a DXIL cache first (DXC, not measured). Then
# for every thread count `--pipelines` makes every compute pipeline of the same input again, with
# XCL's driver blobs off (XCL_PSO_DISK_CACHE=0) and the implicit D3D and driver shader caches off
# (XCL_PIPELINE_CACHE_OFF=1, needs Windows Developer Mode). -ClearNvCache instead empties
# %LOCALAPPDATA%\NVIDIA\DXCache before each run (it also drops other applications' entries).
# Every measured run starts a copy of -Xcl with a name of its own, next to it (the copy is removed
# after the run): the AMD driver keys its shader cache on the exe's file name, so a second run of
# the same name is served warm whatever was cleared (measured on RDNA4, #2129).
# Each build's driver time comes from XCL_PIPELINE_TIMES. Prints a table per thread count: wall
# time, CPU time, peak private commit, pipelines made, summed driver time, p50 / p95 / max per
# pipeline, and the same per DXIL size bucket. Warm runs are not cold numbers: do not mix them.
param(
[Parameter(Mandatory = $true)][string]$Shaders,
# strings: `powershell -File ... -Threads 4,8` passes one string "4,8", which [int[]] would
# read as the number 48
[string[]]$Threads = @(4, 6, 8, 10, 12, 16, 20, 24),
[int]$Limit = 0,
[string]$Xcl = (Join-Path $PSScriptRoot '..\target\release\xcl.exe'),
[string]$Out = (Join-Path ([IO.Path]::GetTempPath()) ('xcl-cold-pso-' + (Get-Date -Format 'yyyyMMdd-HHmmss'))),
[switch]$ClearNvCache,
[int]$TimeoutMinutes = 120
)
$ErrorActionPreference = 'Stop'
[Threading.Thread]::CurrentThread.CurrentCulture = [Globalization.CultureInfo]::InvariantCulture
$Threads = @($Threads | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($t in $Threads) { if ($t -notmatch '^[1-9]\d{0,3}$') { throw "-Threads: '$t' is not a thread count (give them as 4,8,12)" } }
if (-not (Test-Path $Xcl)) { throw "no $Xcl - build it first (cargo build --release -p xcl)" }
$null = New-Item -ItemType Directory -Force -Path $Out
$dxil = Join-Path $Out 'dxil'

# The value at fraction q of the sorted numbers (nearest rank).
function Get-Rank([double[]]$Sorted, [double]$Q) {
if ($Sorted.Count -eq 0) { return 0 }
$Sorted[[math]::Min($Sorted.Count - 1, [math]::Max(0, [math]::Ceiling($Q * $Sorted.Count) - 1))]
}

# Rows of an XCL_PIPELINE_TIMES file: hash, bytes, outcome, wait ms, driver ms.
function Read-Times([string]$Path) {
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "timing file '$Path' is missing" }
$lineNumber = 0; $rowCount = 0
$culture = [Globalization.CultureInfo]::InvariantCulture
foreach ($line in (Get-Content -LiteralPath $Path)) {
$lineNumber++
if ([string]::IsNullOrWhiteSpace($line)) { continue }
$where = "timing file '$Path', line ${lineNumber}"
$f = $line.Split(',')
if ($f.Count -ne 5) { throw "${where}: expected five fields (hash, bytes, outcome, wait ms, driver ms)" }
if ($f[0] -notmatch '^[0-9a-fA-F]{16}$') { throw "${where}: hash must contain 16 hexadecimal digits" }
$bytes = 0L
if (-not [long]::TryParse($f[1], [Globalization.NumberStyles]::None, $culture, [ref]$bytes) -or $bytes -le 0) {
throw "${where}: bytes must be a positive 64-bit integer"
}
if (@('made', 'refused', 'reused') -cnotcontains $f[2]) { throw "${where}: unknown outcome '$($f[2])'" }
$waitMs = 0.0; $driverMs = 0.0
if (-not [double]::TryParse($f[3], [Globalization.NumberStyles]::Float, $culture, [ref]$waitMs) -or
-not [double]::TryParse($f[4], [Globalization.NumberStyles]::Float, $culture, [ref]$driverMs) -or
[double]::IsNaN($waitMs) -or [double]::IsInfinity($waitMs) -or $waitMs -lt 0 -or
[double]::IsNaN($driverMs) -or [double]::IsInfinity($driverMs) -or $driverMs -lt 0) {
throw "${where}: wait and driver milliseconds must be finite non-negative numbers"
}
$rowCount++
[pscustomobject]@{ Hash = $f[0]; Bytes = $bytes; Outcome = $f[2]; WaitMs = $waitMs; DriverMs = $driverMs }
}
if ($rowCount -eq 0) { throw "timing file '$Path' has no measurement rows" }
}

$Buckets = @(@('< 64 KiB', 0, 64KB), @('64-256 KiB', 64KB, 256KB), @('256 KiB-1 MiB', 256KB, 1MB), @('1-4 MiB', 1MB, 4MB), @('>= 4 MiB', 4MB, [long]::MaxValue))

# Summary of the driver builds of one run (the `made` rows: cold compiles).
function Get-Summary($Rows) {
$made = @($Rows | Where-Object Outcome -eq 'made')
$ms = [double[]]@($made | ForEach-Object DriverMs | Sort-Object)
$s = [ordered]@{
made = $made.Count
refused = @($Rows | Where-Object Outcome -eq 'refused').Count
reused = @($Rows | Where-Object Outcome -eq 'reused').Count
driver_s = [math]::Round((($ms | Measure-Object -Sum).Sum) / 1000, 1)
p50_s = [math]::Round((Get-Rank $ms 0.5) / 1000, 2)
p95_s = [math]::Round((Get-Rank $ms 0.95) / 1000, 2)
max_s = [math]::Round((Get-Rank $ms 1.0) / 1000, 2)
buckets = @()
}
foreach ($b in $Buckets) {
$in = [double[]]@($made | Where-Object { $_.Bytes -ge $b[1] -and $_.Bytes -lt $b[2] } | ForEach-Object DriverMs | Sort-Object)
if ($in.Count -eq 0) { continue }
$s.buckets += [pscustomobject]@{ bucket = $b[0]; made = $in.Count; driver_s = [math]::Round((($in | Measure-Object -Sum).Sum) / 1000, 1); p50_s = [math]::Round((Get-Rank $in 0.5) / 1000, 2); p95_s = [math]::Round((Get-Rank $in 0.95) / 1000, 2) }
}
[pscustomobject]$s
}

# One `xcl shaders` run with the given environment; wall and CPU time, peak private commit.
function Invoke-Xcl([string[]]$Arguments, [hashtable]$Environment, [string]$Exe = $Xcl) {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = ($Arguments | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
foreach ($k in $Environment.Keys) { $psi.EnvironmentVariables[$k] = [string]$Environment[$k] }
$p = [System.Diagnostics.Process]::Start($psi)
$stdout = $p.StandardOutput.ReadToEndAsync(); $stderr = $p.StandardError.ReadToEndAsync()
$watch = [Diagnostics.Stopwatch]::StartNew(); $peak = 0L
while (-not $p.WaitForExit(1000)) {
try { $p.Refresh(); $peak = [math]::Max($peak, $p.PrivateMemorySize64) } catch { }
if ($watch.Elapsed.TotalMinutes -gt $TimeoutMinutes) { $p.Kill(); throw "xcl ran over $TimeoutMinutes minutes" }
}
$p.WaitForExit()
[pscustomobject]@{ Exit = $p.ExitCode; WallS = [math]::Round($watch.Elapsed.TotalSeconds, 1); CpuS = [math]::Round($p.TotalProcessorTime.TotalSeconds, 1); PeakMB = [math]::Round($peak / 1MB); Out = $stdout.Result + $stderr.Result }
}

$common = @('shaders', $Shaders, '--precompile', '--only', 'cs')
if ($Limit -gt 0) { $common += @('--limit', "$Limit") }

Write-Host "DXIL pass (not measured) into $dxil"
$prep = Invoke-Xcl $common @{ XCL_DXIL_CACHE = $dxil }
if ($prep.Exit -ne 0) { throw "the DXIL pass failed ($($prep.Exit)):`n$($prep.Out)" }

# The next pass replaces timing files. Their old summary no longer describes this run.
$summaryPath = Join-Path $Out 'summary.csv'
if (Test-Path -LiteralPath $summaryPath -PathType Leaf) { Remove-Item -LiteralPath $summaryPath }
$results = @()
foreach ($n in $Threads) {
$times = Join-Path $Out "times-$n.csv"
if (Test-Path -LiteralPath $times -PathType Leaf) { Remove-Item -LiteralPath $times }
$vars = @{ XCL_DXIL_CACHE = $dxil; XCL_PSO_DISK_CACHE = '0'; XCL_PIPELINE_THREADS = "$n"; XCL_PIPELINE_TIMES = $times }
if ($ClearNvCache) {
$nv = Join-Path $env:LOCALAPPDATA 'NVIDIA\DXCache'
if (Test-Path $nv) { Get-ChildItem $nv -Force | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue }
} else {
$vars.XCL_PIPELINE_CACHE_OFF = '1'
}
Write-Host "threads $n ..."
# next to -Xcl, so that it finds the same DXC and Agility SDK folders
$exe = Join-Path (Split-Path $Xcl -Parent) ('{0}-cold-{1}-{2}{3}' -f [IO.Path]::GetFileNameWithoutExtension($Xcl), $n, ([guid]::NewGuid().ToString('N').Substring(0, 8)), [IO.Path]::GetExtension($Xcl))
Copy-Item -LiteralPath $Xcl -Destination $exe
try { $run = Invoke-Xcl ($common + '--pipelines') $vars $exe } finally { Remove-Item -LiteralPath $exe -Force -ErrorAction SilentlyContinue }
if ($run.Exit -ne 0) { throw "threads ${n}: xcl failed ($($run.Exit)):`n$($run.Out)" }
$s = Get-Summary (Read-Times $times)
$results += [pscustomobject]@{ threads = $n; wall_s = $run.WallS; cpu_s = $run.CpuS; peak_commit_mb = $run.PeakMB; made = $s.made; refused = $s.refused; reused = $s.reused; driver_s = $s.driver_s; p50_s = $s.p50_s; p95_s = $s.p95_s; max_s = $s.max_s; buckets = $s.buckets }
}

$cache = if ($ClearNvCache) { 'NVIDIA DXCache folder emptied before each run' } else { 'implicit D3D and driver caches disabled (XCL_PIPELINE_CACHE_OFF)' }
"cold compute pipelines: $Shaders$(if ($Limit) { ", first $Limit records" }); $cache; XCL driver blobs off"
'| threads | wall s | CPU s | peak commit MB | made | refused | driver s (sum) | p50 s | p95 s | max s |'
'|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|'
foreach ($r in $results) { "| $($r.threads) | $($r.wall_s) | $($r.cpu_s) | $($r.peak_commit_mb) | $($r.made) | $($r.refused) | $($r.driver_s) | $($r.p50_s) | $($r.p95_s) | $($r.max_s) |" }
''
'| threads | DXIL size | made | driver s (sum) | p50 s | p95 s |'
'|---:|---|---:|---:|---:|---:|'
foreach ($r in $results) { foreach ($b in $r.buckets) { "| $($r.threads) | $($b.bucket) | $($b.made) | $($b.driver_s) | $($b.p50_s) | $($b.p95_s) |" } }
$results | Select-Object threads, wall_s, cpu_s, peak_commit_mb, made, refused, reused, driver_s, p50_s, p95_s, max_s | Export-Csv -NoTypeInformation -LiteralPath $summaryPath
Loading
Loading