diff --git a/docs/game_gate.md b/docs/game_gate.md index 4bb6c372da..ce42c9611d 100644 --- a/docs/game_gate.md +++ b/docs/game_gate.md @@ -91,8 +91,9 @@ A crash after the stop request is a warning, except a device loss or a panic, wh ## Not in this version -- A driver for the menus and a fixed route (a Lua mod). -- An ABBA runner over several runs. +- A fixed route from a saved place. The driver mod (`mods/gate_driver`, docs/lua-modding.md) gets through the menus + and walks a loop from wherever control comes. The ABBA runner over gate runs is `scripts/game-abba.ps1` + (docs/measuring_fps.md, section 3). - A time series beside the summary (memory, census, reaping queue). - A "memory rising" warning. - VRAM and RAM peaks. diff --git a/docs/measuring_fps.md b/docs/measuring_fps.md index c12087226e..6bb5eea0b9 100644 --- a/docs/measuring_fps.md +++ b/docs/measuring_fps.md @@ -67,6 +67,13 @@ A change of code, or a switch that cannot be turned in play, needs separate runs reads the runs in that order (logs, or the game gate's run folders with their `summary.json`): one value a run (its world median frame time), neighbouring pairs, the effect with its standard error and 95 % interval from at least 4 balanced pairs, and "B faster" or "B slower" only when the interval leaves 0 out and all pairs but one agree. +- `scripts/game-abba.ps1` does all of it in game: the gate runs in that order, for one exe with two settings + (`-Data`, `-MoreA`, `-MoreB`) or two builds (`-CheckoutA`, `-DataA`, `-CheckoutB`, `-DataB`: a data folder each, their + caches differ), then `abba` into `\comparison.txt`. It leaves out a measured run whose gate failed, whose + pipeline cache was not warm before the measured window, whose exe is not its arm's, or whose `-MoreA`/`-MoreB` + settings do not show in the runtime's settings line, and runs that slot again (`-Retry`, 1). `-DryRun` prints the + plan and the gate commands. Set both arms' switch explicitly (`LEONIDA_X=0` against `LEONIDA_X=1`): only what an + arm sets is checked. At 4 pairs and 300 s in the world it is 11 or 12 runs, about an hour. ## 4. Which number means what diff --git a/scripts/game-abba.ps1 b/scripts/game-abba.ps1 new file mode 100644 index 0000000000..d0e3c7640e --- /dev/null +++ b/scripts/game-abba.ps1 @@ -0,0 +1,130 @@ +#Requires -Version 7.0 +# An ABBA comparison of the D3D12 runtime in game (docs/measuring_fps.md, section 3): gate runs +# (scripts\game-gate.ps1) in a balanced order, then tools\d3d12_ab_compare.py over the measured ones. +# +# One exe, two settings (this checkout's exe, one data folder): +# pwsh -NoProfile -File scripts\game-abba.ps1 -Game -DataTemplate -Out -Data -MoreA 'LEONIDA_X=0' -MoreB 'LEONIDA_X=1' +# Two builds (each arm runs its own checkout's gate and exe, with a data folder of its own: their caches differ): +# pwsh -NoProfile -File scripts\game-abba.ps1 -Game -DataTemplate -Out -CheckoutA -DataA -CheckoutB -DataB +# +# The order comes from `d3d12_ab_compare.py plan`: warm-up runs of each arm, discarded runs, then -Pairs pairs in +# ABBA order. Each measured run is checked with `d3d12_ab_compare.py check`: its gate passed, the pipeline cache was +# warm before the measured window, its exe is the one its arm started with, and its arm's own -MoreA/-MoreB settings +# show in the runtime's settings line when the runtime writes one. A run that fails a check gets an ab-excluded.txt +# (the comparison leaves it out) and its slot runs again, -Retry times (1). Runs go to \runs; gets +# abba.json (what ran, what was left out and why), comparison.txt and comparison.json. +# Options: -Pairs (4), -WorldSeconds (300), -MaxMinutes (45), -More (both arms), -PlayArgs, -Python, -DryRun (prints +# the plan and every gate command, starts nothing). Two arms at 4 pairs and 300 s are 11 or 12 runs: about an hour. +param( + [string]$Game = '', + [string]$DataTemplate = '', + [string]$Out = '', + [string]$Data = '', + [string]$DataA = '', + [string]$DataB = '', + [string]$CheckoutA = '', + [string]$CheckoutB = '', + [string]$MoreA = '', + [string]$MoreB = '', + [string]$More = '', + [int]$Pairs = 4, + [int]$WorldSeconds = 300, + [int]$MaxMinutes = 45, + [string]$PlayArgs = '', + [int]$Retry = 1, + [string]$Python = '', + [switch]$DryRun +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$compare = Join-Path $repo 'tools\d3d12_ab_compare.py' +if (-not $Python) { $Python = (Get-Command python -ErrorAction Stop).Source } +$pwsh = (Get-Process -Id $PID).Path + +foreach ($need in 'Game', 'DataTemplate', 'Out') { + if (-not (Get-Variable $need -ValueOnly)) { throw "-$need is needed" } +} +if (-not $CheckoutA) { $CheckoutA = $repo } +if (-not $CheckoutB) { $CheckoutB = $repo } +$CheckoutA = (Resolve-Path $CheckoutA).Path +$CheckoutB = (Resolve-Path $CheckoutB).Path +$builds = $CheckoutA -ne $CheckoutB +if ($builds) { + if (-not $DataA -or -not $DataB) { throw 'two builds need -DataA and -DataB: their caches differ' } + if ([IO.Path]::GetFullPath($DataA) -eq [IO.Path]::GetFullPath($DataB)) { + throw '-DataA and -DataB are one folder: two builds would share their caches' + } +} else { + if (-not $Data) { throw 'one exe with two settings needs -Data' } + if (-not $MoreA -and -not $MoreB) { throw 'one exe and neither -MoreA nor -MoreB: the arms would be the same' } + $DataA = $Data + $DataB = $Data +} +if ($Pairs -lt 2) { throw '-Pairs is 2 or more (4 for a verdict from pairs)' } +$Out = [IO.Path]::GetFullPath($Out) +foreach ($checkout in $CheckoutA, $CheckoutB) { + if (($Out + '\').StartsWith($checkout + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "-Out is inside a checkout: $Out" } +} +$root = Join-Path $Out 'runs' + +$planArgs = @('-I', $compare, 'plan', '--pairs', $Pairs, '--json') +if (-not $builds) { $planArgs += '--switch' } +$order = (& $Python @planArgs | Out-String) | ConvertFrom-Json +if ($LASTEXITCODE) { throw 'd3d12_ab_compare.py plan failed' } +$slots = @($order.warm_up_and_discarded | ForEach-Object { [pscustomobject]@{ Kind = ($_ -split ' ')[0]; Arm = ($_ -split ' ')[-1] } }) + + @($order.measured | ForEach-Object { [pscustomobject]@{ Kind = 'measured'; Arm = $_ } }) +"mode: $(if ($builds) { 'two builds' } else { 'one exe, two settings' }); $($slots.Count) runs, $Pairs pairs" + +$record = [ordered]@{ schema = 'leonida-abba-run/1'; builds = $builds; pairs = $Pairs; world_seconds = $WorldSeconds; runs = @() } +$exes = @{} +$measured = @() +$index = 0 +foreach ($slot in $slots) { + $index++ + $own = if ($slot.Arm -eq 'A') { $MoreA } else { $MoreB } + $settings = (@($More, $own) | Where-Object { $_ }) -join ';' + $gate = Join-Path $(if ($slot.Arm -eq 'A') { $CheckoutA } else { $CheckoutB }) 'scripts\game-gate.ps1' + $armData = if ($slot.Arm -eq 'A') { $DataA } else { $DataB } + for ($attempt = 0; $attempt -le $Retry; $attempt++) { + $label = '{0:00}-{1}-{2}' -f $index, $slot.Kind, $slot.Arm + if ($attempt) { $label += "-retry$attempt" } + $dir = Join-Path $root $label + $gateArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $gate, 'run', '-Game', $Game, '-Data', $armData, + '-DataTemplate', $DataTemplate, '-Name', $label, '-RunRoot', $root, '-RunDir', $dir, '-WorldSeconds', $WorldSeconds, + '-MaxMinutes', $MaxMinutes, '-More', $settings, '-PlayArgs', $PlayArgs, '-Python', $Python) + if ($DryRun) { + "$index $($slot.Kind) $($slot.Arm): $gate run -Name $label -Data $armData -More '$settings'" + if ($slot.Kind -eq 'measured') { $measured += "$($slot.Arm):$dir" } + break + } + "run $index/$($slots.Count) $($slot.Kind) $($slot.Arm)$(if ($attempt) { ", again" })..." + & $pwsh @gateArgs | Out-Host + $runFile = Join-Path $dir 'run.json' + if (-not (Test-Path $runFile)) { throw "the gate did not start $label (exit $LASTEXITCODE)" } + $exe = (Get-Content $runFile -Raw | ConvertFrom-Json).exe_sha16 + if (-not $exes.ContainsKey($slot.Arm)) { $exes[$slot.Arm] = $exe } + $checkArgs = @('-I', $compare, 'check', $dir, '--exe', $exes[$slot.Arm]) + foreach ($item in ($own -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ })) { $checkArgs += @('--setting', $item) } + $seen = (& $Python @checkArgs | Out-String) | ConvertFrom-Json + $why = if ($slot.Kind -eq 'measured') { $seen.excluded } else { $null } + $record.runs += [ordered]@{ position = $index; kind = $slot.Kind; arm = $slot.Arm; folder = $label; exe = $exe; left_out = $why } + if ($why) { + Set-Content (Join-Path $dir 'ab-excluded.txt') $why -Encoding utf8 + " left out: $why" + if ($attempt -lt $Retry) { continue } + } + if ($slot.Kind -eq 'measured') { $measured += "$($slot.Arm):$dir" } + break + } +} + +if ($DryRun) { + "then: $Python -I $compare abba $($measured -join ' ')" + exit 0 +} +New-Item -ItemType Directory -Force $Out | Out-Null +$record | ConvertTo-Json -Depth 5 | Set-Content (Join-Path $Out 'abba.json') -Encoding utf8 +$text = & $Python -I $compare abba @measured | Out-String +& $Python -I $compare abba @measured --json | Out-String | Set-Content (Join-Path $Out 'comparison.json') -Encoding utf8 +Set-Content (Join-Path $Out 'comparison.txt') $text -Encoding utf8 +$text diff --git a/tests/test_d3d12_ab_compare.py b/tests/test_d3d12_ab_compare.py index d6fc750cfe..5ec4d74e42 100644 --- a/tests/test_d3d12_ab_compare.py +++ b/tests/test_d3d12_ab_compare.py @@ -106,6 +106,47 @@ def test_a_gate_folder_gives_its_world_median_and_a_failed_gate_is_left_out(self self.assertAlmostEqual(ab.run_value(self.gate("ok", 25.0))[0], 40.0) self.assertEqual(ab.run_value(self.gate("bad", 25.0, "FAIL"))[2], "gate FAIL") + def summary_run(self, name, result="PASS", warm=80.0, exe="1" * 16, settings=None): + """A gate run folder with its world at 80 s.""" + d = os.path.join(self.dir, name) + os.makedirs(d) + with open(os.path.join(d, "summary.json"), "w", encoding="utf-8") as f: + json.dump({"run": {"exe_sha16": exe}, "verdict": {"result": result}, "settings": settings or {}, + "times": {"world_at_s": 80.0, "warm_at_s": warm}, "fps": {"median": 25.0}}, f) + return d + + def test_check_keeps_a_good_run_and_gives_its_exe(self): + d = self.summary_run("ok", settings={"LEONIDA_X": "1", "LEONIDA_P": ""}) + self.assertEqual(ab.check_run(d, exe="1" * 16, settings=("LEONIDA_X=1", "LEONIDA_P=F:\\x")), (None, "1" * 16)) + + def test_check_leaves_out_what_does_not_measure_the_arm(self): + why = { + "gate FAIL": ab.check_run(self.summary_run("fail", result="FAIL")), + "the pipeline cache was never warm": ab.check_run(self.summary_run("cold", warm=None)), + "pipelines were made in the measured window": ab.check_run(self.summary_run("late", warm=150.0)), + "another exe than its arm's first run": ab.check_run(self.summary_run("exe", exe="2" * 16), exe="1" * 16), + "LEONIDA_X shows another value": ab.check_run(self.summary_run("off", settings={"LEONIDA_X": "0"}), + settings=("LEONIDA_X=1",)), + "LEONIDA_X is not in the settings line": ab.check_run(self.summary_run("gone", settings={"LEONIDA_Y": "1"}), + settings=("LEONIDA_X=1",)), + } + for expected, (got, _exe) in why.items(): + self.assertEqual(got, expected) + # A runtime without the settings line: nothing to check the setting against. + self.assertIsNone(ab.check_run(self.summary_run("old"), settings=("LEONIDA_X=1",))[0]) + + def test_check_prints_json(self): + out = io.StringIO() + with redirect_stdout(out): + self.assertEqual(ab.main(["check", self.summary_run("cli", warm=None), "--exe", "1" * 16]), 0) + self.assertEqual(json.loads(out.getvalue()), {"excluded": "the pipeline cache was never warm", "exe": "1" * 16}) + + def test_a_run_the_runner_left_out_is_left_out(self): + d = self.gate("excluded", 25.0) + with open(os.path.join(d, ab.EXCLUDED), "w", encoding="utf-8") as f: + f.write("the pipeline cache was never warm\n") + self.assertEqual(ab.run_value(d), (None, None, "excluded: the pipeline cache was never warm")) + def test_a_log_gives_the_median_of_its_world_lines(self): menus = self.log("menus.log", [60.0] * 5, 13) world = self.log("world.log", [20.0, 25.0, 25.0], 4000) diff --git a/tests/test_game_abba.py b/tests/test_game_abba.py new file mode 100644 index 0000000000..983d76e4b1 --- /dev/null +++ b/tests/test_game_abba.py @@ -0,0 +1,107 @@ +"""scripts/game-abba.ps1: its plan and gate commands (-DryRun, no game), its refusals, and a PowerShell name trap.""" +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +SCRIPT = os.path.join(ROOT, "scripts", "game-abba.ps1") +PWSH = shutil.which("pwsh") + + +class Script(unittest.TestCase): + def test_it_needs_powershell_7(self): + # Windows PowerShell 5.1 would fail on it without a clear word: it says so before running anything. + with open(SCRIPT, encoding="utf-8") as f: + self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") + + def test_no_variable_takes_a_parameters_name_in_another_case(self): + # PowerShell names ignore case: a variable `$out` would be the `[string]$Out` parameter. + with open(SCRIPT, encoding="utf-8") as f: + text = f.read() + block = text[text.index("param("):text.index("\n)\n")] + params = re.findall(r"\$(\w+)", block) + self.assertIn("Out", params) + for name in params: + others = {m for m in re.findall(r"\$(\w+)\b", text) if m.lower() == name.lower() and m != name} + self.assertFalse(others, f"${name} is also written {sorted(others)}") + + +@unittest.skipUnless(os.name == "nt" and PWSH, "needs Windows and pwsh") +class DryRun(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix="abba-test-", ignore_cleanup_errors=True) + self.addCleanup(self.tmp.cleanup) + self.dir = self.tmp.name + + def run_script(self, *args): + r = subprocess.run([PWSH, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", SCRIPT, "-Game", "G", + "-DataTemplate", "T", "-Out", os.path.join(self.dir, "out"), "-Python", sys.executable, + "-DryRun", *args], capture_output=True, text=True, timeout=120) + return r.returncode, r.stdout, r.stderr + + def slots(self, out): + return [re.match(r"(\d+) (\S+) ([AB]): (.*)$", line).groups() for line in out.splitlines() + if re.match(r"\d+ ", line)] + + def test_one_exe_two_settings(self): + code, out, err = self.run_script("-Data", os.path.join(self.dir, "data"), "-MoreA", "LEONIDA_X=0", + "-MoreB", "LEONIDA_X=1", "-More", "LEONIDA_Y=2", "-Pairs", "4") + self.assertEqual(code, 0, err) + self.assertIn("mode: one exe, two settings; 11 runs, 4 pairs", out) + slots = self.slots(out) + self.assertEqual([(k, a) for _, k, a, _ in slots], + [("warm-up", "A"), ("warm-up", "B"), ("discarded", "A")] + + [("measured", a) for a in "ABBAABBA"]) + for _, _, arm, command in slots: + self.assertIn(f"-More 'LEONIDA_Y=2;LEONIDA_X={'0' if arm == 'A' else '1'}'", command) + then = [line for line in out.splitlines() if line.startswith("then: ")] + self.assertEqual(len(then), 1) + self.assertEqual(re.findall(r" ([AB]):", then[0]), list("ABBAABBA")) + + def test_two_builds_run_their_own_gate_and_data(self): + a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b") + os.makedirs(os.path.join(a, "scripts")) + os.makedirs(os.path.join(b, "scripts")) + code, out, err = self.run_script("-CheckoutA", a, "-DataA", os.path.join(self.dir, "da"), + "-CheckoutB", b, "-DataB", os.path.join(self.dir, "db"), "-Pairs", "2") + self.assertEqual(code, 0, err) + slots = self.slots(out) + self.assertEqual([(k, arm) for _, k, arm, _ in slots], + [("warm-up", "A"), ("warm-up", "B"), ("discarded", "B"), ("discarded", "A")] + + [("measured", arm) for arm in "ABBA"]) + for _, _, arm, command in slots: + checkout, data = (a, "da") if arm == "A" else (b, "db") + self.assertTrue(command.startswith(os.path.join(checkout, "scripts", "game-gate.ps1")), command) + self.assertIn(os.path.join(self.dir, data), command) + + def test_refusals(self): + same = os.path.join(self.dir, "d") + a, b = os.path.join(self.dir, "a"), os.path.join(self.dir, "b") + os.makedirs(a) + os.makedirs(b) + cases = { + "share their caches": ("-CheckoutA", a, "-CheckoutB", b, "-DataA", same, "-DataB", same), + "need -DataA and -DataB": ("-CheckoutA", a, "-CheckoutB", b), + "the arms would be the same": ("-Data", same), + "-Pairs is 2 or more": ("-Data", same, "-MoreB", "LEONIDA_X=1", "-Pairs", "1"), + } + for message, args in cases.items(): + code, _out, err = self.run_script(*args) + self.assertNotEqual(code, 0, message) + self.assertIn(message, err) + + def test_the_output_is_not_in_a_checkout(self): + r = subprocess.run([PWSH, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", SCRIPT, "-Game", "G", + "-DataTemplate", "T", "-Out", os.path.join(ROOT, "abba-out"), "-Data", "D", + "-MoreB", "LEONIDA_X=1", "-Python", sys.executable, "-DryRun"], + capture_output=True, text=True, timeout=120) + self.assertNotEqual(r.returncode, 0) + self.assertIn("-Out is inside a checkout", r.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/d3d12_ab_compare.py b/tools/d3d12_ab_compare.py index 84e45a27f2..394c9514d5 100644 --- a/tools/d3d12_ab_compare.py +++ b/tools/d3d12_ab_compare.py @@ -3,6 +3,7 @@ python -I tools/d3d12_ab_compare.py abba A: B: B: A: ... [--json] python -I tools/d3d12_ab_compare.py phases [--keep-draw-jumps] [--json] python -I tools/d3d12_ab_compare.py plan --pairs 4 [--switch] [--json] + python -I tools/d3d12_ab_compare.py check [--exe ] [--setting NAME=VALUE ...] `abba` compares separate runs given in the order they were run (docs/measuring_fps.md, section 3). A run is a folder of the game gate (its summary.json: the median of the presents' frame times in the world, and a run @@ -25,6 +26,11 @@ `plan` prints a balanced order: warm-up runs, a discarded run of the first measured side, then ABBA pairs. +`check` tells scripts/game-abba.ps1 whether a gate run counts, as JSON: its gate passed, the pipeline cache was +warm before the measured window (60 s in the world), the exe is its arm's (--exe), and each --setting shows in the +runtime's settings line when the run has one (a value it hid counts as shown). A run folder with an +ab-excluded.txt (written by the runner) is left out of `abba`, its first line being why. + Standard library only; reads files, never runs them; prints no log line, path or argument text. """ @@ -45,6 +51,10 @@ T95 = [12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.160, 2.145, 2.131, 2.120, 2.110, 2.101, 2.093, 2.086, 2.080, 2.074, 2.069, 2.064, 2.060, 2.056, 2.052, 2.048, 2.045, 2.042] WORLD_DRAWS = 1000 +# The gate's measured window starts 60 s into the world (tools/game_gate.py AFTER_WORLD_S). +AFTER_WORLD_S = 60.0 +# Written by scripts/game-abba.ps1 in a run folder it leaves out. +EXCLUDED = "ab-excluded.txt" PHASE = re.compile(r"A/B phase (\d+) bits (\d+) on \[[^\]]*\]: (\d+) frames, mean ([\d.]+) ms, median ([\d.]+), " r"p90 ([\d.]+), ([\d.]+) draws a frame") COUNTERS = re.compile(r"A/B counters phase (\d+) bits (\d+): (.*)$") @@ -113,6 +123,9 @@ def trend_fit(runs): def run_value(path): """(frame ms, draws a frame, why left out or None) of one run.""" summary = os.path.join(path, "summary.json") if os.path.isdir(path) else None + if summary and os.path.exists(os.path.join(path, EXCLUDED)): + with open(os.path.join(path, EXCLUDED), encoding="utf-8") as f: + return None, None, "excluded: " + (f.readline().strip() or "no reason given") if summary: if not os.path.exists(summary): return None, None, "no summary" @@ -222,6 +235,36 @@ def phase_effects(phases, keep_jumps=False): return {"switches": out} +def check_run(path, exe=None, settings=()): + """(why a gate run is left out or None, its exe hash), for scripts/game-abba.ps1.""" + summary = os.path.join(path, "summary.json") + if not os.path.exists(summary): + return "no summary", None + with open(summary, encoding="utf-8") as f: + s = json.load(f) + run_exe = (s.get("run") or {}).get("exe_sha16") + result = (s.get("verdict") or {}).get("result") + if result != "PASS": + return f"gate {result or 'unknown'}", run_exe + times = s.get("times") or {} + world, warm = times.get("world_at_s"), times.get("warm_at_s") + if warm is None: + return "the pipeline cache was never warm", run_exe + if world is not None and warm > world + AFTER_WORLD_S: + return "pipelines were made in the measured window", run_exe + if exe and run_exe != exe: + return "another exe than its arm's first run", run_exe + shown = s.get("settings") or {} + for item in settings if shown else (): + name, _, value = item.partition("=") + got = shown.get(name) + if got is None: + return f"{name} is not in the settings line", run_exe + if not got.startswith("