Skip to content
Open
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
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
122 changes: 122 additions & 0 deletions scripts/cold-pso-bench.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# 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).
# 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,
[int[]]$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
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 $Path)) { return @() }
Get-Content $Path | Where-Object { $_ } | ForEach-Object {
$f = $_.Split(',')
[pscustomobject]@{ Hash = $f[0]; Bytes = [long]$f[1]; Outcome = $f[2]; WaitMs = [double]$f[3]; DriverMs = [double]$f[4] }
}
}

$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) {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Xcl
$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)" }

$results = @()
foreach ($n in $Threads) {
$times = Join-Path $Out "times-$n.csv"
Remove-Item $times -ErrorAction SilentlyContinue
$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 ..."
$run = Invoke-Xcl ($common + '--pipelines') $vars
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 -Path (Join-Path $Out 'summary.csv')
42 changes: 42 additions & 0 deletions scripts/cold-pso-bench.tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Run with powershell.exe or pwsh.exe. Checks cold-pso-bench.ps1 against a fixture xcl.exe: the
# environment each run gets (driver blobs and implicit caches off, the thread count, its own
# times file), and the table it makes from XCL_PIPELINE_TIMES rows.
$ErrorActionPreference = 'Stop'
$bench = Join-Path $PSScriptRoot 'cold-pso-bench.ps1'
$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-cold-pso-' + [guid]::NewGuid())
$null = New-Item -ItemType Directory -Path $fixture
try {
$xcl = Join-Path $fixture 'xcl.cmd'
# A pipelines run (XCL_PIPELINE_TIMES set) writes four builds and the environment it saw.
[IO.File]::WriteAllText($xcl, (@(
'@echo off'
'if not defined XCL_PIPELINE_TIMES exit /b 0'
'>> "%XCL_PIPELINE_TIMES%" echo 0000000000000001,1000,made,1.0,100.0'
'>> "%XCL_PIPELINE_TIMES%" echo 0000000000000002,100000,made,0.5,300.0'
'>> "%XCL_PIPELINE_TIMES%" echo 0000000000000003,2000000,made,0.0,5000.0'
'>> "%XCL_PIPELINE_TIMES%" echo 0000000000000004,500,refused,0.0,1.0'
'>> "%~dp0env-%XCL_PIPELINE_THREADS%.txt" echo %XCL_PSO_DISK_CACHE% %XCL_PIPELINE_CACHE_OFF% %*'
'exit /b 0'
) -join "`r`n") + "`r`n")
$out = Join-Path $fixture 'out'
$table = (& $bench -Shaders 'D:\pack' -Threads 4, 8 -Limit 10 -Xcl $xcl -Out $out) -join "`n"

foreach ($n in 4, 8) {
$seen = (Get-Content (Join-Path $fixture "env-$n.txt") -Raw).Trim()
if ($seen -notmatch '^0 1 shaders D:\\pack --precompile --only cs --limit 10 --pipelines$') { throw "threads ${n}: environment or arguments wrong: $seen" }
# made: 0.1 + 0.3 + 5.0 s; p50 of three is the second, p95 and max the third
if ($table -notmatch "\| $n \| [\d.]+ \| [\d.]+ \| \d+ \| 3 \| 1 \| 5\.4 \| 0\.3 \| 5 \| 5 \|") { throw "threads ${n}: summary row wrong:`n$table" }
foreach ($row in @("\| $n \| < 64 KiB \| 1 \| 0\.1 \|", "\| $n \| 64-256 KiB \| 1 \| 0\.3 \|", "\| $n \| 1-4 MiB \| 1 \| 5 \|")) {
if ($table -notmatch $row) { throw "threads ${n}: bucket row missing ($row):`n$table" }
}
}
if (-not (Test-Path (Join-Path $out 'summary.csv'))) { throw 'no summary.csv' }

# -ClearNvCache replaces the implicit-cache switch
& $bench -Shaders 'D:\pack' -Threads 6 -Xcl $xcl -Out (Join-Path $fixture 'out2') -ClearNvCache *> $null
$seen = (Get-Content (Join-Path $fixture 'env-6.txt') -Raw).Trim()
if ($seen -notmatch '^0 +shaders D:\\pack --precompile --only cs --pipelines$') { throw "-ClearNvCache: caches switch still set: $seen" }
'cold-pso-bench.ps1: ok'
} finally {
Remove-Item -Recurse -Force $fixture -ErrorAction SilentlyContinue
}
Loading