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
62 changes: 56 additions & 6 deletions crates/xcl/src/shaders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1124,7 +1124,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 @@ -1136,10 +1135,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 @@ -1221,6 +1217,26 @@ struct Pipelines {
max_dxil: usize,
#[cfg(test)]
cache_dir: Option<PathBuf>,
/// `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 @@ -1421,6 +1437,14 @@ 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);
// `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()),
Expand All @@ -1434,6 +1458,7 @@ impl Pipelines {
running: (Mutex::new(0), std::sync::Condvar::new()),
most,
max_dxil,
times,
#[cfg(test)]
cache_dir: None,
})
Expand Down Expand Up @@ -1526,13 +1551,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 @@ -1554,12 +1582,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 @@ -1574,6 +1606,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(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 @@ -1595,7 +1632,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 @@ -2070,6 +2107,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
173 changes: 173 additions & 0 deletions scripts/cold-pso-bench.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# 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).
# The 8 MiB cap of --pipelines is off (XCL_PIPELINE_MAX_KB=0): a capped program writes no timing
# line, so the summary would leave out the biggest ones without saying so.
# 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 $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
}

# Windows retains PeakPagefileUsage (peak private commit) on the process handle after exit.
if (-not ('XclColdPso.MemoryCounters' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace XclColdPso {
public static class MemoryCounters {
[StructLayout(LayoutKind.Sequential)]
private struct Counters {
public uint Size, PageFaultCount;
public UIntPtr PeakWorkingSet, WorkingSet, PeakPagedPool, PagedPool;
public UIntPtr PeakNonPagedPool, NonPagedPool, PagefileUsage, PeakPagefileUsage;
}

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool K32GetProcessMemoryInfo(SafeProcessHandle process, ref Counters counters, uint size);

public static ulong PeakCommit(SafeProcessHandle process) {
var counters = new Counters();
counters.Size = (uint)Marshal.SizeOf(typeof(Counters));
if (!K32GetProcessMemoryInfo(process, ref counters, counters.Size))
throw new Win32Exception(Marshal.GetLastWin32Error());
return counters.PeakPagefileUsage.ToUInt64();
}
}
}
'@
}

# 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] }
$watch = [Diagnostics.Stopwatch]::StartNew()
$p = [System.Diagnostics.Process]::Start($psi)
try {
$stdout = $p.StandardOutput.ReadToEndAsync(); $stderr = $p.StandardError.ReadToEndAsync()
while (-not $p.WaitForExit(1000)) {
if ($watch.Elapsed.TotalMinutes -gt $TimeoutMinutes) { $p.Kill(); throw "xcl ran over $TimeoutMinutes minutes" }
}
$p.WaitForExit()
$wall = $p.ExitTime.ToUniversalTime() - $p.StartTime.ToUniversalTime()
$peak = [XclColdPso.MemoryCounters]::PeakCommit($p.SafeHandle)
[pscustomobject]@{ Exit = $p.ExitCode; WallS = [math]::Round($wall.TotalSeconds, 1); CpuS = [math]::Round($p.TotalProcessorTime.TotalSeconds, 1); PeakMB = [math]::Round($peak / 1MB); Out = $stdout.Result + $stderr.Result }
} finally {
$p.Dispose()
}
}

$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_MAX_KB = '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 }
# set, not left out: the run would otherwise inherit the caller's XCL_PIPELINE_CACHE_OFF=1
$vars.XCL_PIPELINE_CACHE_OFF = '0'
} 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 -Path (Join-Path $Out 'summary.csv')
Loading
Loading