From 30a3ef1055ed5da9d04a6ca667996112756486c1 Mon Sep 17 00:00:00 2001 From: Sebastian Kondratowicz Date: Wed, 25 Nov 2026 23:20:05 +0100 Subject: [PATCH] Scripts: cold driver benchmark of compute pipelines over thread counts (#2088) pass at 4 to 24 workers. scripts/cold-pso-bench.ps1 fills a DXIL cache once (DXC, not timed), then makes every compute pipeline of the same input again for each thread count with XCL's driver blobs off and either the implicit D3D and driver shader caches off (XCL_PIPELINE_CACHE_OFF=1, Developer Mode) or the NVIDIA DXCache folder emptied (-ClearNvCache), and tabulates wall and CPU time, peak commit, summed driver time and p50/p95/max per pipeline, also per DXIL size bucket. xcl shaders --pipelines gets the two switches it needs: - XCL_PIPELINE_TIMES=: one CSV line per pipeline (DXIL hash and bytes, made/reused/refused, slot wait and time in CreateComputePipelineState); - XCL_PIPELINE_CACHE_OFF=1: the pass turns the implicit caches off through the helper --measure-pso already used (now shared), or refuses to run. On an RTX 4070 (617.14, i7-13700F), 67 compute programs (every 40th of a retail pack), cold: wall time 558 s at 4 threads, 430 s at 6 and 415-432 s from 8 to 24, CPU time ~2100-2400 s throughout, while summed driver time grew 2.6x and peak commit 5.5 -> 13.6 GB. The fixture test runs with its own LOCALAPPDATA and without inherited XCL_PIPELINE_TIMES / XCL_PIPELINE_CACHE_OFF, so -ClearNvCache never empties a real NVIDIA cache and no real timing file gets rows (found and fixed by itsSio in review). Every measured run starts a copy of the exe under a name of its own, next to the original, and removes it afterwards: the AMD driver keys its shader cache on the exe's file name, so with -ClearNvCache on AMD the second run of a sweep was served warm and reported as cold (found and measured on RDNA4 by bielfreedom in review). -Threads is read as text and split on commas: from cmd or bash, `powershell -File ... -Threads 4,8` passes one string "4,8", which an [int[]] parameter silently read as 48 threads; anything that is not a thread count is refused. Every measured run also turns off the 8 MiB DXIL cap of --pipelines (XCL_PIPELINE_MAX_KB=0): a capped program returns before writing its timing line, so the summary silently left out the biggest programs (found by bmjask in review). With -ClearNvCache the runs set XCL_PIPELINE_CACHE_OFF=0 rather than leaving it out, so a caller's =1 does not turn the switch back on; and wall time and peak commit come from the process itself (start and exit times, PeakPagefileUsage on its handle), since a child shorter than the one-second sampling showed 0 MB (both found by bmjask in review; the measurement change is RavenCurseBurg's). Co-Authored-By: itsSio <31954644+itsSio@users.noreply.github.com> Co-Authored-By: bielfreedom <341226708+bielfreedom@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Co-Authored-By: RavenCurseBurg <360931527+RavenCurseBurg@users.noreply.github.com> --- crates/xcl/src/shaders.rs | 62 +++++++++-- scripts/cold-pso-bench.ps1 | 173 +++++++++++++++++++++++++++++++ scripts/cold-pso-bench.tests.ps1 | 78 ++++++++++++++ 3 files changed, 307 insertions(+), 6 deletions(-) create mode 100644 scripts/cold-pso-bench.ps1 create mode 100644 scripts/cold-pso-bench.tests.ps1 diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..a1aa4fe268 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -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) -> Result<(), MeasureError> { - use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use MeasureError::{Failed, Unavailable}; @@ -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::().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(); @@ -1221,6 +1217,26 @@ struct Pipelines { max_dxil: usize, #[cfg(test)] cache_dir: Option, + /// `XCL_PIPELINE_TIMES=`: one `timing_line` per pipeline, for benchmarks of the driver + times: Option>, +} + +/// 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::().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 @@ -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()), @@ -1434,6 +1458,7 @@ impl Pipelines { running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil, + times, #[cfg(test)] cache_dir: None, }) @@ -1526,6 +1551,7 @@ 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 { @@ -1533,6 +1559,8 @@ impl Pipelines { } *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 @@ -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::(&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::(); @@ -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, @@ -1595,7 +1632,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, 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; } } @@ -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] diff --git a/scripts/cold-pso-bench.ps1 b/scripts/cold-pso-bench.ps1 new file mode 100644 index 0000000000..057897367b --- /dev/null +++ b/scripts/cold-pso-bench.ps1 @@ -0,0 +1,173 @@ +# Cold NVIDIA (or any) driver compile benchmark of compute pipelines, for #2088 workstream 6. +# +# .\scripts\cold-pso-bench.ps1 -Shaders [-Threads 4,8,12] +# [-Limit N] [-Xcl .\target\release\xcl.exe] [-Out ] [-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') diff --git a/scripts/cold-pso-bench.tests.ps1 b/scripts/cold-pso-bench.tests.ps1 new file mode 100644 index 0000000000..286b3b1604 --- /dev/null +++ b/scripts/cold-pso-bench.tests.ps1 @@ -0,0 +1,78 @@ +# 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, an exe name of its own that is removed afterwards), 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 +$savedAppData = $env:LOCALAPPDATA +$savedTimes = $env:XCL_PIPELINE_TIMES +$savedCacheOff = $env:XCL_PIPELINE_CACHE_OFF +try { + # The fixture must never clear the user's driver cache or append to a real timing file. + $env:LOCALAPPDATA = Join-Path $fixture 'local-appdata' + $cache = Join-Path $env:LOCALAPPDATA 'NVIDIA\DXCache' + $null = New-Item -ItemType Directory -Path $cache + $sentinel = Join-Path $cache 'sentinel' + [IO.File]::WriteAllText($sentinel, 'temporary fixture cache') + Remove-Item Env:XCL_PIPELINE_TIMES, Env:XCL_PIPELINE_CACHE_OFF -ErrorAction SilentlyContinue + $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 %~n0 %XCL_PSO_DISK_CACHE% %XCL_PIPELINE_MAX_KB% %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" + + $names = @() + foreach ($n in 4, 8) { + $seen = (Get-Content (Join-Path $fixture "env-$n.txt") -Raw).Trim() + if ($seen -notmatch "^xcl-cold-$n-[0-9a-f]{8} 0 0 1 shaders D:\\pack --precompile --only cs --limit 10 --pipelines$") { throw "threads ${n}: exe name, environment (cache, 8 MiB cap off, cache switch) or arguments wrong: $seen" } + $names += ($seen -split ' ')[0] + # 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' } + foreach ($row in (Import-Csv -LiteralPath (Join-Path $out 'summary.csv'))) { + if ([long]$row.peak_commit_mb -le 0) { throw "no peak commit for short child at $($row.threads) threads" } + } + # a new exe name for each run (the AMD driver's cache key), none left behind + if ($names[0] -eq $names[1]) { throw "two runs used one exe name: $($names[0])" } + $left = @(Get-ChildItem $fixture -Filter 'xcl-cold-*') + if ($left.Count) { throw "exe copies left: $($left.Name -join ', ')" } + + # from cmd or bash (`-File`) "3,5" arrives as one string: two runs, not one of 35 threads + $shell = (Get-Process -Id $PID).Path + $null = & $shell -NoProfile -ExecutionPolicy Bypass -File $bench -Shaders 'D:\pack' -Threads '3,5' -Xcl $xcl -Out (Join-Path $fixture 'out3') + if ($LASTEXITCODE) { throw "-File -Threads 3,5 failed ($LASTEXITCODE)" } + if (-not ((Test-Path (Join-Path $fixture 'env-3.txt')) -and (Test-Path (Join-Path $fixture 'env-5.txt')))) { throw '-File -Threads 3,5 did not run 3 and 5 threads' } + if (Test-Path (Join-Path $fixture 'env-35.txt')) { throw '-File -Threads 3,5 ran 35 threads' } + $refused = $false + try { & $bench -Shaders 'D:\pack' -Threads '4,x' -Xcl $xcl -Out (Join-Path $fixture 'out4') *> $null } catch { $refused = $_.Exception.Message -match "-Threads: 'x'" } + if (-not $refused) { throw '-Threads 4,x was not refused' } + + # -ClearNvCache replaces the implicit-cache switch, also when the caller has it set + $env:XCL_PIPELINE_CACHE_OFF = '1' + & $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 '^xcl-cold-6-[0-9a-f]{8} 0 0 0 shaders D:\\pack --precompile --only cs --pipelines$') { throw "-ClearNvCache: caches switch still set: $seen" } + if (Test-Path -LiteralPath $sentinel) { throw '-ClearNvCache: temporary cache was not cleared' } + if ($env:XCL_PIPELINE_CACHE_OFF -ne '1') { throw "-ClearNvCache changed the caller's XCL_PIPELINE_CACHE_OFF" } + 'cold-pso-bench.ps1: ok' +} finally { + $env:LOCALAPPDATA = $savedAppData + $env:XCL_PIPELINE_TIMES = $savedTimes + $env:XCL_PIPELINE_CACHE_OFF = $savedCacheOff + Remove-Item -Recurse -Force $fixture -ErrorAction SilentlyContinue +}