diff --git a/README.md b/README.md index bdb207620f..e1201b1307 100644 --- a/README.md +++ b/README.md @@ -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 -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. diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 68ee303327..c013dcb723 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -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) -> Result<(), MeasureError> { - use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; use MeasureError::{Failed, Unavailable}; @@ -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::().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(); @@ -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=`: 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 @@ -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 }) } } @@ -1262,6 +1286,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 { @@ -1269,6 +1294,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 @@ -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::(&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::(); @@ -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, @@ -1331,7 +1367,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; } } @@ -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] diff --git a/scripts/cold-pso-bench.ps1 b/scripts/cold-pso-bench.ps1 new file mode 100644 index 0000000000..5beb51040b --- /dev/null +++ b/scripts/cold-pso-bench.ps1 @@ -0,0 +1,156 @@ +# 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). +# 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 diff --git a/scripts/cold-pso-bench.tests.ps1 b/scripts/cold-pso-bench.tests.ps1 new file mode 100644 index 0000000000..8a6c124aef --- /dev/null +++ b/scripts/cold-pso-bench.tests.ps1 @@ -0,0 +1,235 @@ +# 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 +$fixtureRoot = (Resolve-Path -LiteralPath $fixture).ProviderPath +$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' +if (-not $fixtureRoot.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { throw "fixture outside temporary directory: $fixtureRoot" } +$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_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 1 shaders D:\\pack --precompile --only cs --limit 10 --pipelines$") { throw "threads ${n}: exe name, environment 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' } + # 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 + $cachePath = (Resolve-Path -LiteralPath $cache).ProviderPath + if (-not $cachePath.StartsWith($fixtureRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "cache outside fixture: $cachePath" } + & $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 +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' } + + # An exit-zero process may still leave missing or corrupt timings. Keep every case's + # result so a baseline run reports the whole matrix, not only its first failure. + $source = Join-Path $fixture 'fixture-times.csv' + [IO.File]::WriteAllText($xcl, (@( + '@echo off' + 'if not defined XCL_PIPELINE_TIMES exit /b 0' + 'if exist "%~dp0fixture-times.csv" type "%~dp0fixture-times.csv" >> "%XCL_PIPELINE_TIMES%"' + 'exit /b 0' + ) -join "`r`n") + "`r`n") + $good = '0000000000000001,1,made,0,0' + $cases = @( + @{ Name = 'missing'; Data = $null; Error = 'is missing' } + @{ Name = 'empty'; Data = ''; Error = 'has no measurement rows' } + @{ Name = 'blank-only'; Data = " `r`n`t`r`n"; Error = 'has no measurement rows' } + ) + $badRows = @( + @{ Name = 'truncated'; Row = '0000000000000001,1,made,0' } + @{ Name = 'extra-field'; Row = '0000000000000001,1,made,0,0,extra' } + @{ Name = 'hash-short'; Row = '1,1,made,0,0' } + @{ Name = 'hash-long'; Row = '00000000000000001,1,made,0,0' } + @{ Name = 'hash-nonhex'; Row = '000000000000000g,1,made,0,0' } + @{ Name = 'unknown-outcome'; Row = '0000000000000001,1,unknown,0,0' } + ) + foreach ($value in @('', 'bogus', '1.5', '1e3', '9223372036854775808', '0', '-1')) { + $badRows += @{ Name = "bytes-$value"; Row = "0000000000000001,$value,made,0,0" } + } + foreach ($field in @('wait', 'driver')) { + foreach ($value in @('', 'bogus', '-0.5', 'NaN', 'Infinity', '-Infinity', '1e309')) { + $row = if ($field -eq 'wait') { "0000000000000001,1,made,$value,0" } else { "0000000000000001,1,made,0,$value" } + $badRows += @{ Name = "$field-$value"; Row = $row } + } + } + foreach ($bad in $badRows) { + $cases += @{ Name = $bad.Name; Data = "$good`r`n`r`n$($bad.Row)`r`n"; Line = 3 } + } + foreach ($outcome in @('made', 'refused', 'reused')) { + $cases += @{ Name = "valid-$outcome-zero"; Data = "0000000000000001,1,$outcome,0,0`r`n"; Counts = @([int]($outcome -eq 'made'), [int]($outcome -eq 'refused'), [int]($outcome -eq 'reused')) } + } + $cases += @{ Name = 'valid-blank-lines'; Data = "`r`n$good`r`n `r`n0000000000000002,2,refused,0,0`r`n0000000000000003,3,reused,0,0`r`n"; Counts = @(1, 1, 1) } + $cases += @{ Name = 'valid-negative-zero'; Data = "0000000000000001,1,made,-0.0,-0.0`r`n"; Counts = @(1, 0, 0) } + $cases += @{ Name = 'valid-[literal]-path'; Data = "$good`r`n"; Counts = @(1, 0, 0) } + # XCL appends: reusing an output directory must remove its previous timings first. + $cases += @{ Name = 'valid-literal-path-rerun'; OutName = 'valid-[literal]-path'; Data = "$good`r`n"; Counts = @(1, 0, 0) } + $cases += @{ Name = 'invalid-after-valid'; OutName = 'valid-[literal]-path'; Data = "bad row`r`n"; Line = 1 } + $cases += @{ Name = 'valid-after-invalid'; OutName = 'valid-[literal]-path'; Data = "$good`r`n"; Counts = @(1, 0, 0) } + $failures = New-Object 'System.Collections.Generic.List[string]' + $passed = 0 + foreach ($case in $cases) { + if ($null -eq $case.Data) { Remove-Item -LiteralPath $source -ErrorAction SilentlyContinue } + else { [IO.File]::WriteAllText($source, $case.Data) } + $outName = if ($case.ContainsKey('OutName')) { $case.OutName } else { $case.Name } + $caseOut = Join-Path $fixture ('case-' + $outName) + $summary = Join-Path $caseOut 'summary.csv' + $timing = Join-Path $caseOut 'times-1.csv' + $errorText = $null + try { & $bench -Shaders 'D:\pack' -Threads 1 -Xcl $xcl -Out $caseOut *> $null } + catch { $errorText = $_.Exception.Message } + $problems = New-Object 'System.Collections.Generic.List[string]' + if ($case.ContainsKey('Counts')) { + if ($errorText) { $problems.Add("unexpected error: $errorText") } + elseif (-not (Test-Path -LiteralPath $summary)) { $problems.Add('no summary.csv') } + else { + $rows = @(Import-Csv -LiteralPath $summary) + if ($rows.Count -ne 1) { $problems.Add("expected one summary row, got $($rows.Count)") } + else { + $counts = @([int]$rows[0].made, [int]$rows[0].refused, [int]$rows[0].reused) -join ',' + if ($counts -ne ($case.Counts -join ',')) { $problems.Add("wrong outcome counts: $counts") } + foreach ($metric in @('driver_s', 'p50_s', 'p95_s', 'max_s')) { + if ([double]$rows[0].$metric -ne 0) { $problems.Add("$metric should be zero") } + } + } + } + } else { + if (-not $errorText) { $problems.Add('invalid timing file accepted') } + else { + $prefix = [regex]::Escape("timing file '$timing'") + $expected = if ($case.ContainsKey('Line')) { "^${prefix}, line $($case.Line): .+" } else { "^$prefix $($case.Error)$" } + if ($errorText -notmatch $expected) { $problems.Add("wrong diagnostic: $errorText") } + } + if (Test-Path -LiteralPath $summary) { $problems.Add('published summary.csv for invalid timings') } + } + $copies = @(Get-ChildItem -LiteralPath $fixture -Filter 'xcl-cold-*') + if ($copies.Count) { $problems.Add("exe copies left: $($copies.Name -join ', ')") } + if ($problems.Count) { + $failure = "$($case.Name): $($problems -join '; ')" + $failures.Add($failure) + Write-Host "FAIL $failure" + } else { $passed++; Write-Host "PASS $($case.Name)" } + } + Write-Host "timing validation: $passed passed, $($failures.Count) failed, $($cases.Count) cases" + if ($failures.Count) { throw "$($failures.Count) timing validation cases failed" } + # A failed preparation has not replaced any timings; keep the previous complete result. + $previousSummary = [Convert]::ToBase64String([IO.File]::ReadAllBytes($summary)) + $previousTiming = [Convert]::ToBase64String([IO.File]::ReadAllBytes($timing)) + [IO.File]::WriteAllText($xcl, "@echo off`r`nexit /b 7`r`n") + $prepFailed = $false + try { & $bench -Shaders 'D:\pack' -Threads 1 -Xcl $xcl -Out $caseOut *> $null } + catch { $prepFailed = $_.Exception.Message -match '^the DXIL pass failed \(7\):' } + if (-not $prepFailed) { throw 'failed preparation was not reported' } + if ([Convert]::ToBase64String([IO.File]::ReadAllBytes($summary)) -ne $previousSummary -or + [Convert]::ToBase64String([IO.File]::ReadAllBytes($timing)) -ne $previousTiming) { + throw 'failed preparation changed the previous summary or timings' + } + 'failed preparation preserves previous results: ok' + # Undeletable but readable timings must not be reused, or even start a measurement. + $started = Join-Path $fixture 'measurement-started.txt' + [IO.File]::WriteAllText($xcl, (@( + '@echo off' + 'if not defined XCL_PIPELINE_TIMES exit /b 0' + '> "%~dp0measurement-started.txt" echo started' + 'if exist "%~dp0fixture-times.csv" type "%~dp0fixture-times.csv" >> "%XCL_PIPELINE_TIMES%"' + 'exit /b 0' + ) -join "`r`n") + "`r`n") + $oldTiming = "0000000000000001,1,made,0,1500`r`n" + $newTiming = "0000000000000002,2,made,0,2000`r`n" + foreach ($blocker in @('locked', 'read-only')) { + Remove-Item -LiteralPath $source, $started -ErrorAction SilentlyContinue + [IO.File]::WriteAllText($timing, $oldTiming) + [IO.File]::WriteAllBytes($summary, [Convert]::FromBase64String($previousSummary)) + $oldBytes = [Convert]::ToBase64String([IO.File]::ReadAllBytes($timing)) + $attributes = [IO.File]::GetAttributes($timing) + $reader = $null + $problems = New-Object 'System.Collections.Generic.List[string]' + try { + if ($blocker -eq 'locked') { $reader = [IO.File]::Open($timing, 'Open', 'Read', 'Read') } + else { [IO.File]::SetAttributes($timing, $attributes -bor [IO.FileAttributes]::ReadOnly) } + $failed = $false + try { & $bench -Shaders 'D:\pack' -Threads 1 -Xcl $xcl -Out $caseOut *> $null } + catch { $failed = $true } + if (-not $failed) { $problems.Add('undeletable timing file accepted') } + if (Test-Path -LiteralPath $summary) { $problems.Add('published summary.csv from old timings') } + if (Test-Path -LiteralPath $started) { $problems.Add('measurement started before old timings were removed') } + if ([Convert]::ToBase64String([IO.File]::ReadAllBytes($timing)) -ne $oldBytes) { $problems.Add('old timings changed') } + } finally { + if ($reader) { $reader.Dispose() } + [IO.File]::SetAttributes($timing, $attributes) + } + # Releasing the file allows a retry, with only this run's different, non-zero row. + Remove-Item -LiteralPath $started -ErrorAction SilentlyContinue + [IO.File]::WriteAllText($source, $newTiming) + & $bench -Shaders 'D:\pack' -Threads 1 -Xcl $xcl -Out $caseOut *> $null + $rows = @(Import-Csv -LiteralPath $summary) + if (-not (Test-Path -LiteralPath $started) -or $rows.Count -ne 1 -or + [int]$rows[0].made -ne 1 -or [double]$rows[0].driver_s -ne 2 -or + [Convert]::ToBase64String([IO.File]::ReadAllBytes($timing)) -ne [Convert]::ToBase64String([IO.File]::ReadAllBytes($source))) { + $problems.Add('retry did not publish only fresh timings') + } + if ($problems.Count) { + $failure = "${blocker} timings: $($problems -join '; ')" + $failures.Add($failure) + Write-Host "FAIL $failure" + } else { Write-Host "PASS $blocker timings and retry" } + } + if ($failures.Count) { throw "$($failures.Count) timing replacement cases failed" } + 'cold-pso-bench.ps1: ok' +} finally { + $env:LOCALAPPDATA = $savedAppData + $env:XCL_PIPELINE_TIMES = $savedTimes + $env:XCL_PIPELINE_CACHE_OFF = $savedCacheOff + $cleanup = (Resolve-Path -LiteralPath $fixture).ProviderPath + if ($cleanup -ne $fixtureRoot -or -not $cleanup.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase)) { throw "cleanup outside fixture: $cleanup" } + Remove-Item -LiteralPath $cleanup -Recurse -Force -ErrorAction SilentlyContinue +}