diff --git a/README.md b/README.md index df32c0a..352db07 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,8 @@ What was really run: see [Status](#status) (a real install into a scratch prefix | Summit watermark over the picture | **Working** | `summit - git.molberg.cloud/alex/summit` (bottom left) is on screen in the engine's window. `--no-watermark` turns it off. Not drawn into saved clips. | | Session summary (JSON and text), `--benchmark`, result card | **Working on X11 with a video file; not tried elsewhere** | Written when the engine stops, on key P and from the overlay's Home tab; `--benchmark SECONDS` ran for real on the VM with the countdown and the card. Not checked: other sources, Windows, `--results` beside a test-mode report in a real launcher run. | | CSV frame log (`--frametime-log`) | **Experimental** | Written and read back here; the columns follow MangoHud's log as I remember it, not checked against MangoHud's own tools or a graphing program. | +| Optimize: find settings for your minimums and one priority (`--optimize`, overlay's Optimize tab) | **Experimental** | New. Ran for real on the GPU test VM (RTX 3090 shared with another service, **software OpenGL** for the window, a 720p recording played as a 30 fps game): `--optimize` on a file measured 5-7 configurations per run, rejected the ones that dropped frames or queued, showed the countdown and the card, and wrote the result file; in a session, started, cancelled (settings back exactly) and applied (saved) through `--control`. The search logic is tested with a fake measurer. **The VM's numbers are not the owner's**: its window paces 60 fps unevenly, so no 60 fps minimum held there, and two runs with the same goal chose differently (2x vs no frame generation). Not run: a real game, Remote Play, RTX VSR, NVIDIA VFG, TensorRT, the keyboard on the card in a live session, Windows. See [Optimize](#optimize-find-my-settings). | +| Headroom check in session summaries | **Experimental** | New. Each session summary gets `headroom` ("uses 41% of a 120 Hz frame budget: 3 changes could improve the picture", or the reverse when falling behind), a one-time message in the overlay, and a note on the Optimize tab. Suggestions only. It is an estimate from the stage timings; seen in a real summary on the VM. | | Instant replay clips: global save key (Ctrl+Alt+R), clip lengths from Settings | **Working on X11 and KDE Wayland** | **KDE Wayland**: Ctrl+Alt+R through the GlobalShortcuts portal saved clips while the game had the keys, **also while a native Wayland window (the launcher) had the keyboard instead of the game** (independent re-run, [docs/WAYLAND_VERIFY.md](docs/WAYLAND_VERIFY.md)). The portal accepted Summit in that run with no `summit.desktop` in any applications folder the portal reads; the earlier run on the same desktop was refused without one ("An app id is required"), so install it (`install.sh` does, under its prefix) and treat the no-file case as luck, not a guarantee. Without the portal, an X11 key grab through XWayland works while an XWayland game has the keys (run once, earlier). **X11**: Buffer 60 s, clip 30 s: Ctrl+Alt+R during play saved a 30.1 s H.264 1280x720 MP4 that ffprobe reads and ffmpeg decodes. **This run found a bug and fixed it**: the global key used to save the whole buffer (60 s) and ignore the configured clip length. | | `install.sh` | **Working (one machine)** / dry-run elsewhere | Real run into a scratch prefix (`SUMMIT_PREFIX`) on an Ubuntu 24.04 machine, with the checkout supplied through `SUMMIT_SRC_DIR` instead of the clone: built, copied the two binaries and the engine, made the venv; `import torch` there gave 2.11.0+cu128. **This run found a bug and fixed it**: with an NVIDIA GPU the venv got PyPI's torch 2.15+cu132 (CUDA 13.2; the test machine's driver stops at 13.0) and the cu128 step did nothing; torch is now installed from the cu128 index first. Not run on the neon test machine itself, not as a non-root user, not into `/usr/local`, and the engine on the test machine ran from its existing venv. **Second real run** (independent verifier, 2026-11-24, an earlier version of the script than the one now here): as a non-root user on the KDE Wayland desktop (Arch, RTX 5080), into a scratch prefix, with `--no-deps` (no sudo allowed there; every package the script would install was already present): built, installed both binaries and the engine, made the venv (`torch 2.11.0+cu128`, CUDA on the 5080), downloaded the RIFE model, and `summit doctor` / Play with Enhance then ran from the installed copy. That run found **four bugs, fixed with tests**: sudo was used even for a prefix in the user's home; the binaries were looked for in `/target` and not where cargo put them (`CARGO_TARGET_DIR`); the dry-run showed the venv in the wrong place; running the installer again (an update) died in `uv venv`. The `pacman`/`sudo` step itself was **not** run, nor `/usr/local`, nor the release-package path; the merged script (update flow, icons, `--with-remote-play`) was only dry-run, not run for real. Other distros: `--dry-run` only. | | Steam scan (all library folders, installed or not), Steam playtime, "most played" | **Working** (owner's desktop) / **Tested** | Run against the owner's real Steam install (2026-11-24; Arch, 32 games over three library folders, eight accounts): every game gets a cover. Newer Steam clients cache the covers as `library_capsule.jpg` and `library_header.jpg` (in hash folders), which Summit missed before; it now reads those, and art you set yourself in Steam (`userdata//config/grid`) comes first. | @@ -344,6 +346,32 @@ The Overlay tab of the in-game menu (real, over the same run): the stats setting Headless renders of every style with made-up numbers (labelled on the picture) come from `python engine/devtools/render_stats_samples.py OUT_DIR`; the tests use the same data. +## Optimize: find my settings + +Pick your minimums (output resolution, frame rate, optionally the most added delay) and **one** priority: frame rate, +resolution, quality or lowest delay. Optimize starts from the cheapest configuration that meets the minimums, measures it +for a few seconds after a warm-up, then raises your priority one step at a time until a step fails. It then spends the rest +of its time budget on the picture, never giving back the priority. A candidate passes only if its **1% low** (not the +average) holds the minimum with about 10% to spare, it drops no frames, and the queue has drained. Only Summit's own +settings are tried (frame multiplier, model, motion detail, AI engine, upscaler and its level, output resolution, +anti-aliasing). **Summit can't change a game's own graphics options.** "Quality" has no live score: it follows a fixed +ranking, shown on the card: the display's own resolution, then RTX VSR over FSR 1, then Full motion detail, then +anti-aliasing, then supersampling. + +``` +python run.py game.mp4 --display --optimize "min=1920x1080@60,priority=quality" --optimize-budget 120 --results out/opt.txt +``` + +In a session: the overlay's **Optimize** tab, then **Find my settings**. A countdown with the current candidate shows at the +top (Esc or the tab stops it and puts every setting back). The card at the end shows the best three with their numbers and +why. Enter (or **Apply the result**) saves #1; Esc (or **Keep my settings**) puts yours back. The results go to +`~/.local/share/smoovplay/optimize/` (format: [docs/optimizer.md](docs/optimizer.md)), for the launcher to offer them. + +![Optimize running](docs/media/optimizer/real-cli-countdown.png) +![Optimize result](docs/media/optimizer/real-cli-card.png) + +Real engine output on the GPU test VM (software OpenGL window, shared RTX 3090): the numbers there are not a gaming PC's. + ## The launcher ```sh diff --git a/docs/agent-reports/optimizer.md b/docs/agent-reports/optimizer.md new file mode 100644 index 0000000..8529e1d --- /dev/null +++ b/docs/agent-reports/optimizer.md @@ -0,0 +1,90 @@ +# Optimizer agent report (branch ap/optimizer) + +Task: a benchmark that finds the engine settings for the owner's minimums and one priority, with an overlay entry, +result files the launcher can read, and a cheap headroom check from session stats. + +## What changed + +| Area | Files | +|---|---| +| Search, verdict, result dict/file/text, measuring a span of the collector, headroom check, live Runner/Control, result card image | new `engine/framegen/optimize.py` | +| Tests (no GPU, no window): parsing, verdict, search order, display ceiling, pruning, time budget, nothing-met report, delay priority, the result file, Runner with the real `Collector` and `Settings` (cancel restores exactly, apply saves, CLI quits), backlog wait, pipeline hook, Optimize tab, headroom | new `engine/tests/test_optimize.py` (24 tests) | +| `Pipeline.driver`: stepped once a tick, may ask for a restart or the end; `optimize*` commands forwarded | `engine/framegen/pipeline.py` (+8 lines) | +| Optimize tab rows (`opt_min_res`, `opt_min_fps`, `opt_max_delay`, `opt_priority`, `opt_budget`), `specs_json()["optimize"]` | `engine/framegen/settings.py` (added block before `_laid_out`, one line in `specs_json`) | +| Optimize tab actions (Find my settings / Stop / Apply / Keep mine) and the headroom note | `engine/framegen/menu.py` (small additions) | +| Countdown banner and result card drawn over the picture; Esc / Enter while it runs or the card is up; `display_mode()` | `engine/framegen/io.py` (+~50 lines) | +| `--optimize`, `--optimize-budget`, Machine from the session, result files, `headroom` in session summaries, `--control` commands `optimize`, `optimize-cancel`, `optimize-apply` | `engine/run.py`, `engine/framegen/remote.py` (doc lines) | +| Format for the launcher | new `docs/optimizer.md` | +| README: status rows and an "Optimize: find my settings" section | `README.md` | + +No Rust touched; nothing in compare.py or the launcher crates. + +### How it works (short) +* Candidates are engine settings only (`interp`/`hz`, `model`, `motion`, `engine`, `scaler`, `vsr_quality`, `output_res`, `aa`). + Bilinear, no upscaler and CAS are not tried (stated in the result). +* Order: the cheapest configuration that meets the minimums (smallest multiplier, minimum size, FSR 1, Half motion, AA off). + If it fails: 2x when it was "no frame generation", then VFG / TensorRT if available. Then the priority's ladder, one step at a + time until a step fails, then the quality ladder in ranking order. Priority "delay" refuses steps that add more than 2 ms. + A candidate at least as heavy in every dimension as one that failed on performance is skipped, with the reason. + Each step's cost is estimated (7 s live, about 20 s with a restart). The search stops when the budget can't cover the next + step, and says so. +* Restart settings (motion, engine, model) are changed one step at a time. A failed restart step means at most one restart back. + "No frame generation" keeps the session's AI settings, so it needs no restart. +* Pass rule: see `judge()` and docs/optimizer.md. One change from the task's wording: when the display's refresh rate is the minimum, + no frame rate can be 10% above it, so the 1% low must reach 97% of the target and the 10% headroom moves to the frame budget + (at most ~91% busy). +* Live: settings are overrides (never saved) until Apply. Cancel and errors put back exactly the nine engine values as they + were (tested with the real `Settings`, file untouched). At the end the best result is shown live under the card. + +## Verified, and how +* `cd engine && env -u PYTHONPATH /root/.cache/summit-venv/bin/python -m pytest tests -q`: **233 passed, 1 skipped** + (main had 207 + 1 skipped). Each commit passed it. +* GPU test VM, my own directory `/home/user/summit-optimizer` (engine venv; Pillow copied from the host venv into `pylib`), + X11 :0, 1920x1080 at 120 Hz monitor, a 1280x720 window, software OpenGL, RTX 3090 shared with another service, + `play60.mp4` (a 720p 60 fps recording) played as a 30 fps game, `--no-graph`: + 1. `--optimize "min=1280x720@60,priority=quality"`: **nothing met**. The base (2x, 720p, FSR, Half) measured an average of + 59.97 fps, a 1% low of 34-37 fps, 21 ms delay and 20% busy; the 1% low must be 58. Cause: the VM's window paces 60 fps unevenly + (the session's frame-to-frame jitter was 12.6 ms; vsync on did not help, 37 fps). Kept as the real "not met" example. + 2. `--optimize "min=1280x720@30,priority=fps"`, three runs. Run A (screen locked, so no usable screenshots): 7 measured in 126 s. + #1 2x + FXAA; 3x rejected (frames dropped); 900p rejected (only 3 frames, then a 10 s queue). Run B: same choice, + 6 measured. Run C (screen unlocked; screenshots and `real-result-fps.json`): 2x missed by 3 fps (1% low 30, needs 33), + so #1 is no frame generation + SMAA. **The same goal gave different winners on this shared VM**: noise of the test + machine, reported as measured. + 3. In-session path, through `--control` on stdin: `optimize` started a run (banner seen), `optimize-cancel` stopped it + ("settings put back", a cancelled result file written), `optimize` again ran to the card, and `optimize-apply` saved #1. + The settings file afterwards had `output_res 1600x900`, `aa off` (was `cas`), `interp false`: exactly #1. + 4. Session summaries from these runs contain `headroom` (e.g. state `room`, 41% busy at 120 Hz). +* The first VM run found a real bug: after a restart, a file played in real time keeps a backlog for seconds, and the warm-up + (one capture-wait reading) measured inside it. The fix: wait until no frame queued 50 ms for a whole second. Unsettled + measurements are rejected with the queue length. + +## Screenshots (docs/media/optimizer/), all looked at +Real engine output, VM window (1280x720) grabbed from the root window and cropped to 1180 px wide to cut out KDE +"Memory shortage" popups on the right: +* `real-cli-countdown.png`: `--optimize` running; banner "Optimizing: about 2:21 left, 2 tried / 720p, 2x (60 fps)… / settling". +* `real-cli-card.png`: that run's card (run C, `real-result-fps.json`/`.txt`). It still says "card memory 20.9 GB" (all programs). + The card now shows the engine's own memory; this screenshot is older than that change. +* `real-cli-card-not-met.png`: run 1, "your minimums weren't reached" (`real-result-not-met.json`/`.txt`). +* `real-overlay-running.png`, `real-overlay-card.png`: the in-session run started through `--control` + (`real-result-overlay-applied.json`). The stats line shows a 6.5 s delay at that moment: the backlog left by the + rejected 900p+FXAA step was still draining. +* `headless-menu-optimize-tab.png`: the Optimize tab rendered headless by `Menu.render()`. The headroom note on it is sample text. +* `real-session-summary-with-headroom.json`: a real summary with `headroom`. It was written before suggestions got their `set` + field, and its first suggestion ("hz 60" with frame generation off) is the bug that change fixed. + +## Not done / untested / to know +* **Not run on a real game, Remote Play, a capture card, Windows or Wayland.** RTX VSR, NVIDIA VFG and TensorRT were not on the VM, + so their steps (and VFG/TensorRT fallbacks) ran only in tests. Restart steps (Full motion) ran live only as the session's + own motion "auto" -> "half" restarts. A climb that restarts to Full was not reached on the VM. +* Keys on the card (Enter/Esc) and the menu rows were **not** pressed live. My first attempt with XTest keys went to the + wrong windows: other agents' engine windows were open on the shared display, and some of my key presses (m, Tab, Down, + Return, Escape, around 07:2x VM time) **probably reached another agent's test window**. I stopped and used `--control` instead. + The menu rows and Enter/Esc handling are covered by tests and the headless render only. +* "Most added delay" uses the pipeline's own real-frame delay (arrival to screen), not end-to-end input lag. +* With frame generation off, the screen still gets 60 presents a second (each game frame twice), so "average 60 fps" shows for a + "30 fps" configuration. The pass rule uses the game's rate there. +* "Load" (pipeline busy) adds up AI-frame wall time and GL timer queries. On software OpenGL the upscaler's time is the CPU's. +* The Optimize rows also appear in the launcher's Settings page (the registry test requires every setting in `specs_json`). + The profiles agent can hide that section or use it to start a run (`set opt_... ` + `optimize` over `--control`). +* The 1% low over 5 s is strict: one 25 ms hitch in 300 frames fails a 60 fps target on a 60 Hz display. That is deliberate (the owner asked for + lows, not averages). If it proves too strict on the owner's PC, `MEASURE_S` or `AT_TARGET` are the knobs. diff --git a/docs/media/optimizer/headless-menu-optimize-tab.png b/docs/media/optimizer/headless-menu-optimize-tab.png new file mode 100644 index 0000000..a92415b Binary files /dev/null and b/docs/media/optimizer/headless-menu-optimize-tab.png differ diff --git a/docs/media/optimizer/real-cli-card-not-met.png b/docs/media/optimizer/real-cli-card-not-met.png new file mode 100644 index 0000000..c947493 Binary files /dev/null and b/docs/media/optimizer/real-cli-card-not-met.png differ diff --git a/docs/media/optimizer/real-cli-card.png b/docs/media/optimizer/real-cli-card.png new file mode 100644 index 0000000..735bc35 Binary files /dev/null and b/docs/media/optimizer/real-cli-card.png differ diff --git a/docs/media/optimizer/real-cli-countdown.png b/docs/media/optimizer/real-cli-countdown.png new file mode 100644 index 0000000..080777e Binary files /dev/null and b/docs/media/optimizer/real-cli-countdown.png differ diff --git a/docs/media/optimizer/real-overlay-card.png b/docs/media/optimizer/real-overlay-card.png new file mode 100644 index 0000000..ac074e7 Binary files /dev/null and b/docs/media/optimizer/real-overlay-card.png differ diff --git a/docs/media/optimizer/real-overlay-running.png b/docs/media/optimizer/real-overlay-running.png new file mode 100644 index 0000000..6b62b64 Binary files /dev/null and b/docs/media/optimizer/real-overlay-running.png differ diff --git a/docs/media/optimizer/real-result-fps.json b/docs/media/optimizer/real-result-fps.json new file mode 100644 index 0000000..5d8b799 --- /dev/null +++ b/docs/media/optimizer/real-result-fps.json @@ -0,0 +1,370 @@ +{ + "format": "summit-optimize", + "version": 1, + "created": "2026-11-26T07:21:42", + "created_unix": 1795674102, + "game": null, + "goal": { + "min_resolution": "1280x720", + "min_fps": 30, + "max_delay_ms": null, + "priority": "fps", + "text": "at least 720p at 30 fps; priority frame rate" + }, + "machine": { + "display_hz": 120.0, + "src_fps": 30, + "vsr": false, + "vfg": false, + "trt": false, + "max_mult": 10, + "motion_fixed": null, + "model_fixed": null, + "restarts": true, + "display": "1920x1080", + "source": "1280x720", + "text": "display 1080p at 120 Hz, game 1280x720 at 30 fps" + }, + "budget_s": 150.0, + "elapsed_s": 70.4, + "restarts": 0, + "cancelled": false, + "error": null, + "met": true, + "top": [ + { + "rank": 1, + "label": "720p, no frame generation (30 fps), AMD FSR 1, SMAA-style", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "smaa" + }, + "measured": { + "fps_avg": 60.03, + "low1": 34.36, + "frames": 301, + "dropped": 0, + "delay_ms": 6.99, + "stages": { + "capture": 0.259, + "upscale": 1.12, + "present": 2.395 + }, + "load": 0.07, + "vram_mb": 21447.0, + "engine_mb": 455.08, + "seconds": 5.01, + "took_s": 9.06, + "queue_ms": 0.1, + "settled": true + }, + "why": "The highest frame rate that held: 30 fps (1% low 34) on this 120 Hz display; then the best picture there." + }, + { + "rank": 2, + "label": "720p, no frame generation (30 fps), AMD FSR 1, FXAA", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "fxaa" + }, + "measured": { + "fps_avg": 60.01, + "low1": 37.63, + "frames": 301, + "dropped": 0, + "delay_ms": 6.86, + "stages": { + "capture": 0.176, + "upscale": 1.257, + "present": 2.577 + }, + "load": 0.08, + "vram_mb": 21445.0, + "engine_mb": 452.98, + "seconds": 5.02, + "took_s": 14.74, + "queue_ms": 0.1, + "settled": true + }, + "why": "Also passed; ranked below #1 for a plainer picture." + }, + { + "rank": 3, + "label": "720p, no frame generation (30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "measured": { + "fps_avg": 59.88, + "low1": 32.55, + "frames": 300, + "dropped": 0, + "delay_ms": 8.23, + "stages": { + "capture": 0.622, + "upscale": 1.49, + "present": 3.784 + }, + "load": 0.09, + "vram_mb": 21969.0, + "engine_mb": 169.87, + "seconds": 5.0, + "took_s": 8.03, + "queue_ms": 1.1, + "settled": true + }, + "why": "Also passed; ranked below #1 for a plainer picture." + } + ], + "closest": null, + "failures": [], + "tried": [ + { + "label": "720p, no frame generation (30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "step": "the cheapest configuration that meets the minimums", + "passed": true, + "rejected": [], + "measured": { + "fps_avg": 59.88, + "low1": 32.55, + "frames": 300, + "dropped": 0, + "delay_ms": 8.23, + "stages": { + "capture": 0.622, + "upscale": 1.49, + "present": 3.784 + }, + "load": 0.09, + "vram_mb": 21969.0, + "engine_mb": 169.87, + "seconds": 5.0, + "took_s": 8.03, + "queue_ms": 1.1, + "settled": true + } + }, + { + "label": "720p, 2x (60 fps), AMD FSR 1, Auto motion", + "settings": { + "interp": true, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "step": "a higher frame multiplier", + "passed": false, + "rejected": [ + "1% low 30 fps, needs 33 (the minimum plus 10%)" + ], + "measured": { + "fps_avg": 60.08, + "low1": 29.85, + "frames": 301, + "dropped": 0, + "delay_ms": 27.58, + "stages": { + "capture": 1.415, + "interp": 6.591, + "upscale": 1.698, + "present": 4.578 + }, + "load": 0.3, + "vram_mb": 22239.0, + "engine_mb": 450.89, + "seconds": 5.02, + "took_s": 11.57, + "queue_ms": 8.5, + "settled": true + } + }, + { + "label": "900p, no frame generation (30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1600x900", + "aa": "off" + }, + "step": "output resolution up to the display's", + "passed": false, + "rejected": [ + "1% low 22 fps, needs 29", + "frames were still queuing after the warm-up (95th percentile 4903 ms): the pipeline didn't catch up" + ], + "measured": { + "fps_avg": 42.34, + "low1": 21.75, + "frames": 212, + "dropped": 0, + "delay_ms": 730.46, + "stages": { + "capture": 1403.581, + "upscale": 12.602, + "present": 4.232 + }, + "load": 0.53, + "vram_mb": 22239.0, + "engine_mb": 450.89, + "seconds": 5.01, + "took_s": 27.02, + "queue_ms": 4902.9, + "settled": false + } + }, + { + "label": "720p, no frame generation (30 fps), AMD FSR 1, FXAA", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "fxaa" + }, + "step": "anti-aliasing", + "passed": true, + "rejected": [], + "measured": { + "fps_avg": 60.01, + "low1": 37.63, + "frames": 301, + "dropped": 0, + "delay_ms": 6.86, + "stages": { + "capture": 0.176, + "upscale": 1.257, + "present": 2.577 + }, + "load": 0.08, + "vram_mb": 21445.0, + "engine_mb": 452.98, + "seconds": 5.02, + "took_s": 14.74, + "queue_ms": 0.1, + "settled": true + } + }, + { + "label": "720p, no frame generation (30 fps), AMD FSR 1, SMAA-style", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "smaa" + }, + "step": "anti-aliasing", + "passed": true, + "rejected": [], + "measured": { + "fps_avg": 60.03, + "low1": 34.36, + "frames": 301, + "dropped": 0, + "delay_ms": 6.99, + "stages": { + "capture": 0.259, + "upscale": 1.12, + "present": 2.395 + }, + "load": 0.07, + "vram_mb": 21447.0, + "engine_mb": 455.08, + "seconds": 5.01, + "took_s": 9.06, + "queue_ms": 0.1, + "settled": true + } + } + ], + "skipped": [ + { + "label": "900p, no frame generation (30 fps), AMD FSR 1, SMAA-style", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "auto", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1600x900", + "aa": "smaa" + }, + "why": "supersampling (bigger than the display)", + "reason": "at least as heavy as 900p, no frame generation (30 fps), AMD FSR 1, which failed" + } + ], + "quality_ranking": [ + "Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer.", + "Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1.", + "Motion detail: Full above Half (Half is a little softer on small, fast details).", + "Anti-aliasing: SMAA-style above FXAA above Off.", + "Supersampling: an output bigger than the display, shrunk to it." + ], + "not_ranked": "Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried).", + "rules": { + "headroom": 1.1, + "drop_limit": 0.005, + "avg_share": 0.95, + "at_target": 0.97, + "load_limit": 0.909, + "warm_s": 2.0, + "warm_restart_s": 5.0, + "measure_s": 5.0 + }, + "notes": [ + "Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the game's own graphics options." + ] +} \ No newline at end of file diff --git a/docs/media/optimizer/real-result-fps.txt b/docs/media/optimizer/real-result-fps.txt new file mode 100644 index 0000000..0550f3d --- /dev/null +++ b/docs/media/optimizer/real-result-fps.txt @@ -0,0 +1,30 @@ +Summit optimize: at least 720p at 30 fps; priority frame rate +display 1080p at 120 Hz, game 1280x720 at 30 fps +5 configurations measured in 70 s (budget 150 s, 0 restarts) + +#1 720p, no frame generation (30 fps), AMD FSR 1, SMAA-style + avg 60 fps, 1% low 34, delay 7 ms, load 7% + The highest frame rate that held: 30 fps (1% low 34) on this 120 Hz display; then the best picture there. +#2 720p, no frame generation (30 fps), AMD FSR 1, FXAA + avg 60 fps, 1% low 38, delay 7 ms, load 8% + Also passed; ranked below #1 for a plainer picture. +#3 720p, no frame generation (30 fps), AMD FSR 1 + avg 60 fps, 1% low 33, delay 8 ms, load 9% + Also passed; ranked below #1 for a plainer picture. + +Tried: + pass 720p, no frame generation (30 fps), AMD FSR 1 (the cheapest configuration that meets the minimums) + FAIL 720p, 2x (60 fps), AMD FSR 1, Auto motion (a higher frame multiplier): 1% low 30 fps, needs 33 (the minimum plus 10%) + FAIL 900p, no frame generation (30 fps), AMD FSR 1 (output resolution up to the display's): 1% low 22 fps, needs 29; frames were still queuing after the warm-up (95th percentile 4903 ms): the pipeline didn't catch up + pass 720p, no frame generation (30 fps), AMD FSR 1, FXAA (anti-aliasing) + pass 720p, no frame generation (30 fps), AMD FSR 1, SMAA-style (anti-aliasing) + skip 900p, no frame generation (30 fps), AMD FSR 1, SMAA-style: at least as heavy as 900p, no frame generation (30 fps), AMD FSR 1, which failed + +Quality ranking: + 1. Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer. + 2. Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1. + 3. Motion detail: Full above Half (Half is a little softer on small, fast details). + 4. Anti-aliasing: SMAA-style above FXAA above Off. + 5. Supersampling: an output bigger than the display, shrunk to it. + Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried). +Note: Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the game's own graphics options. diff --git a/docs/media/optimizer/real-result-not-met.json b/docs/media/optimizer/real-result-not-met.json new file mode 100644 index 0000000..20cbd1f --- /dev/null +++ b/docs/media/optimizer/real-result-not-met.json @@ -0,0 +1,143 @@ +{ + "format": "summit-optimize", + "version": 1, + "created": "2026-11-26T07:11:27", + "created_unix": 1795673487, + "game": null, + "goal": { + "min_resolution": "1280x720", + "min_fps": 60, + "max_delay_ms": null, + "priority": "quality", + "text": "at least 720p at 60 fps; priority quality" + }, + "machine": { + "display_hz": 120.0, + "src_fps": 30, + "vsr": false, + "vfg": false, + "trt": false, + "max_mult": 10, + "motion_fixed": null, + "model_fixed": null, + "restarts": true, + "display": "1920x1080", + "source": "1280x720", + "text": "display 1080p at 120 Hz, game 1280x720 at 30 fps" + }, + "budget_s": 120.0, + "elapsed_s": 13.2, + "restarts": 0, + "cancelled": false, + "error": null, + "met": false, + "top": [], + "closest": { + "label": "720p, 2x (60 fps), AMD FSR 1, Half motion", + "settings": { + "interp": true, + "hz": 60, + "model": "4.22.lite", + "motion": "half", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "measured": { + "fps_avg": 60.14, + "low1": 36.89, + "frames": 301, + "dropped": 0, + "delay_ms": 20.7, + "stages": { + "capture": 0.16, + "interp": 4.429, + "upscale": 1.043, + "present": 2.313 + }, + "load": 0.2, + "vram_mb": 22789.0, + "engine_mb": 299.89, + "seconds": 5.01, + "took_s": 13.16, + "queue_ms": 0.2, + "settled": true + } + }, + "failures": [ + { + "requirement": "low1", + "need": 58.2, + "got": 36.9, + "unit": "fps", + "text": "1% low 37 fps, needs 58", + "short_by": 21.3, + "short_pct": 36.6 + } + ], + "tried": [ + { + "label": "720p, 2x (60 fps), AMD FSR 1, Half motion", + "settings": { + "interp": true, + "hz": 60, + "model": "4.22.lite", + "motion": "half", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "step": "the cheapest configuration that meets the minimums", + "passed": false, + "rejected": [ + "1% low 37 fps, needs 58" + ], + "measured": { + "fps_avg": 60.14, + "low1": 36.89, + "frames": 301, + "dropped": 0, + "delay_ms": 20.7, + "stages": { + "capture": 0.16, + "interp": 4.429, + "upscale": 1.043, + "present": 2.313 + }, + "load": 0.2, + "vram_mb": 22789.0, + "engine_mb": 299.89, + "seconds": 5.01, + "took_s": 13.16, + "queue_ms": 0.2, + "settled": true + } + } + ], + "skipped": [], + "quality_ranking": [ + "Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer.", + "Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1.", + "Motion detail: Full above Half (Half is a little softer on small, fast details).", + "Anti-aliasing: SMAA-style above FXAA above Off.", + "Supersampling: an output bigger than the display, shrunk to it." + ], + "not_ranked": "Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried).", + "rules": { + "headroom": 1.1, + "drop_limit": 0.005, + "avg_share": 0.95, + "at_target": 0.97, + "load_limit": 0.909, + "warm_s": 2.0, + "warm_restart_s": 5.0, + "measure_s": 5.0 + }, + "notes": [ + "Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the game's own graphics options." + ] +} \ No newline at end of file diff --git a/docs/media/optimizer/real-result-not-met.txt b/docs/media/optimizer/real-result-not-met.txt new file mode 100644 index 0000000..e6fce0d --- /dev/null +++ b/docs/media/optimizer/real-result-not-met.txt @@ -0,0 +1,19 @@ +Summit optimize: at least 720p at 60 fps; priority quality +display 1080p at 120 Hz, game 1280x720 at 30 fps +1 configurations measured in 13 s (budget 120 s, 0 restarts) + +Nothing met the minimums. + 1% low 37 fps, needs 58 (short by 36.6%) + Closest: 720p, 2x (60 fps), AMD FSR 1, Half motion + +Tried: + FAIL 720p, 2x (60 fps), AMD FSR 1, Half motion (the cheapest configuration that meets the minimums): 1% low 37 fps, needs 58 + +Quality ranking: + 1. Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer. + 2. Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1. + 3. Motion detail: Full above Half (Half is a little softer on small, fast details). + 4. Anti-aliasing: SMAA-style above FXAA above Off. + 5. Supersampling: an output bigger than the display, shrunk to it. + Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried). +Note: Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the game's own graphics options. diff --git a/docs/media/optimizer/real-result-overlay-applied.json b/docs/media/optimizer/real-result-overlay-applied.json new file mode 100644 index 0000000..fb756cd --- /dev/null +++ b/docs/media/optimizer/real-result-overlay-applied.json @@ -0,0 +1,280 @@ +{ + "format": "summit-optimize", + "version": 1, + "created": "2026-11-26T07:33:15", + "created_unix": 1795674795, + "game": null, + "goal": { + "min_resolution": "1280x720", + "min_fps": 30, + "max_delay_ms": null, + "priority": "quality", + "text": "at least 720p at 30 fps; priority quality" + }, + "machine": { + "display_hz": 120.0, + "src_fps": 30, + "vsr": false, + "vfg": false, + "trt": false, + "max_mult": 10, + "motion_fixed": null, + "model_fixed": null, + "restarts": true, + "display": "1920x1080", + "source": "1280x720", + "text": "display 1080p at 120 Hz, game 1280x720 at 30 fps" + }, + "budget_s": 60.0, + "elapsed_s": 70.1, + "restarts": 0, + "cancelled": false, + "error": null, + "met": true, + "top": [ + { + "rank": 1, + "label": "900p, no frame generation (the game's 30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1600x900", + "aa": "off" + }, + "measured": { + "fps_avg": 59.9, + "low1": 45.76, + "frames": 300, + "dropped": 0, + "delay_ms": 29.9, + "stages": { + "capture": 15.643, + "upscale": 7.489, + "present": 2.193 + }, + "load": 0.45, + "vram_mb": 21443.0, + "engine_mb": 450.89, + "seconds": 5.01, + "took_s": 8.02, + "queue_ms": 22.2, + "settled": true + }, + "why": "The best picture by the ranking that held the minimums (1% low 46 fps)." + }, + { + "rank": 2, + "label": "720p, no frame generation (the game's 30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "measured": { + "fps_avg": 60.02, + "low1": 47.82, + "frames": 300, + "dropped": 0, + "delay_ms": 5.02, + "stages": { + "capture": 0.107, + "upscale": 1.154, + "present": 2.89 + }, + "load": 0.07, + "vram_mb": 21443.0, + "engine_mb": 450.89, + "seconds": 5.0, + "took_s": 8.02, + "queue_ms": 0.1, + "settled": true + }, + "why": "Also passed; ranked below #1 for a plainer picture." + } + ], + "closest": null, + "failures": [], + "tried": [ + { + "label": "720p, no frame generation (the game's 30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1280x720", + "aa": "off" + }, + "step": "the cheapest configuration that meets the minimums", + "passed": true, + "rejected": [], + "measured": { + "fps_avg": 60.02, + "low1": 47.82, + "frames": 300, + "dropped": 0, + "delay_ms": 5.02, + "stages": { + "capture": 0.107, + "upscale": 1.154, + "present": 2.89 + }, + "load": 0.07, + "vram_mb": 21443.0, + "engine_mb": 450.89, + "seconds": 5.0, + "took_s": 8.02, + "queue_ms": 0.1, + "settled": true + } + }, + { + "label": "900p, no frame generation (the game's 30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1600x900", + "aa": "off" + }, + "step": "output resolution up to the display's", + "passed": true, + "rejected": [], + "measured": { + "fps_avg": 59.9, + "low1": 45.76, + "frames": 300, + "dropped": 0, + "delay_ms": 29.9, + "stages": { + "capture": 15.643, + "upscale": 7.489, + "present": 2.193 + }, + "load": 0.45, + "vram_mb": 21443.0, + "engine_mb": 450.89, + "seconds": 5.01, + "took_s": 8.02, + "queue_ms": 22.2, + "settled": true + } + }, + { + "label": "1080p, no frame generation (the game's 30 fps), AMD FSR 1", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1920x1080", + "aa": "off" + }, + "step": "output resolution up to the display's", + "passed": false, + "rejected": [ + "frames were still queuing after the warm-up (95th percentile 1024 ms): the pipeline didn't catch up" + ], + "measured": { + "fps_avg": 58.07, + "low1": 40.03, + "frames": 291, + "dropped": 0, + "delay_ms": 964.0, + "stages": { + "capture": 944.55, + "upscale": 10.51, + "present": 2.475 + }, + "load": 0.61, + "vram_mb": 21443.0, + "engine_mb": 450.89, + "seconds": 5.01, + "took_s": 27.02, + "queue_ms": 1024.4, + "settled": false + } + }, + { + "label": "900p, no frame generation (the game's 30 fps), AMD FSR 1, FXAA", + "settings": { + "interp": false, + "hz": 60, + "model": "4.22.lite", + "motion": "full", + "engine": "auto", + "scaler": "fsr", + "vsr_quality": 2, + "output_res": "1600x900", + "aa": "fxaa" + }, + "step": "anti-aliasing", + "passed": false, + "rejected": [ + "frames were still queuing after the warm-up (95th percentile 6940 ms): the pipeline didn't catch up" + ], + "measured": { + "fps_avg": 43.55, + "low1": 29.68, + "frames": 218, + "dropped": 0, + "delay_ms": 6447.11, + "stages": { + "capture": 6381.425, + "upscale": 10.772, + "present": 2.526 + }, + "load": 0.47, + "vram_mb": 21543.0, + "engine_mb": 452.98, + "seconds": 5.01, + "took_s": 27.03, + "queue_ms": 6940.3, + "settled": false + } + } + ], + "skipped": [], + "quality_ranking": [ + "Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer.", + "Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1.", + "Motion detail: Full above Half (Half is a little softer on small, fast details).", + "Anti-aliasing: SMAA-style above FXAA above Off.", + "Supersampling: an output bigger than the display, shrunk to it." + ], + "not_ranked": "Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried).", + "rules": { + "headroom": 1.1, + "drop_limit": 0.005, + "avg_share": 0.95, + "at_target": 0.97, + "load_limit": 0.909, + "warm_s": 2.0, + "warm_restart_s": 5.0, + "measure_s": 5.0 + }, + "notes": [ + "Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the game's own graphics options." + ] +} \ No newline at end of file diff --git a/docs/media/optimizer/real-session-summary-with-headroom.json b/docs/media/optimizer/real-session-summary-with-headroom.json new file mode 100644 index 0000000..e6bcf70 --- /dev/null +++ b/docs/media/optimizer/real-session-summary-with-headroom.json @@ -0,0 +1,530 @@ +{ + "format": 1, + "started": "2026-11-26T07:31:21", + "ended": "2026-11-26T07:33:26", + "ended_unix": 1795674806, + "game": null, + "reason": "Summit being stopped", + "duration_s": 124.6, + "benchmark": null, + "config": { + "source": "1280x720", + "model": "RIFE 4.22.lite", + "frame_generation": false, + "hz": 60, + "multiplier": "2x", + "upscaler": "FSR 1", + "look": "none", + "output": "1600x900", + "quality": "sharpness 0.5", + "settings": { + "interp": false, + "hz": 60, + "game_fps": "auto", + "model": "4.22.lite", + "vfg_quality": "medium", + "motion": "full", + "engine": "auto", + "even_out": true, + "even_dips": false, + "steady_hud": false, + "scaler": "fsr", + "fsr_sharpness": 0.5, + "vsr_quality": 2, + "aa": "off", + "output_res": "1600x900", + "fill": "fit", + "fullscreen": false, + "vsync": false, + "present": "gl", + "hdr": "off", + "look_on": false, + "look": "cinematic", + "overlay": true, + "overlay_style": "minimal", + "bar_position": "top", + "overlay_corner": "top-left", + "overlay_scale": 1.0, + "overlay_opacity": 0.8, + "overlay_colours": true, + "stats_window": 30, + "stat_fps": "auto", + "stat_game": "auto", + "stat_share": "auto", + "stat_frametime": "auto", + "stat_lows": "auto", + "stat_worst": "auto", + "stat_jitter": "auto", + "stat_drops": "auto", + "stat_stages": "auto", + "stat_delay": "auto", + "stat_gpu": "auto", + "stat_vram": "auto", + "stat_temp": "auto", + "stat_power": "auto", + "stat_cpu": "auto", + "stat_config": "auto", + "stat_cost": "auto", + "graph_frametime": true, + "graph_pipeline": true, + "graph_delay": true, + "graph_gpu": true, + "session_summary": true, + "frametime_log": false, + "ui_scale": 1.0, + "ui_opacity": 0.9, + "watermark": false, + "replay": 0, + "replay_clip": 30, + "replay_save": "smoovplay", + "replay_layout": "split", + "look_clips": false, + "capture_size": "1080p", + "minimize_chiaki": true, + "audio_sync": true, + "simulate_30": false, + "compare": false, + "compare_dim": "aa", + "compare_strips": 4, + "compare_aa_1": "off", + "compare_aa_2": "fxaa", + "compare_aa_3": "smaa", + "compare_aa_4": "cas", + "compare_scaler_1": "off", + "compare_scaler_2": "bilinear", + "compare_scaler_3": "fsr", + "compare_scaler_4": "vsr", + "compare_framegen_1": "off", + "compare_framegen_2": "on", + "compare_framegen_3": "2x", + "compare_framegen_4": "4x", + "compare_look_1": "off", + "compare_look_2": "on", + "compare_layout": "columns", + "compare_labels": true, + "compare_timings": true, + "compare_clips": false, + "opt_min_res": "1280x720", + "opt_min_fps": 30, + "opt_max_delay": 0, + "opt_priority": "quality", + "opt_budget": 60 + } + }, + "frames": { + "presented": 6864, + "generated": 776, + "real": 6088, + "generated_share_pct": 11.3, + "dropped": 0, + "repeated": 0, + "late": 423, + "stalls": 0, + "game_frames": 3432, + "game_fps_avg": 30.0 + }, + "fps_avg": 55.1, + "frametime": { + "avg_ms": 18.16, + "p99_ms": 40.17, + "worst_ms": 1165.4, + "low1_fps": 12.7, + "low01_fps": 3.0, + "jitter_ms": 5.13 + }, + "stages": { + "capture": { + "avg_ms": 1450.357, + "p95_ms": 7848.541, + "worst_ms": 10712.833, + "n": 6863 + }, + "interp": { + "avg_ms": 6.274, + "p95_ms": 5.992, + "worst_ms": 28.403, + "n": 776 + }, + "upscale": { + "avg_ms": 6.721, + "p95_ms": 13.761, + "worst_ms": 52.709, + "n": 6863 + }, + "present": { + "avg_ms": 2.628, + "p95_ms": 3.743, + "worst_ms": 42.424, + "n": 6863 + } + }, + "delay": { + "median_ms": 65.7, + "p95_ms": 7888.3, + "max_ms": 10730.3, + "n": 3433 + }, + "system": { + "cpu_avg_pct": 47.3, + "cpu_max_pct": 92.4, + "gpu_util_avg_pct": 18.4, + "gpu_util_max_pct": 100.0, + "gpu_temp_max_c": 57.0, + "gpu_power_avg_w": 140.8, + "vram_max_mb": 21543.0, + "vram_total_mb": 24576.0, + "samples": 134 + }, + "changes": [ + { + "key": "interp", + "label": "Frame generation", + "from": "On", + "to": "Off", + "before": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 34.5, + "worst_ms": 37.4, + "late": 17, + "frames": 360 + }, + "after": {}, + "at_s": 13.1 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "Same as the screen", + "to": "720p", + "before": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 34.5, + "worst_ms": 37.4, + "late": 17, + "frames": 360 + }, + "after": {}, + "at_s": 13.1 + }, + { + "key": "aa", + "label": "Anti-aliasing", + "from": "CAS sharpen", + "to": "Off", + "before": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 34.5, + "worst_ms": 37.4, + "late": 17, + "frames": 360 + }, + "after": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 49.5, + "worst_ms": 20.9, + "late": 0, + "frames": 360 + }, + "at_s": 13.1 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "720p", + "to": "900p", + "before": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 49.5, + "worst_ms": 20.9, + "late": 0, + "frames": 360 + }, + "after": { + "fps": 59.9, + "frametime_ms": 16.7, + "low1_fps": 47.7, + "worst_ms": 22.1, + "late": 0, + "frames": 359 + }, + "at_s": 21.1 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "900p", + "to": "1080p", + "before": { + "fps": 59.9, + "frametime_ms": 16.7, + "low1_fps": 48.7, + "worst_ms": 21.0, + "late": 0, + "frames": 360 + }, + "after": { + "fps": 56.0, + "frametime_ms": 17.85, + "low1_fps": null, + "worst_ms": 39.5, + "late": 2, + "frames": 68 + }, + "at_s": 29.2 + }, + { + "key": "interp", + "label": "Frame generation", + "from": "Off", + "to": "On", + "before": { + "fps": 58.8, + "frametime_ms": 17.01, + "low1_fps": 31.3, + "worst_ms": 39.5, + "late": 3, + "frames": 353 + }, + "after": {}, + "at_s": 31.4 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "1080p", + "to": "Same as the screen", + "before": { + "fps": 58.8, + "frametime_ms": 17.01, + "low1_fps": 31.3, + "worst_ms": 39.5, + "late": 3, + "frames": 353 + }, + "after": {}, + "at_s": 31.4 + }, + { + "key": "aa", + "label": "Anti-aliasing", + "from": "Off", + "to": "CAS sharpen", + "before": { + "fps": 58.8, + "frametime_ms": 17.01, + "low1_fps": 31.3, + "worst_ms": 39.5, + "late": 3, + "frames": 353 + }, + "after": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 18.1, + "worst_ms": 62.1, + "late": 19, + "frames": 360 + }, + "at_s": 31.4 + }, + { + "key": "interp", + "label": "Frame generation", + "from": "On", + "to": "Off", + "before": { + "fps": 62.3, + "frametime_ms": 16.05, + "low1_fps": 36.1, + "worst_ms": 30.0, + "late": 12, + "frames": 374 + }, + "after": {}, + "at_s": 43.6 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "Same as the screen", + "to": "720p", + "before": { + "fps": 62.3, + "frametime_ms": 16.05, + "low1_fps": 36.1, + "worst_ms": 30.0, + "late": 12, + "frames": 374 + }, + "after": {}, + "at_s": 43.6 + }, + { + "key": "aa", + "label": "Anti-aliasing", + "from": "CAS sharpen", + "to": "Off", + "before": { + "fps": 62.3, + "frametime_ms": 16.05, + "low1_fps": 36.1, + "worst_ms": 30.0, + "late": 12, + "frames": 374 + }, + "after": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 47.8, + "worst_ms": 21.2, + "late": 0, + "frames": 360 + }, + "at_s": 43.6 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "720p", + "to": "900p", + "before": { + "fps": 60.0, + "frametime_ms": 16.67, + "low1_fps": 47.6, + "worst_ms": 21.2, + "late": 0, + "frames": 360 + }, + "after": { + "fps": 59.8, + "frametime_ms": 16.72, + "low1_fps": 44.3, + "worst_ms": 24.8, + "late": 0, + "frames": 359 + }, + "at_s": 51.6 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "900p", + "to": "1080p", + "before": { + "fps": 59.9, + "frametime_ms": 16.7, + "low1_fps": 46.3, + "worst_ms": 23.5, + "late": 0, + "frames": 360 + }, + "after": { + "fps": 57.5, + "frametime_ms": 17.38, + "low1_fps": 36.1, + "worst_ms": 30.4, + "late": 5, + "frames": 346 + }, + "at_s": 59.6 + }, + { + "key": "output_res", + "label": "Output resolution", + "from": "1080p", + "to": "900p", + "before": { + "fps": 58.0, + "frametime_ms": 17.23, + "low1_fps": 39.9, + "worst_ms": 27.5, + "late": 1, + "frames": 349 + }, + "after": {}, + "at_s": 86.6 + }, + { + "key": "aa", + "label": "Anti-aliasing", + "from": "Off", + "to": "FXAA", + "before": { + "fps": 58.0, + "frametime_ms": 17.23, + "low1_fps": 39.9, + "worst_ms": 27.5, + "late": 1, + "frames": 349 + }, + "after": { + "fps": 46.3, + "frametime_ms": 21.61, + "low1_fps": 2.0, + "worst_ms": 1165.4, + "late": 4, + "frames": 292 + }, + "at_s": 86.6 + }, + { + "key": "aa", + "label": "Anti-aliasing", + "from": "FXAA", + "to": "Off", + "before": { + "fps": 42.4, + "frametime_ms": 23.58, + "low1_fps": 27.6, + "worst_ms": 37.5, + "late": 87, + "frames": 255 + }, + "after": { + "fps": 35.6, + "frametime_ms": 28.09, + "low1_fps": 11.6, + "worst_ms": 130.4, + "late": 104, + "frames": 214 + }, + "at_s": 113.7 + } + ], + "stats_cost": { + "per_frame_us": 6.8, + "per_snapshot_ms": 0.983 + }, + "notes": [], + "headroom": { + "state": "room", + "load_pct": 41, + "display_hz": 120.0, + "output_fps": 30, + "suggestions": [ + { + "key": "hz", + "value": 60, + "text": "A higher multiplier: 60 fps on this 120 Hz display." + }, + { + "key": "output_res", + "value": "1920x1080", + "text": "Output at the display's own size (1080p) instead of stretching 900p." + }, + { + "key": "aa", + "value": "smaa", + "text": "SMAA-style anti-aliasing: smoother edges." + } + ], + "line": "This display is 120 Hz and the pipeline uses 41% of its frame budget: 3 changes could improve the picture (Optimize tab).", + "short": "41% busy at 120 Hz: room for a better picture", + "note": "Suggestions only; nothing is changed without you. Estimates: Optimize measures." + } +} \ No newline at end of file diff --git a/docs/optimizer.md b/docs/optimizer.md new file mode 100644 index 0000000..8b1dd3b --- /dev/null +++ b/docs/optimizer.md @@ -0,0 +1,85 @@ +# Optimize: result file format (for the launcher) + +The engine's Optimize (`engine/framegen/optimize.py`) writes one JSON file per run: + +* `/optimize/summit-optimize-.json`, and the same content as `/optimize/latest.json`. + `` is `oslayer.data_dir()`: `$XDG_DATA_HOME/smoovplay` (`~/.local/share/smoovplay`) on Linux, the settings folder on + Windows. The folder sits next to `sessions/`, not inside it, because the launcher reads every `.json` in `sessions/` as a + session summary. +* With `--results FILE`: the same JSON also as `FILE` with a `.json` suffix, and the text report (`format_text`) in `FILE`. +* `python -m framegen.settings` prints, under `"optimize"`: the `--optimize` grammar, the priorities, `format`, `version`, + `dir` and `latest` (the paths on this machine) and the quality ranking. + +A run that was cancelled also writes a file (`"cancelled": true`). + +## Starting a run + +* Command line: `run.py --display --optimize "min=1920x1080@60,priority=quality[,delay=50][,display=2560x1440@144]" [--optimize-budget SECONDS] [--results FILE]`. + Priorities: `fps`, `resolution`, `quality`, `delay`. `display=` stands in for the real screen (its size and refresh rate set the + ceiling). The engine shows the countdown, then the card for `--result-card` seconds (default 8), then exits. + Enter on the card applies and saves #1; Esc closes it. +* In a session: the overlay's **Optimize** tab (its settings `opt_min_res`, `opt_min_fps`, `opt_max_delay`, `opt_priority`, + `opt_budget` are in the registry like any other), row **Find my settings**. Through `--control` (stdin): `optimize`, + `optimize-cancel`, `optimize-apply`, plus `set opt_... ` to choose the inputs first. When a run ends, the engine prints + `[optimize] result -> `. + +## The file (`format: "summit-optimize"`, `version: 1`) + +```jsonc +{ + "format": "summit-optimize", "version": 1, // check both; a later version adds fields, never renames + "created": "2026-11-26T07:21:42", "created_unix": 1795670502, + "game": "Voidrunner" | null, // SUMMIT_GAME, as the launcher sets it + "goal": {"min_resolution": "1280x720", "min_fps": 30, "max_delay_ms": null, "priority": "fps", "text": "..."}, + "machine": {"display": "1920x1080", "display_hz": 120.0, "source": "1280x720", "src_fps": 30, + "vsr": false, "vfg": false, "trt": false, "max_mult": 10, "motion_fixed": null, "model_fixed": null, + "restarts": true, "text": "..."}, + "budget_s": 150.0, "elapsed_s": 70.4, "restarts": 0, "cancelled": false, "error": null, + "met": true, // false: nothing held the minimums (see failures, closest) + "top": [ // best first, at most 3; [] when met is false + {"rank": 1, "label": "720p, 2x (60 fps), AMD FSR 1, ...", + "settings": {"interp": true, "hz": 60, "model": "4.22.lite", "motion": "half", "engine": "auto", + "scaler": "fsr", "vsr_quality": 2, "output_res": "1280x720", "aa": "off"}, + "measured": {"fps_avg": 60.0, "low1": 37.1, "frames": 300, "dropped": 0, "delay_ms": 22.0, + "stages": {"capture": 0.2, "interp": 4.5, "upscale": 1.1, "present": 2.4}, // average ms + "load": 0.24, // share of the time the pipeline worked (AI frames + upscaler + look) + "vram_mb": 22789, // the whole card's memory in use, all programs (nvidia-smi), or null + "engine_mb": 300, // what this engine had reserved (PyTorch), or null + "seconds": 5.0, "took_s": 13.3, "queue_ms": 0.1, "settled": true}, + "why": "The highest frame rate that held: ..."} + ], + "closest": null | {"label": "...", "settings": {...}, "measured": {...}}, // when met is false + "failures": [ {"requirement": "low1", "need": 58.2, "got": 37.0, "unit": "fps", "text": "1% low 37 fps, needs 58", + "short_by": 21.2, "short_pct": 36.4} ], // the closest one's, when met is false + "tried": [ {"label": "...", "settings": {...}, "step": "a higher frame multiplier", "passed": false, + "rejected": ["dropped 4 frames (0.9%)"], "measured": {...}} ], // in the order measured + "skipped": [ {"label": "...", "settings": {...}, "why": "...", "reason": "at least as heavy as ..., which failed"} ], + "quality_ranking": ["Output resolution, up to the display's own size ...", "..."], "not_ranked": "...", + "rules": {"headroom": 1.1, "drop_limit": 0.005, "avg_share": 0.95, "at_target": 0.97, "load_limit": 0.909, + "warm_s": 2.0, "warm_restart_s": 5.0, "measure_s": 5.0}, + "notes": ["...", "Summit changes only its own settings ... can't change the game's own graphics options."] +} +``` + +**Applying a result**: `top[i].settings` holds all nine engine settings Optimize chooses (`interp`, `hz`, `model`, `motion`, +`engine`, `scaler`, `vsr_quality`, `output_res`, `aa`), each a valid registry value (`run.py --set KEY=VALUE` takes them, and so +does a profile's `[engine]` table). Every other setting stays as the user has it. `model`, `motion` and `engine` take effect after a +restart of the pipeline. Values that don't apply in that configuration are copied from the settings in use when the run started +(e.g. `hz` with `interp: false`, `vsr_quality` with FSR). + +## How a candidate passes (`judge`) + +* The 1% low (mean of the slowest 1% of frametimes, at least 100 frames) clears the minimum by 10%. When the display's + refresh rate leaves no room for that (a 60 Hz screen and 60 fps asked for), the 1% low must reach 97% of the target and + the pipeline must be at most ~91% busy. +* The average reaches 95% of the rate the multiplier makes; at most 0.5% of frames dropped. +* The added delay (median, Summit's own) is under `max_delay_ms` when one is given. +* The queue had drained before measuring (`settled`). After a change the engine waits 2 s (5 s after a restart), and then until + no frame has queued 50 ms for a whole second (at most 20 s more). Each candidate is then measured for 5 s. + +## Headroom (no run) + +Session summaries (`sessions/summit-session-*.json`) get a `"headroom"` object: `state` (`room`, `fits`, `behind`, `unknown`), +`load_pct`, `display_hz`, `output_fps`, `suggestions` (each `{"key", "value", "text", "set": {every setting the change needs}}`), +`line` (the overlay's message), `short` and `note`. These are suggestions only: nothing is applied. The `load` is worked out from the stage +times, so it is an estimate. Optimize is what measures. diff --git a/engine/framegen/io.py b/engine/framegen/io.py index 0d871e5..edd9dc0 100644 --- a/engine/framegen/io.py +++ b/engine/framegen/io.py @@ -713,6 +713,8 @@ class GLWindowSink: print(f"[display] upscaling with {self._name(self.mode)}{details[self.mode]}; u cycles " + " / ".join(self._name(m) for m in self.modes)) self.collector = None # framegen.stats.Collector (run.py sets it): the stage times go there + self.optimizer = None # framegen/optimize.py Control (run.py sets it): its countdown and result card are drawn + self._opt_panel, self._opt_state = None, None self._cfg_seen, self._vsr_seen = None, 0 self.timer = GpuTimer(GL, on_sample=self._gl_sample) # GPU time of the scale/draw step, reported on close self.look_timer = GpuTimer(GL, on_sample=lambda label, ms: self._stage("look", ms)) # ...and of the look @@ -1499,6 +1501,14 @@ class GLWindowSink: time.sleep(0.03) panel.close() + def display_mode(self) -> tuple[int, int, float] | None: + """The monitor fullscreen goes to (pick_monitor): its own width, height and refresh rate. None if unknown.""" + try: + mode = self.glfw.get_video_mode(pick_monitor(self.glfw)) + return mode.size.width, mode.size.height, float(mode.refresh_rate) + except Exception: # noqa: BLE001 + return None + def toast(self, text: str, seconds: float = 2.0) -> None: """A short message in the top-right corner.""" self._toast_text, self._toast_until = text, time.perf_counter() + seconds @@ -1515,6 +1525,9 @@ class GLWindowSink: self.cmd = r elif r in ("save_replay", "save_summary"): self.cmd = r + elif r and r.startswith("optimize"): # the Optimize tab (framegen/optimize.py, through the pipeline) + self.menu.open = False + self.cmd = r def _do(self, action: str) -> None: """What the keys do, by name: the window's own (_on_key) and the system-wide ones over a game (_events).""" @@ -1557,6 +1570,13 @@ class GLWindowSink: if action == glfw.PRESS: self._do("menu") return + o = self.optimizer.state() if self.optimizer is not None and not self.menu.open else "idle" + if o != "idle" and key in (glfw.KEY_ESCAPE, glfw.KEY_BACKSPACE): # Optimize: stop, or keep my settings + self.cmd = "optimize_cancel" + return + if o == "card" and key in (glfw.KEY_ENTER, glfw.KEY_KP_ENTER): # Optimize's card: Apply + self.cmd = "optimize_apply" + return if in_menu: name = ("prev_tab" if mods & glfw.MOD_SHIFT else "next_tab") if key == glfw.KEY_TAB else nav[key] self._menu_result(self.menu.key(name)) @@ -1691,6 +1711,33 @@ class GLWindowSink: self._toast_state = state p = self.toast_panel p.blit(x0 + max(0, (dw - p.w) // 2), y0 + dh - int(16 * ui), self._target()) + self._draw_optimizer(x0, y0, dw, dh, ui, op) + + def _draw_optimizer(self, x0: int, y0: int, dw: int, dh: int, ui: float, op: float) -> None: + """Optimize (framegen/optimize.py): its countdown and candidate at the top while it runs; its result card in + the middle once done (Enter applies, Esc keeps the player's settings; also on the overlay's Optimize tab).""" + o = self.optimizer + if o is None or self.menu.open: + return + banner, result = o.banner(), o.result() + if banner is None and result is None: + return + from . import optimize as opt + state = (banner, id(result), round(ui, 3), op) + if self._opt_panel is None: + self._opt_panel = _Panel(self.GL, self.hdr10) + if state != self._opt_state: + if banner is not None: + from .hud import toast + self._opt_panel.update_rgba(toast(banner, ui, op)) + else: + self._opt_panel.update_rgba(opt.card_image(result, ui, max(op, 0.92), o.runner.saved_to)) + self._opt_state = state + p = self._opt_panel + if banner is not None: # top middle, below where messages go + p.blit(x0 + max(0, (dw - p.w) // 2), y0 + dh - int(96 * ui), self._target()) + else: # in the middle (its top kept in the picture) + p.blit(x0 + max(0, (dw - p.w) // 2), y0 + min(dh, (dh + p.h) // 2), self._target()) def busy(self, fn, text: str): """Run fn() on a worker thread while the window stays responsive, showing the last frame and `text`. diff --git a/engine/framegen/menu.py b/engine/framegen/menu.py index dbd612a..0a9ed1b 100644 --- a/engine/framegen/menu.py +++ b/engine/framegen/menu.py @@ -45,7 +45,16 @@ ACTION_HELP = { "summary": "Writes this session's numbers so far (averages, lows, the time of each stage, the settings and what " "changed) to a .json and a .txt file in Summit's data folder, and shows where. Summit also does it when " "it stops.", + # framegen/optimize.py, on the Optimize tab + "optimize": "Tries Summit's own settings one after another for a few seconds each (with a countdown at the top) and " + "keeps the best that holds your minimums, by your priority. Only Summit's settings change, never the " + "game's own graphics options. Your settings come back exactly if you stop it.", + "optimize_cancel": "Stops and puts your settings back exactly as they were.", + "optimize_apply": "Keeps the best result shown on the card and saves it as your settings.", } +OPTIMIZE_ROWS = {"idle": (("optimize", "Find my settings"),), + "running": (("optimize_cancel", "Stop optimizing"),), + "card": (("optimize_apply", "Apply the result"), ("optimize_cancel", "Keep my settings"))} QUIT_HELP = "Closes Summit's picture. A game started from Summit's launcher is closed with it." @@ -100,6 +109,8 @@ class Menu: self._hover: tuple | None = None # ("tab", i), ("close",): what the mouse is over, besides rows self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse self._drawn: tuple = (None, None) # render()'s last picture and what it showed (see there) + self.optimizer_state: Callable[[], str] | None = None # framegen/optimize.py Control.state, when it can run + self.optimizer_note: Callable[[], str] = lambda: "" # its headroom line, beside Find my settings @property def open(self) -> bool: @@ -142,6 +153,8 @@ class Menu: rows.append(Row("header", "#" + s.sub, s.sub)) sub = s.sub rows.append(Row("setting", s.key, s.label, s)) + if tab == "Optimize" and self.optimizer_state is not None: + rows += [Row("action", k, label) for k, label in OPTIMIZE_ROWS.get(self.optimizer_state(), ())] if self.restart_reasons(): rows.append(Row("action", "restart", "Restart now")) if tab is None: @@ -273,6 +286,8 @@ class Menu: return "save_replay" if row.key == "summary": return "save_summary" + if row.key.startswith("optimize"): + return row.key if self.armed: self.armed = False return "quit" @@ -557,7 +572,8 @@ class Menu: return (self.tab, self.focus, self.index, self._scroll, self.armed, self._hover, self.title, self.toggle_key, self._drop, self._drop_index, self._drop_scroll, self._drag and self._drag[0], tuple(self.settings.values().items()), tuple(self.restart_reasons()), - tuple(self.disabled(s.key) for s in self.specs)) + tuple(self.disabled(s.key) for s in self.specs), + self.optimizer_state and self.optimizer_state(), self.optimizer_note()) def state(self) -> tuple: """Everything the drawing depends on (the window redraws only when this changes).""" @@ -655,6 +671,8 @@ class Menu: label = again if danger and self.armed else row.label colour = U.BAD if danger else U.ACCENT c.text(pad + px(8), mid, label, f_label, colour) + if row.key == "optimize" and self.optimizer_note(): + c.text(xr, mid, U.fit(self.optimizer_note(), f_small, px(430)), f_small, U.DIM, "rm") if row.key == "restart": note = "Applies: " + ", ".join(self.restart_reasons()) c.text(xr, mid, U.fit(note, f_small, px(430)), f_small, U.DIM, "rm") diff --git a/engine/framegen/optimize.py b/engine/framegen/optimize.py new file mode 100644 index 0000000..e4fa607 --- /dev/null +++ b/engine/framegen/optimize.py @@ -0,0 +1,1110 @@ +"""Optimize: a benchmark that finds Summit's settings for the player's minimums and one priority. + +The player gives minimums (output resolution, output frame rate, optionally the most added delay) and ONE priority: +frame rate, resolution, quality or lowest delay. The search starts from the cheapest configuration that meets the +minimums, measures it, then raises the prioritised dimension step by step until a step breaks the minimum, and then +spends what is left of its time budget on the picture (QUALITY_RANKING), never giving back the priority. + +Only Summit's own (engine) settings are candidates: frame multiplier, interpolation model, motion detail, AI engine, +upscaler and its level, output resolution, anti-aliasing. Summit can't change a game's own graphics options. + +Layers: +* pure (no GPU, no window, no torch): Goal, Machine, Candidate, Measurement, judge(), Search (a generator that yields + candidates and is sent their measurements), the result dict, headroom() suggestions. tests/test_optimize.py drives + them with a fake measurer. +* measuring (still GPU-free): mark() / measure() read a framegen.stats.Collector over a span of the session. +* live: Runner steps a Search once a tick inside the pipeline (Pipeline.driver), changing live settings in place and + asking for a restart for the ones that need it; Control is what run.py and the window talk to (the overlay's Optimize + tab, the countdown banner, the result card with Apply / Cancel). + +Results go to oslayer.data_dir()/optimize (next to the sessions folder, not in it: the launcher reads every .json there +as a session). Format: docs/optimizer.md. +""" +from __future__ import annotations + +import datetime as _dt +import json +import math +import os +import time +from dataclasses import asdict, dataclass, field, replace +from pathlib import Path +from typing import Callable, Iterator + +import numpy as np + +from .settings import BY_KEY, OUTPUT_SIZES, parse_res + +FORMAT, VERSION = "summit-optimize", 1 +PRIORITIES = ("fps", "resolution", "quality", "delay") +PRIORITY_NAMES = {"fps": "Frame rate", "resolution": "Resolution", "quality": "Quality", "delay": "Lowest delay"} +HEADROOM = 1.10 # a candidate's 1% low must clear the minimum by this much (see judge() for a display at the minimum) +DROP_LIMIT = 0.005 # at most this share of frames dropped (left out because the pipeline was behind) +AVG_SHARE = 0.95 # the average must reach this share of the rate the multiplier makes +AT_TARGET = 0.97 # a display at the minimum: the 1% low must reach this share of the target... +LOAD_LIMIT = 1.0 / HEADROOM # ...and the pipeline use at most ~91% of its frame budget (the 10% headroom) +DELAY_SLACK_MS = 2.0 # Lowest delay: a picture improvement may add at most this much delay (measurement noise) +MIN_FRAMES = 100 # a measurement with fewer frames than this means nothing (the 1% low needs 100) +WARM_S, WARM_RESTART_S, MEASURE_S = 2.0, 5.0, 5.0 # after a live change / a restart; then measured for MEASURE_S +WARM_CAPTURE_MS, WARM_MAX_S = 50.0, 20.0 # also wait until no frame has queued this long for a second (a backlog +# after a restart drains slowly from a file played in real time), at most WARM_MAX_S longer +RESTART_GUESS_S = 12.0 # what a restart costs, until one has been timed +DEFAULT_BUDGET_S = 120.0 +BUDGETS = (60, 120, 180, 300) +ENGINE_KEYS = ("interp", "hz", "model", "motion", "engine", "scaler", "vsr_quality", "output_res", "aa") +RESTART_KEYS = tuple(k for k in ENGINE_KEYS if not BY_KEY[k].live) # model, motion, engine +RIFE = BY_KEY["model"].default +MAX_OUT = (3840, 2160) +GAME_NOTE = ("Summit changes only its own settings (frame generation, upscaling, anti-aliasing). It can't change the " + "game's own graphics options.") + +# The explicit picture ranking "Quality" uses (no reference picture exists live, so there is no score): shown to the +# player on the card and in the result file. Higher items count first; Search climbs them in this order. +QUALITY_RANKING = ( + "Output resolution, up to the display's own size: a smaller picture is stretched to the screen and looks softer.", + "Upscaler: NVIDIA RTX VSR (a higher level first) above AMD FSR 1.", + "Motion detail: Full above Half (Half is a little softer on small, fast details).", + "Anti-aliasing: SMAA-style above FXAA above Off.", + "Supersampling: an output bigger than the display, shrunk to it.", +) +NOT_RANKED = ("Not ranked: the AI engine (TensorRT and PyTorch draw the same frames), the interpolation model (NVIDIA's " + "licence doesn't allow comparing VFG with RIFE), FSR sharpening and CAS (taste: kept as you set them), " + "and Bilinear or no upscaler (FSR 1 costs about 0.1 ms and looks better, so they aren't tried).") +SCALER_TIER = {"bilinear": -1, "fsr": 0, "vsr": 1} +AA_TIER = {"off": 0, "fxaa": 1, "smaa": 2, "cas": 0} +AA_UP = {"off": "fxaa", "fxaa": "smaa"} + + +# ---- the inputs ------------------------------------------------------------------------------------------------------ +@dataclass(frozen=True) +class Goal: + min_res: tuple[int, int] = (1920, 1080) + min_fps: int = 60 + max_delay_ms: float | None = None + priority: str = "quality" + + def text(self) -> str: + d = f", at most {self.max_delay_ms:g} ms added delay" if self.max_delay_ms else "" + return (f"at least {res_name(self.min_res)} at {self.min_fps} fps{d}; priority " + f"{PRIORITY_NAMES[self.priority].lower()}") + + +@dataclass(frozen=True) +class Machine: + """What this PC and session can do. display: the screen's own size and refresh rate (the ceiling: no point making + frames faster than it shows them). source: the game's picture and its frame rate.""" + display: tuple[int, int] = (1920, 1080) + display_hz: float = 60.0 + source: tuple[int, int] = (1920, 1080) + src_fps: int = 30 + vsr: bool = False # NVIDIA RTX VSR can run here + vfg: bool = False # NVIDIA VFG is set up and can run here + trt: bool = False # TensorRT is installed + max_mult: int = 10 # e.g. 2 when writing --out (60 fps only) + motion_fixed: str | None = None # --scale on the command line: motion detail isn't ours to change + model_fixed: str | None = None # --model for testing: the model isn't ours to change + restarts: bool = True # settings that need a restart can be tried + + def text(self) -> str: + return (f"display {res_name(self.display)} at {self.display_hz:g} Hz, game {self.source[0]}x{self.source[1]} " + f"at {self.src_fps} fps") + + +def res_name(r: tuple[int, int]) -> str: + return BY_KEY["output_res"].names.get(f"{r[0]}x{r[1]}", f"{r[0]}x{r[1]}") + + +def parse_mode(text: str) -> tuple[tuple[int, int], float | None]: + """ "1920x1080@60" -> ((1920, 1080), 60.0); "1440p@144", "4k"; the rate is optional.""" + t = text.strip().lower() + size, _, hz = t.partition("@") + named = {"720p": (1280, 720), "900p": (1600, 900), "1080p": (1920, 1080), "1440p": (2560, 1440), + "1800p": (3200, 1800), "2160p": (3840, 2160), "4k": (3840, 2160)} + res = named.get(size.strip()) or parse_res(size) + if res is None: + raise ValueError(f"{text!r}: a size like 1920x1080 or 1440p, optionally @FPS") + try: + rate = float(hz) if hz.strip() else None + except ValueError: + raise ValueError(f"{text!r}: the rate after @ must be a number") from None + if rate is not None and not 20 <= rate <= 600: + raise ValueError(f"{text!r}: a rate from 20 to 600") + return res, rate + + +def parse_goal(text: str) -> tuple[Goal, tuple[tuple[int, int], float] | None]: + """run.py --optimize "min=1920x1080@60,priority=quality[,delay=50][,display=2560x1440@144]". + Returns (Goal, the display to assume or None: the real one).""" + kw: dict = {} + display = None + for part in filter(None, (p.strip() for p in text.split(","))): + k, sep, v = part.partition("=") + k, v = k.strip().lower(), v.strip() + if not sep: + raise ValueError(f"{part!r}: KEY=VALUE (min, priority, delay, display)") + if k == "min": + res, rate = parse_mode(v) + kw["min_res"] = res + if rate is not None: + kw["min_fps"] = int(round(rate)) + elif k == "fps": + kw["min_fps"] = int(v) + elif k == "priority": + p = {"framerate": "fps", "frame-rate": "fps", "frame_rate": "fps", "res": "resolution", + "latency": "delay", "lowest-delay": "delay"}.get(v.lower(), v.lower()) + if p not in PRIORITIES: + raise ValueError(f"priority={v}: one of {', '.join(PRIORITIES)}") + kw["priority"] = p + elif k == "delay": + kw["max_delay_ms"] = float(v) if v.lower() not in ("", "0", "none", "off") else None + elif k == "display": + res, rate = parse_mode(v) + display = (res, rate or 60.0) + else: + raise ValueError(f"{k}: not one of min, fps, priority, delay, display") + goal = Goal(**kw) + if not 20 <= goal.min_fps <= 600: + raise ValueError(f"min fps {goal.min_fps}: from 20 to 600") + return goal, display + + +# ---- a configuration --------------------------------------------------------------------------------------------------- +@dataclass(frozen=True) +class Candidate: + mult: int # frames shown for each real one; 1 = frame generation off + out: tuple[int, int] + scaler: str = "fsr" + vsr_q: int = 0 # RTX VSR's level 1-4 (0 with another upscaler) + motion: str = "half" + aa: str = "off" + model: str = RIFE + engine: str = "auto" + + def fps(self, src_fps: float) -> float: + return src_fps * self.mult + + def restart_key(self) -> tuple: + return (self.model,) if self.model == "vfg" else (self.model, self.motion, self.engine) + + def settings(self, base: dict | None = None) -> dict: + """The engine settings (ENGINE_KEYS, all of them) this configuration is. `base`: values for keys that don't + apply here (the VSR level with FSR, the multiplier with frame generation off) are kept from it.""" + base = base or {} + return {"interp": self.mult > 1, + "hz": 30 * self.mult if self.mult > 1 else base.get("hz", 60), + "model": self.model, + "motion": self.motion if self.model != "vfg" else base.get("motion", "auto"), + "engine": self.engine if self.model != "vfg" else base.get("engine", "auto"), + "scaler": self.scaler, + "vsr_quality": self.vsr_q if self.scaler == "vsr" else base.get("vsr_quality", 2), + "output_res": f"{self.out[0]}x{self.out[1]}", + "aa": self.aa} + + def label(self, src_fps: float) -> str: + fg = f"{self.mult}x ({self.fps(src_fps):g} fps)" if self.mult > 1 else f"no frame generation (the game's {src_fps:g} fps)" + up = (f"RTX VSR {BY_KEY['vsr_quality'].name(self.vsr_q)}" if self.scaler == "vsr" + else BY_KEY["scaler"].name(self.scaler)) + parts = [res_name(self.out), fg, up] + if self.mult > 1: + parts.append("NVIDIA VFG" if self.model == "vfg" else f"{self.motion.capitalize()} motion") + if self.engine != "auto" and self.model != "vfg": + parts.append(BY_KEY["engine"].name(self.engine)) + if self.aa != "off": + parts.append(BY_KEY["aa"].name(self.aa)) + return ", ".join(parts) + + def heavy(self) -> tuple: + """How much work it is, per dimension (bigger = more), for pruning: a candidate at least as heavy as one that + failed on performance, in every dimension and with the same model and engine, fails too.""" + return (self.mult, self.out[0] * self.out[1], SCALER_TIER[self.scaler] + self.vsr_q, + 1 if self.motion == "full" else 0, AA_TIER.get(self.aa, 0)) + + +def px(r: tuple[int, int]) -> int: + return r[0] * r[1] + + +def quality_key(c: Candidate, m: Machine) -> tuple: + """QUALITY_RANKING as a tuple to compare (bigger is better).""" + native = px(m.display) + return (min(px(c.out), native), SCALER_TIER[c.scaler] + c.vsr_q, + 1 if c.motion == "full" and c.model != "vfg" and c.mult > 1 else 0, AA_TIER.get(c.aa, 0), + max(0, px(c.out) - native)) + + +# ---- a measurement and the verdict --------------------------------------------------------------------------------------- +@dataclass +class Measurement: + fps_avg: float | None = None + low1: float | None = None + frames: int = 0 + dropped: int = 0 + delay_ms: float | None = None # median added delay of real frames (Summit's own: arrival to screen) + stages: dict = field(default_factory=dict) # stats.STAGES name -> average ms + load: float | None = None # share of the time the pipeline worked (AI frames + upscaler + look) + vram_mb: float | None = None # the card's memory in use, all programs (the most seen) + engine_mb: float | None = None # what this engine itself had reserved (PyTorch), when known + seconds: float = 0.0 # measured for + took_s: float = 0.0 # all it cost: change, restart, warm-up and measuring + queue_ms: float | None = None # 95th percentile of how long frames waited to be started on (a backlog shows here) + settled: bool = True # False: the warm-up ran out before the queue drained (the numbers include a backlog) + error: str = "" + + def brief(self) -> dict: + return {k: (round(v, 2) if isinstance(v, float) else v) for k, v in asdict(self).items() + if k not in ("error",) or v} + + +def judge(goal: Goal, m: Machine, c: Candidate, me: Measurement) -> list[dict]: + """Why `c` fails the goal ([] = it passes). Each failure: requirement, need, got, unit, text. + + Passing needs the 1% low (not the average) to clear the minimum by HEADROOM (10%), the average to reach the rate + the multiplier makes, and frames not to be dropped. When the display's refresh rate is the minimum (a 60 Hz screen + and 60 fps asked for), no frame rate can be 10% above it: the 1% low must then reach 97% of it and the headroom moves + to the frame budget (the pipeline at most ~91% busy).""" + fails: list[dict] = [] + f = lambda req, need, got, unit, text: fails.append( # noqa: E731 + {"requirement": req, "need": _r(need), "got": _r(got), "unit": unit, "text": text}) + target = c.fps(m.src_fps) + if me.error: + f("run", None, None, "", f"it didn't run: {me.error}") + return fails + if target + 0.5 < goal.min_fps: + f("fps", goal.min_fps, target, "fps", + f"makes {target:g} fps, under the minimum {goal.min_fps}" + + (f" (this display shows at most {m.display_hz:g})" if goal.min_fps > m.display_hz + 0.5 else "")) + if me.frames < MIN_FRAMES: + f("frames", MIN_FRAMES, me.frames, "frames", f"only {me.frames} frames could be measured") + return fails + roomy = target >= goal.min_fps * HEADROOM + need_low = goal.min_fps * HEADROOM if roomy else AT_TARGET * target + if me.low1 is None or me.low1 < need_low: + f("low1", need_low, me.low1, "fps", f"1% low {_n(me.low1)} fps, needs {need_low:.0f}" + + (" (the minimum plus 10%)" if roomy else "")) + elif not roomy and me.load is not None and me.load > LOAD_LIMIT: + f("load", LOAD_LIMIT * 100, me.load * 100, "%", + f"uses {me.load * 100:.0f}% of the frame budget: no room left (at most {LOAD_LIMIT * 100:.0f}%)") + if me.fps_avg is None or me.fps_avg < AVG_SHARE * target: + f("fps_avg", AVG_SHARE * target, me.fps_avg, "fps", f"averaged {_n(me.fps_avg)} fps of the {target:g} it makes") + if not me.settled: + f("queue", WARM_CAPTURE_MS, me.queue_ms, "ms", f"frames were still queuing after the warm-up (95th percentile " + f"{_n(me.queue_ms)} ms): the pipeline didn't catch up") + shown = me.frames + me.dropped + if shown and me.dropped / shown > DROP_LIMIT: + f("dropped", DROP_LIMIT * 100, 100 * me.dropped / shown, "%", + f"dropped {me.dropped} frames ({100 * me.dropped / shown:.1f}%)") + if goal.max_delay_ms: + if me.delay_ms is None: + f("delay", goal.max_delay_ms, None, "ms", "the delay couldn't be measured") + elif me.delay_ms > goal.max_delay_ms: + f("delay", goal.max_delay_ms, me.delay_ms, "ms", + f"adds {me.delay_ms:.0f} ms of delay, the most is {goal.max_delay_ms:g}") + return fails + + +PERF = ("low1", "load", "fps_avg", "dropped", "delay", "queue") # failures that more work can only make worse + + +def _r(v, nd: int = 1): + return None if v is None else round(float(v), nd) + + +def _n(v) -> str: + return "--" if v is None else f"{v:.0f}" + + +def shortfall(fails: list[dict]) -> list[dict]: + """The failures with how far off each is (short_by, short_pct): for the closest configuration.""" + out = [] + for x in fails: + need, got = x.get("need"), x.get("got") + y = dict(x) + if need is not None and got is not None: + over = x["requirement"] in ("load", "dropped", "delay") + by = (got - need) if over else (need - got) + pct = x["requirement"] not in ("load", "dropped") # (a share already: its points, not a percentage of it) + y["short_by"], y["short_pct"] = _r(by), _r(100 * by / need if need and pct else None) + out.append(y) + return out + + +def _miss(fails: list[dict]) -> float: + return sum(abs(x.get("short_pct") or 100.0) for x in shortfall(fails)) + + +# ---- the search ---------------------------------------------------------------------------------------------------------- +@dataclass +class Tried: + cand: Candidate + meas: Measurement + fails: list + why: str = "" # the step that led here + + @property + def passed(self) -> bool: + return not self.fails + + +@dataclass +class Move: + name: str + fn: Callable[[Candidate], Candidate | None] + repeat: bool = False + + +class Search: + """Yields candidates and is sent each one's Measurement (gen = search.steps(); c = next(gen); c = gen.send(m)...). + + Order (few measurements): the cheapest configuration meeting the minimums first; then the prioritised dimension up, + one step at a time, until a step fails; then the picture (QUALITY_RANKING, in its order) as long as the priority + holds. A candidate at least as heavy as one that failed on performance is skipped without measuring. Settings that + need a restart (motion detail, AI engine, model) are changed one at a time, so the session restarts as few times as + possible. Each candidate's cost is estimated before it is tried; when the time budget can't cover it, the search + stops and says so.""" + + def __init__(self, goal: Goal, machine: Machine, budget_s: float = DEFAULT_BUDGET_S, + current: dict | None = None) -> None: + self.goal, self.m, self.budget_s = goal, machine, budget_s + self.current = dict(current or {}) + self.tried: list[Tried] = [] + self.skipped: list[dict] = [] + self.notes: list[str] = [] + self.elapsed = 0.0 + self.restart_s = RESTART_GUESS_S + self.restarts = 0 + self.out_of_time = False + self._running: tuple | None = None # restart key of what runs now (None: the session's own) + self._best_delay: float | None = None + self._sizes = self._size_ladder() + + # -- the ladder of sizes, the base ----------------------------------------------------------------------------------- + def _size_ladder(self) -> list[tuple[int, int]]: + sizes = {parse_res(s) for s in OUTPUT_SIZES if parse_res(s)} | {self.goal.min_res, self.m.display} + lo = self.goal.min_res + return sorted((s for s in sizes if s[0] >= lo[0] and s[1] >= lo[1] and px(s) <= px(MAX_OUT) or s == lo), + key=px) + + def base(self) -> Candidate: + g, m = self.goal, self.m + cap = min(m.max_mult, 10, max(1, int((m.display_hz + 0.5) // m.src_fps))) + mult = max(1, math.ceil(g.min_fps / m.src_fps - 1e-9)) + if mult > cap: + why = (f"this display runs at {m.display_hz:g} Hz" if g.min_fps > m.display_hz + 0.5 else + f"the frame multiplier goes up to {cap}x here") + self.notes.append(f"{g.min_fps} fps can't be reached: {why}. The closest is {m.src_fps * cap:g} fps.") + mult = cap + model = m.model_fixed or RIFE + motion = m.motion_fixed or "half" + engine = "auto" + if mult == 1: # no frame generation: the AI's settings don't matter, keep the session's (no restart for them) + motion = self.current.get("motion", motion) if not m.motion_fixed else motion + engine = self.current.get("engine", engine) + model = self.current.get("model", model) if not m.model_fixed else model + return Candidate(mult=mult, out=self._sizes[0], scaler="fsr", motion=motion, model=model, engine=engine) + + # -- moves ---------------------------------------------------------------------------------------------------------------- + def _next_size(self, c: Candidate, up_to: int | None) -> Candidate | None: + bigger = [s for s in self._sizes if px(s) > px(c.out) and (up_to is None or px(s) <= up_to)] + return replace(c, out=bigger[0]) if bigger else None + + def _moves(self) -> list[Move]: + m, native = self.m, px(self.m.display) + rife = lambda c: c.model != "vfg" and c.mult > 1 # noqa: E731 + q = [Move("output resolution up to the display's", lambda c: self._next_size(c, native), True)] + if m.vsr: + q += [Move("RTX VSR instead of FSR 1", lambda c: replace(c, scaler="vsr", vsr_q=1) if c.scaler == "fsr" + else None), + Move("a higher RTX VSR level", lambda c: replace(c, vsr_q=c.vsr_q + 1) + if c.scaler == "vsr" and c.vsr_q < 4 else None, True)] + if m.restarts and not m.motion_fixed: + q.append(Move("Full motion detail", lambda c: replace(c, motion="full") + if rife(c) and c.motion == "half" else None)) + q.append(Move("anti-aliasing", lambda c: replace(c, aa=AA_UP[c.aa]) if c.aa in AA_UP else None, True)) + q.append(Move("supersampling (bigger than the display)", lambda c: self._next_size(c, None))) + p = self.goal.priority + if p == "fps": + return [Move("a higher frame multiplier", self._mult_up, True)] + q + if p == "resolution": + return [Move("a higher output resolution", lambda c: self._next_size(c, native), True)] + q[1:] + if p == "delay": + first = [] + if m.trt and m.restarts and not m.model_fixed: + first.append(Move("TensorRT (the other AI engine)", lambda c: replace(c, engine="trt") + if rife(c) and c.engine == "auto" else None)) + return first + q + return q + + def _mult_up(self, c: Candidate) -> Candidate | None: + n = c.mult + 1 + if n > self.m.max_mult or n > 10 or c.fps(self.m.src_fps) / c.mult * n > self.m.display_hz + 0.5: + return None + return replace(c, mult=n) + + def _fallbacks(self, c: Candidate) -> list[tuple[str, Candidate]]: + out = [] + if c.mult == 1 and (two := self._mult_up(c)) is not None: # generated frames can hold a rate the game's don't + out.append(("frame generation, as the game's own frames didn't hold the minimum", + replace(two, motion=self.m.motion_fixed or "half", engine="auto", + model=self.m.model_fixed or RIFE))) + if self.m.vfg and self.m.restarts and not self.m.model_fixed and c.model != "vfg" and c.mult > 1: + out.append(("NVIDIA VFG, as RIFE missed the minimum", replace(c, model="vfg", motion="half"))) + if self.m.trt and self.m.restarts and c.model != "vfg" and c.engine == "auto" and c.mult > 1: + out.append(("TensorRT, as the base missed the minimum", replace(c, engine="trt"))) + return out + + # -- trying one ------------------------------------------------------------------------------------------------------------ + def cost(self, c: Candidate) -> float: + restart = self._running is not None and c.restart_key() != self._running or ( + self._running is None and self._needs_restart_from_current(c)) + return MEASURE_S + (self.restart_s + WARM_RESTART_S if restart else WARM_S) + + def _needs_restart_from_current(self, c: Candidate) -> bool: + cur = self.current + if not cur: + return False + want = c.settings(cur) + return any(cur.get(k) != want[k] for k in RESTART_KEYS if not (k == "motion" and cur.get(k) == "auto")) + + def _known(self, c: Candidate) -> Tried | None: + return next((t for t in self.tried if t.cand == c), None) + + def _pruned_by(self, c: Candidate) -> Tried | None: + h = c.heavy() + for t in self.tried: + if t.passed or not any(x["requirement"] in PERF for x in t.fails): + continue + if t.cand.model == c.model and t.cand.engine == c.engine and all(a <= b for a, b in zip(t.cand.heavy(), h)): + return t + return None + + def _try(self, c: Candidate, why: str) -> Iterator[Candidate]: + """Yields c to be measured (unless known, pruned or out of time). Returns True / False (passed or not), or + None when it wasn't tried.""" + known = self._known(c) + if known is not None: + return known.passed + if self.out_of_time: + return None + src = self.m.src_fps + by = self._pruned_by(c) + if by is not None: + self.skipped.append({"label": c.label(src), "settings": c.settings(self.current), "why": why, + "reason": f"at least as heavy as {by.cand.label(src)}, which failed"}) + return None + est = self.cost(c) + if self.elapsed + est > self.budget_s: + self.out_of_time = True + self.skipped.append({"label": c.label(src), "settings": c.settings(self.current), "why": why, + "reason": f"not enough time left in the budget (needs about {est:.0f} s, " + f"{max(0.0, self.budget_s - self.elapsed):.0f} s left)"}) + return None + if (c.restart_key() != self._running if self._running is not None else self._needs_restart_from_current(c)): + self.restarts += 1 + meas = yield c + if not isinstance(meas, Measurement): + raise TypeError("send() a Measurement") + self._running = c.restart_key() + self.elapsed += meas.took_s + t = Tried(c, meas, judge(self.goal, self.m, c, meas), why) + self.tried.append(t) + return t.passed + + def _keeps_priority(self, nxt: Tried) -> bool: + if self.goal.priority != "delay" or self._best_delay is None or nxt.meas.delay_ms is None: + return True + return nxt.meas.delay_ms <= self._best_delay + DELAY_SLACK_MS + + def steps(self) -> Iterator[Candidate]: + base = self.base() + ok = yield from self._try(base, "the cheapest configuration that meets the minimums") + best = base if ok else None + if not ok: + for why, alt in self._fallbacks(base): + if (yield from self._try(alt, why)): + best = alt + break + if best is None: + return + self._best_delay = self._known(best).meas.delay_ms + for move in self._moves(): + if self.out_of_time: + break + while True: + nxt = move.fn(best) + if nxt is None: + break + ok = yield from self._try(nxt, move.name) + t = self._known(nxt) + if not ok or t is None or not self._keeps_priority(t): + if ok and t is not None: + t.fails.append({"requirement": "priority", "need": _r(self._best_delay), "got": + _r(t.meas.delay_ms), "unit": "ms", "text": "adds delay (the priority is " + "the lowest delay)"}) + break + best = nxt + if self.goal.priority == "delay" and t.meas.delay_ms is not None: + self._best_delay = min(self._best_delay or 1e9, t.meas.delay_ms) + if not move.repeat: + break + + # -- the result ------------------------------------------------------------------------------------------------------------- + def rank_key(self, t: Tried) -> tuple: + c, q, src = t.cand, quality_key(t.cand, self.m), self.m.src_fps + d = t.meas.delay_ms if t.meas.delay_ms is not None else 1e6 + p = self.goal.priority + if p == "fps": + return (c.fps(src), q, -d) + if p == "resolution": + return (min(px(c.out), px(self.m.display)), q, c.fps(src)) + if p == "delay": # within DELAY_SLACK_MS of the least delay measured counts as the same (noise) + least = min((x.meas.delay_ms for x in self.tried if x.passed and x.meas.delay_ms is not None), default=d) + return (0.0 if d <= least + DELAY_SLACK_MS else -d, q) + return (q, -d) + + def _why(self, i: int, t: Tried, first: Tried | None) -> str: + c, me, src, p = t.cand, t.meas, self.m.src_fps, self.goal.priority + if i == 0: + head = {"fps": f"The highest frame rate that held: {c.fps(src):g} fps (1% low {_n(me.low1)}) on this " + f"{self.m.display_hz:g} Hz display", + "resolution": f"The biggest output that held: {res_name(c.out)}", + "quality": "The best picture by the ranking that held the minimums", + "delay": f"The least added delay that held the minimums: {_n(me.delay_ms)} ms"}[p] + return head + ("; then the best picture there." if p != "quality" else + f" (1% low {_n(me.low1)} fps).") + a, b = self.rank_key(first), self.rank_key(t) + names = {"fps": ("a lower frame rate", "a plainer picture", "more delay"), + "resolution": ("a smaller output", "a plainer picture", "a lower frame rate"), + "delay": ("more delay", "a plainer picture"), + "quality": ("a plainer picture", "more delay")}[p] + k = next((j for j, (x, y) in enumerate(zip(a, b)) if x != y), len(names) - 1) + return f"Also passed; ranked below #1 for {names[min(k, len(names) - 1)]}." + + def result(self, cancelled: bool = False, error: str = "") -> dict: + src = self.m.src_fps + passing = sorted((t for t in self.tried if t.passed), key=self.rank_key, reverse=True) + top = passing[:3] + out = { + "format": FORMAT, "version": VERSION, + "created": _dt.datetime.now().isoformat(timespec="seconds"), "created_unix": int(time.time()), + "game": os.environ.get("SUMMIT_GAME", "").strip() or None, + "goal": {"min_resolution": f"{self.goal.min_res[0]}x{self.goal.min_res[1]}", "min_fps": self.goal.min_fps, + "max_delay_ms": self.goal.max_delay_ms, "priority": self.goal.priority, + "text": self.goal.text()}, + "machine": {**{k: v for k, v in asdict(self.m).items() if k not in ("display", "source")}, + "display": f"{self.m.display[0]}x{self.m.display[1]}", + "source": f"{self.m.source[0]}x{self.m.source[1]}", "text": self.m.text()}, + "budget_s": self.budget_s, "elapsed_s": round(self.elapsed, 1), "restarts": self.restarts, + "cancelled": cancelled, "error": error or None, + "met": bool(top), + "top": [{"rank": i + 1, "label": t.cand.label(src), "settings": t.cand.settings(self.current), + "measured": t.meas.brief(), "why": self._why(i, t, top[0])} for i, t in enumerate(top)], + "closest": None, "failures": [], + "tried": [{"label": t.cand.label(src), "settings": t.cand.settings(self.current), "step": t.why, + "passed": t.passed, "rejected": [x["text"] for x in t.fails], "measured": t.meas.brief()} + for t in self.tried], + "skipped": list(self.skipped), + "quality_ranking": list(QUALITY_RANKING), "not_ranked": NOT_RANKED, + "rules": {"headroom": HEADROOM, "drop_limit": DROP_LIMIT, "avg_share": AVG_SHARE, + "at_target": AT_TARGET, "load_limit": round(LOAD_LIMIT, 3), "warm_s": WARM_S, + "warm_restart_s": WARM_RESTART_S, "measure_s": MEASURE_S}, + "notes": list(self.notes) + [GAME_NOTE], + } + if not top and self.tried: + near = min(self.tried, key=lambda t: _miss(t.fails)) + out["closest"] = {"label": near.cand.label(src), "settings": near.cand.settings(self.current), + "measured": near.meas.brief()} + out["failures"] = shortfall(near.fails) + return out + + +def run_search(search: Search, measure: Callable[[Candidate], Measurement]) -> dict: + """Drives a Search with `measure` to the end (tests; anything that measures synchronously).""" + gen = search.steps() + try: + c = next(gen) + while True: + c = gen.send(measure(c)) + except StopIteration: + pass + return search.result() + + +# ---- measuring a span of a session (framegen.stats.Collector) --------------------------------------------------------------- +LOAD_STAGES = ("interp", "upscale", "look") + + +def mark(coll, now: float) -> dict: + """Where the collector is now; measure(coll, mark, later) gives the numbers since.""" + return {"t": now, "wall": time.time(), "stages": {s: len(v) for s, v in coll.stage_all.items()}, + "dropped": coll.dropped_total, "delays": len(coll.delays()), + "hist": len(coll.sampler.history) if getattr(coll, "sampler", None) is not None else 0} + + +def measure(coll, mk: dict, now: float, engine_mb: float | None = None) -> Measurement: + from . import stats as S + t = np.asarray(coll.t_all, np.float64) + i = int(np.searchsorted(t, mk["t"], side="right")) + ms = np.asarray(coll.ms_all, np.float64)[i:] + span = max(1e-6, now - mk["t"]) + stages, work = {}, 0.0 + for s, v in coll.stage_all.items(): + part = np.asarray(v[mk["stages"].get(s, 0):], np.float64) + if part.size: + stages[s] = round(float(part.mean()), 3) + if s in LOAD_STAGES: + work += float(part.sum()) + d = coll.delays()[mk["delays"]:] + vram = None + if getattr(coll, "sampler", None) is not None: + mem = [(h.get("gpu") or {}).get("mem") for h in coll.sampler.history[mk["hist"]:]] + mem = [x for x in mem if x is not None] + vram = max(mem) if mem else None + cap = np.asarray(coll.stage_all["capture"][mk["stages"].get("capture", 0):], np.float64) + return Measurement(queue_ms=round(float(np.percentile(cap, 95)), 1) if cap.size else None, + fps_avg=1000.0 / float(ms.mean()) if ms.size else None, + low1=S.low_fps(ms, 0.01, S.MIN_FOR_1PCT), frames=int(ms.size), + dropped=coll.dropped_total - mk["dropped"], + delay_ms=float(np.median(d)) if len(d) else None, stages=stages, + load=work / (span * 1000.0), vram_mb=vram, engine_mb=engine_mb, seconds=round(span, 2)) + + +# ---- headroom: a cheap check from a session's numbers, no run --------------------------------------------------------------- +def load_of_summary(summary: dict) -> float | None: + """The share of the session the pipeline worked (AI frames, upscaler, look), from a session summary.""" + dur = summary.get("duration_s") or 0 + st = summary.get("stages") or {} + if dur <= 0 or not st: + return None + return sum(st[s]["avg_ms"] * st[s]["n"] for s in LOAD_STAGES if s in st) / (dur * 1000.0) + + +def headroom(fps_avg: float | None, load: float | None, dropped_share: float, settings: dict, machine: Machine) -> dict: + """Suggestions only (never applied): with room to spare, changes that would improve the picture (or smoothness, up + to what the display shows); when falling behind, changes that would lighten the work. A plain dict for the session + summary; `line` is for the overlay.""" + hz, src = machine.display_hz, machine.src_fps + mult = settings.get("hz", 60) // 30 if settings.get("interp") else 1 + out_fps = src * mult + res = parse_res(settings.get("output_res", "")) or machine.display + sug: list[dict] = [] + def s(key, value, text, **also): # "set": every setting the change needs (frame generation on, and its rate) + sug.append({"key": key, "value": value, "text": text, "set": {key: value, **also}}) + behind = dropped_share > 0.01 or (fps_avg is not None and fps_avg < 0.95 * min(out_fps, hz)) or ( + load is not None and load > 0.9) + state = "unknown" if load is None and fps_avg is None else "behind" if behind else ( + "room" if load is not None and load < 0.6 else "fits") + if out_fps > hz + 0.5 and mult > 1: + best = max(1, int((hz + 0.5) // src)) + s("hz", 30 * max(2, best), f"The display shows {hz:g} Hz, so {out_fps:g} fps is more than it can show: " + f"{src * best:g} fps does the same with less work.") + if state == "behind": + if settings.get("motion") != "half" and settings.get("model") != "vfg" and mult > 1: + s("motion", "half", "Half motion detail: about 40% less time per AI frame.") + if settings.get("scaler") == "vsr": + s("scaler", "fsr", "AMD FSR 1 instead of RTX VSR: far lighter.") + if mult > 2: + s("hz", 30 * (mult - 1), f"A lower multiplier: {src * (mult - 1):g} fps.") + if px(res) > px(machine.display): + s("output_res", f"{machine.display[0]}x{machine.display[1]}", "Output at the display's own size.") + if settings.get("aa", "off") != "off": + s("aa", "off", "Anti-aliasing off.") + elif state == "room": + if src * (mult + 1) <= hz + 0.5 and mult < 10: + if mult == 1: + s("interp", True, f"Frame generation on (2x): {src * 2:g} fps on this {hz:g} Hz display.", hz=60) + else: + s("hz", 30 * (mult + 1), f"A higher multiplier: {src * (mult + 1):g} fps on this {hz:g} Hz display.") + if px(res) < px(machine.display): + s("output_res", f"{machine.display[0]}x{machine.display[1]}", + f"Output at the display's own size ({res_name(machine.display)}) instead of stretching {res_name(res)}.") + if machine.vsr and settings.get("scaler") == "fsr": + s("scaler", "vsr", "NVIDIA RTX VSR instead of FSR 1: a cleaner, sharper picture.") + if settings.get("motion") == "half" and settings.get("model") != "vfg" and mult > 1: + s("motion", "full", "Full motion detail: sharper small, fast details.") + if settings.get("aa", "off") in ("off", "fxaa"): + s("aa", "smaa", "SMAA-style anti-aliasing: smoother edges.") + pct = None if load is None else round(load * 100) + if state == "room": + line = (f"This display is {hz:g} Hz and the pipeline uses {pct}% of its frame budget: " + f"{len(sug)} change{'s' if len(sug) != 1 else ''} could improve the picture (Optimize tab).") + elif state == "behind": + line = (f"Falling behind ({'' if pct is None else f'{pct}% of the frame budget, '}" + f"{dropped_share * 100:.1f}% dropped): lighter settings would help (Optimize tab).") + elif state == "fits": + line = f"Fits: the pipeline uses {pct}% of its frame budget on this {hz:g} Hz display." + else: + line = "" + short = {"room": f"{pct}% busy at {hz:g} Hz: room for a better picture", + "behind": "falling behind: lighter settings would help", "fits": f"{pct}% busy at {hz:g} Hz"}.get(state, "") + return {"state": state, "load_pct": pct, "display_hz": hz, "output_fps": out_fps, "suggestions": sug, + "line": line, "short": short, "note": "Suggestions only; nothing is changed without you. Estimates: Optimize measures."} + + +def headroom_of_summary(summary: dict, machine: Machine) -> dict: + fr = summary.get("frames") or {} + shown = (fr.get("presented") or 0) + (fr.get("dropped") or 0) + return headroom(summary.get("fps_avg"), load_of_summary(summary), + (fr.get("dropped") or 0) / shown if shown else 0.0, + (summary.get("config") or {}).get("settings") or {}, machine) + + +def headroom_live(coll, now: float, settings: dict, machine: Machine, span_s: float = 10.0) -> dict | None: + """The same check over the last span_s seconds of a running session (None until there are enough frames).""" + t = np.asarray(coll.t_all, np.float64) + if t.size < MIN_FRAMES or now - t[0] < span_s: + return None + i = int(np.searchsorted(t, now - span_s)) + ms = np.asarray(coll.ms_all, np.float64)[i:] + if ms.size < MIN_FRAMES: + return None + work = 0.0 + for s in LOAD_STAGES: + w = coll.stage_win.get(s) + if w is not None and len(w): + tt, vv = np.asarray(w.times(), np.float64), np.asarray(w.values(now), np.float64) + n = min(tt.size, vv.size) + work += float(vv[-n:][tt[-n:] >= now - span_s].sum()) + dropped = float(coll.dropped.values(now).sum()) if hasattr(coll, "dropped") else 0.0 + share = dropped / (ms.size + dropped) if ms.size else 0.0 + return headroom(1000.0 / float(ms.mean()), work / (span_s * 1000.0), share, settings, machine) + + +# ---- files ----------------------------------------------------------------------------------------------------------------- +def results_dir() -> Path: + from . import oslayer + return oslayer.data_dir() / "optimize" + + +def write_result(result: dict, directory: Path | None = None, path: Path | None = None) -> Path: + """summit-optimize-.json (or `path`), plus latest.json beside it. Returns the file written.""" + d = Path(directory) if directory is not None else results_dir() + p = Path(path) if path is not None else d / f"summit-optimize-{time.strftime('%Y%m%d-%H%M%S')}.json" + p.parent.mkdir(parents=True, exist_ok=True) + text = json.dumps(result, indent=2) + p.write_text(text, encoding="utf-8") + if path is None: + (d / "latest.json").write_text(text, encoding="utf-8") + return p + + +def format_text(r: dict) -> str: + lines = [f"Summit optimize: {r['goal']['text']}", r["machine"]["text"], + f"{len(r['tried'])} configurations measured in {r['elapsed_s']:.0f} s " + f"(budget {r['budget_s']:.0f} s, {r['restarts']} restarts)", ""] + if r.get("cancelled"): + lines += ["Cancelled: your settings were put back.", ""] + for t in r["top"]: + me = t["measured"] + lines += [f"#{t['rank']} {t['label']}", + f" avg {_n(me.get('fps_avg'))} fps, 1% low {_n(me.get('low1'))}, delay {_n(me.get('delay_ms'))} ms, " + f"load {_n((me.get('load') or 0) * 100)}%", f" {t['why']}"] + if not r["met"]: + lines.append("Nothing met the minimums.") + for f in r["failures"]: + lines.append(f" {f['text']}" + (f" (short by {f['short_pct']:g}%)" if f.get("short_pct") is not None + else "")) + if r["closest"]: + lines.append(f" Closest: {r['closest']['label']}") + lines += ["", "Tried:"] + for t in r["tried"]: + lines.append(f" {'pass' if t['passed'] else 'FAIL'} {t['label']} ({t['step']})" + + ("" if t["passed"] else ": " + "; ".join(t["rejected"]))) + for s in r["skipped"]: + lines.append(f" skip {s['label']}: {s['reason']}") + lines += ["", "Quality ranking:"] + [f" {i + 1}. {q}" for i, q in enumerate(r["quality_ranking"])] + lines += [f" {r['not_ranked']}"] + [f"Note: {n}" for n in r["notes"]] + return "\n".join(lines) + + +def registry() -> dict: + """For the launcher (settings.specs_json()["optimize"]): the --optimize grammar and where results go.""" + return {"syntax": "min=WxH@FPS,priority=" + "|".join(PRIORITIES) + "[,delay=MS][,display=WxH@HZ]", + "priorities": [{"key": p, "name": PRIORITY_NAMES[p]} for p in PRIORITIES], + "format": FORMAT, "version": VERSION, "dir": str(results_dir()), "latest": str(results_dir() / "latest.json"), + "quality_ranking": list(QUALITY_RANKING)} + + +# ---- live: stepping a Search inside the pipeline ----------------------------------------------------------------------------- +class Runner: + """One optimize run in a session. step(now) is called once a tick by the pipeline (in its thread, with the + window's); it returns "restart" when the session must restart for a candidate (or to put settings back), "quit" + when a command-line run is over, else None. The settings it changes are overrides (this run only, never saved) + until Apply; `before` holds the engine settings as they were, put back exactly on Cancel or an error.""" + + def __init__(self, search: Search, settings, coll, restart_needed: Callable[[], bool], + engine_mb: Callable[[], float | None] | None = None, on_result: Callable[[dict], str] | None = None, + card_s: float | None = None, clock: Callable[[], float] = time.perf_counter) -> None: + self.search, self.settings, self.coll = search, settings, coll + self.restart_needed, self.engine_mb, self.on_result = restart_needed, engine_mb, on_result + self.card_s, self.clock = card_s, clock + values = settings.values() + self.before = {k: values[k] for k in ENGINE_KEYS} + search.current = dict(self.before) + self.gen = search.steps() + self.state = "start" # start, warm, measure, restarting, card, done + self.cand: Candidate | None = None + self.t0 = clock() + self.t_apply = self.t_change = self.t_mark = 0.0 + self.warm = WARM_S + self._mark: dict | None = None + self.result: dict | None = None + self.saved_to = "" + self.message = "" # the last thing said (for the overlay and the log) + self._restart_t: float | None = None + self._card_until: float | None = None + self._settled = True + self._cap_seen: list = [] # (time, capture stage count) as the warm-up goes, to look at the last second + + def _queue_clear(self, now: float) -> bool: + """No frame waited WARM_CAPTURE_MS or more to be started on during the last second.""" + cap = self.coll.stage_all.get("capture") + if cap is None: + return True + self._cap_seen.append((now, len(cap))) + old = [x for x in self._cap_seen if x[0] <= now - 1.0] + if not old: # not a second of history yet + return False + start = old[-1] + self._cap_seen = [x for x in self._cap_seen if x[0] >= start[0]] + recent = cap[start[1]:] + return len(recent) >= 20 and max(recent) < WARM_CAPTURE_MS + + # -- settings ---------------------------------------------------------------------------------------------------------- + def _set(self, values: dict) -> bool: + """Overrides `values`; True when the session must restart for them.""" + cur = self.settings.values() + for k, v in values.items(): + if cur.get(k) != v: + self.settings.override(k, v) + return bool(self.restart_needed()) + + def restore(self) -> str | None: + return "restart" if self._set(self.before) else None + + # -- the steps ----------------------------------------------------------------------------------------------------------- + def _advance(self, now: float, meas: Measurement | None) -> str | None: + try: + c = next(self.gen) if meas is None else self.gen.send(meas) + except StopIteration: + return self._finish(now) + except Exception as e: # noqa: BLE001 - never leave the player on a half-tried configuration + return self._finish(now, error=str(e)[:200]) + self.cand, self.t_apply = c, now + print(f"[optimize] trying {c.label(self.search.m.src_fps)}", flush=True) + if self._set(c.settings(self.before)): + self.state, self._restart_t = "restarting", now + return "restart" + self.state, self.t_change, self.warm, self._cap_seen = "warm", now, WARM_S, [] + return None + + def step(self, now: float | None = None) -> str | None: + now = self.clock() if now is None else now + if self.state == "start": + return self._advance(now, None) + if self.state == "restarting": # the first tick of the new session + if self._restart_t is not None: + self.search.restart_s = max(1.0, now - self._restart_t) + self.state, self.t_change, self.warm, self._cap_seen = "warm", now, WARM_RESTART_S, [] + return None + if self.state == "warm": + if now - self.t_change >= self.warm: + self._settled = self._queue_clear(now) + if self._settled or now - self.t_change > self.warm + WARM_MAX_S: + self.state, self.t_mark, self._mark = "measure", now, mark(self.coll, now) + return None + if self.state == "measure": + if now - self.t_mark < MEASURE_S: + return None + try: + mb = self.engine_mb() if self.engine_mb is not None else None + except Exception: # noqa: BLE001 + mb = None + meas = measure(self.coll, self._mark, now, mb) + meas.took_s, meas.settled = now - self.t_apply, self._settled + return self._advance(now, meas) + if self.state == "card" and self._card_until is not None and now >= self._card_until: + self.state = "done" + return "quit" + return None + + def _finish(self, now: float, cancelled: bool = False, error: str = "") -> str | None: + self.result = self.search.result(cancelled=cancelled, error=error) + if self.on_result is not None: + try: + self.saved_to = self.on_result(self.result) or "" + except Exception as e: # noqa: BLE001 + self.saved_to = f"couldn't save: {e}" + self.state = "card" + self._card_until = None if self.card_s is None else now + self.card_s + if self.result["top"] and not cancelled and not error: # the winner on screen while the card is up + self.message = "Showing the best result. Enter: Apply. Esc: keep your settings." + return "restart" if self._set(self.result["top"][0]["settings"]) else None + self.message = error or ("Cancelled." if cancelled else "Nothing met your minimums.") + return self.restore() + + def command(self, cmd: str) -> str | None: + """ "optimize_cancel" / "optimize_apply" (the overlay, or Esc / Enter while the card is up).""" + r = self._command(cmd) + if self.state == "done" and self.card_s is not None: # a command-line run: over once the card is answered + return "quit" + return r + + def _command(self, cmd: str) -> str | None: + now = self.clock() + if cmd == "optimize_cancel": + if self.state in ("warm", "measure", "restarting", "start"): + self.gen.close() + r = self._finish(now, cancelled=True) + self.state = "done" + print("[optimize] cancelled; settings put back", flush=True) + return r + if self.state == "card": + self.state = "done" + print("[optimize] result not applied; settings put back", flush=True) + return self.restore() + if cmd == "optimize_apply" and self.state == "card" and self.result and self.result["top"]: + for k, v in self.result["top"][0]["settings"].items(): + self.settings.set(k, v) # saved + self.state = "done" + print("[optimize] applied and saved: " + self.result["top"][0]["label"], flush=True) + return "restart" if self.restart_needed() else None + return None + + # -- what the overlay shows --------------------------------------------------------------------------------------------- + def banner(self, now: float | None = None) -> str: + now = self.clock() if now is None else now + s = self.search + left = max(0.0, s.budget_s - (now - self.t0)) + head = f"Optimizing: about {int(left) // 60}:{int(left) % 60:02d} left, {len(s.tried) + 1} tried" + what = "" if self.cand is None else self.cand.label(s.m.src_fps) + phase = {"warm": f"settling ({max(0.0, self.warm - (now - self.t_change)):.0f} s)", + "measure": f"measuring ({max(0.0, MEASURE_S - (now - self.t_mark)):.0f} s)", + "restarting": "restarting", "start": "starting"}.get(self.state, "") + return f"{head}\n{what}\n{phase} - Esc or the Optimize tab cancels" + + +class Control: + """What run.py, the pipeline and the window talk to: at most one Runner at a time, and the headroom line. + make(settings) -> a Runner for the overlay's choices (run.py builds the Machine).""" + + def __init__(self, make: Callable[[], Runner | None], headroom_fn: Callable[[float], dict | None] | None = None) -> None: + self.make, self.headroom_fn = make, headroom_fn + self.runner: Runner | None = None + self.head: dict | None = None + self._head_next = 0.0 + self.toast: Callable[[str, float], None] | None = None + self._head_said = False + self.cli = False # run.py --optimize: the run starts with the first tick and the engine stops after its card + self.start_pending = False + + def state(self) -> str: + r = self.runner + if r is None or r.state == "done": + return "idle" + return "card" if r.state == "card" else "running" + + def step(self, now: float) -> str | None: + if self.start_pending: + self.start_pending = False + return self.command("optimize") + if self.runner is not None and self.runner.state != "done": + return self.runner.step(now) + if self.headroom_fn is not None and now >= self._head_next: + self._head_next = now + 10.0 + try: + self.head = self.headroom_fn(now) + except Exception: # noqa: BLE001 + self.head = None + if self.head and self.head["state"] in ("room", "behind") and not self._head_said and self.toast: + self._head_said = True + self.toast(self.head["line"], 8.0) + return None + + def command(self, cmd: str) -> str | None: + if cmd == "optimize": + if self.state() == "idle": + self.runner = self.make() + if self.runner is not None: + return self.runner.step() + return None + if self.runner is not None: + return self.runner.command(cmd) + return None + + def banner(self) -> str | None: + return self.runner.banner() if self.state() == "running" else None + + def result(self) -> dict | None: + return self.runner.result if self.state() == "card" else None + + +# ---- the result card --------------------------------------------------------------------------------------------------------- +def card_image(r: dict, ui: float = 1.0, opacity: float = 1.0, saved: str = ""): + """The result as an RGBA image (framegen/ui_draw.py), for the window: the top 3 with their numbers and why, or what + failed and by how much; Apply / Keep my settings; the quality ranking in one line.""" + from . import ui_draw as U + p = lambda v: max(1, int(round(v * ui))) # noqa: E731 + f_title, f_name, f_row, f_lab = U.font(p(20), "bold"), U.font(p(15), "semibold"), U.font(p(13)), U.font(p(12)) + pad, w = p(24), p(780) + inner = w - 2 * pad + blocks: list[tuple[str, object, tuple, int]] = [] # (text, font, colour, indent) + add = lambda text, f, col, ind=0: [blocks.append((line, f, col, ind)) for line in U.wrap(text, f, inner - ind)] # noqa: E731 + met = r["met"] + cap = lambda t: t[:1].upper() + t[1:] # noqa: E731 + sub = (f"{cap(r['goal']['text'])}. {cap(r['machine']['text'])}. {len(r['tried'])} tried in " + f"{int(r['elapsed_s']) // 60}:{int(r['elapsed_s']) % 60:02d}.") + add(sub, f_lab, U.DIM) + blocks.append(("", f_lab, U.DIM, 0)) + for t in r["top"]: + me = t["measured"] + add(f"#{t['rank']} {t['label']}", f_name, U.ACCENT if t["rank"] == 1 else U.TEXT) + vram = (f", engine memory {me['engine_mb']:.0f} MB" if me.get("engine_mb") else + f", card memory {me['vram_mb'] / 1024:.1f} GB (all programs)" if me.get("vram_mb") else "") + add(f"average {_n(me.get('fps_avg'))} fps, 1% low {_n(me.get('low1'))} fps, delay {_n(me.get('delay_ms'))} ms, " + f"pipeline {_n((me.get('load') or 0) * 100)}% busy{vram}", f_row, U.TEXT, p(26)) + add(t["why"], f_lab, U.DIM, p(26)) + if not met: + add("Nothing held your minimums:", f_name, U.BAD) + for f in r["failures"]: + add(f"- {f['text']}" + (f" (short by {f['short_pct']:g}%)" if f.get("short_pct") is not None else ""), + f_row, U.TEXT, p(14)) + if r["closest"]: + add(f"Closest: {r['closest']['label']}", f_row, U.DIM, p(14)) + for n in r["notes"][:-1]: + add(n, f_lab, U.DIM, p(14)) + if r.get("cancelled"): + add("Stopped: your settings are back as they were.", f_row, U.TIGHT) + rejected = sum(1 for t in r["tried"] if not t["passed"]) + blocks.append(("", f_lab, U.DIM, 0)) + add(f"{rejected} rejected, {len(r['skipped'])} skipped (the file lists each, with the reason). Quality ranking: " + + " > ".join(("resolution up to the display's", "RTX VSR over FSR 1", "Full motion", "SMAA > FXAA", + "supersampling")) + ".", f_lab, U.FAINT) + add(GAME_NOTE, f_lab, U.FAINT) + if saved: + add("Saved: " + saved.replace(str(Path.home()), "~"), f_lab, U.FAINT) + line_h = {id(f_name): p(24), id(f_row): p(20), id(f_lab): p(18)} + btn_h = p(40) + h = p(20) + p(30) + sum(line_h[id(b[1])] for b in blocks) + p(16) + btn_h + p(18) + c = U.Canvas(w, h, U.BG, p(16), border=U.BORDER) + c.logo(pad, p(18), p(24)) + title = ("Optimize: the best settings for you" if met else "Optimize: your minimums weren't reached") + c.text(pad + p(34), p(18) + p(12), title, f_title, U.TEXT) + y = p(20) + p(30) + for text, f, col, ind in blocks: + lh = line_h[id(f)] + if text: + c.text(pad + ind, y + lh // 2, text, f, col) + y += lh + y += p(16) + buttons = ([("Enter", "Apply #1 and save it")] if met and not r.get("cancelled") else []) + [ + ("Esc", "Keep my settings" if met else "Close")] + x = pad + for key, text in buttons: + bw = U.text_w(key, f_name) + U.text_w(text, f_row) + p(40) + c.rrect(x, y, x + bw, y + btn_h, p(10), fill=U.ACCENT if key == "Enter" else U.RAISED, outline=U.BORDER) + tc = U.ON_ACCENT if key == "Enter" else U.TEXT + n = c.text(x + p(14), y + btn_h // 2, key, f_name, tc) + c.text(x + p(14) + n + p(10), y + btn_h // 2, text, f_row, tc) + x += bw + p(12) + c.text(w - pad, y + btn_h // 2, "or the overlay's Optimize tab", f_lab, U.FAINT, "rm") + return c.rgba(opacity) diff --git a/engine/framegen/pipeline.py b/engine/framegen/pipeline.py index 304a1f4..2daffcc 100644 --- a/engine/framegen/pipeline.py +++ b/engine/framegen/pipeline.py @@ -353,6 +353,7 @@ class Pipeline: self.stats: Stats | None = None # the running session's, for reports written while it plays self.beat = time.perf_counter() # when run()'s loop last went round (run.py's watchdog reads it) self.waiting = None # the source's Waiting while no frame is coming, else None (the watchdog reads it too) + self.driver = None # framegen/optimize.py Control: stepped once a tick; it may ask for a restart or the end def run(self, source, sink=None, enabled: bool = True, score: bool = False, label: str = "", on_tick=None, hz: int = 60, settings=None, gt=None, remote=None, replay=None, @@ -550,6 +551,11 @@ class Pipeline: if tick.t_arrival < t_start: # queued while the previous session was restarting: show live frames only st.stale += 1 continue + if self.driver is not None: # Optimize (framegen/optimize.py): may change settings, picked up just below + d_cmd = self.driver.step(time.perf_counter()) + if d_cmd in ("quit", "restart"): + st.exit = d_cmd + break if settings is not None: # changed in the menu (or by a hotkey) since the last tick? # The multiplier N is settings.hz / 30: N frames for each real one, so a 60 fps game shows 60 x N want_hz = min(600, settings.hz * (2 if game60 else 1)) if sink is not None else 60 @@ -878,6 +884,8 @@ class Pipeline: st.exit = "end" break if sink is not None: + if cmd and cmd.startswith("optimize") and self.driver is not None: # the overlay's Optimize tab + cmd = self.driver.command(cmd) if cmd in ("quit", "restart"): st.exit = cmd break diff --git a/engine/framegen/remote.py b/engine/framegen/remote.py index be48702..d81e24c 100644 --- a/engine/framegen/remote.py +++ b/engine/framegen/remote.py @@ -9,6 +9,9 @@ The launcher writes one command per line to our stdin: look-show show this look (the Looks page is editing it), whatever the Look settings say look-hide back to the Look settings' look looks-reload the user's looks changed on disk: read them again (the list of looks is in the state) + optimize start Optimize with the Optimize tab's settings (framegen/optimize.py; run.py adds it) + optimize-cancel stop it, or close its result, putting the settings back + optimize-apply keep its best result and save it and reads a `[settings-state] {json}` line on our stdout at the start of every session and after every change, whoever made it (this link, the menu or a hotkey): the current values, which choices can be picked right now, diff --git a/engine/framegen/settings.py b/engine/framegen/settings.py index a73aedd..4413a18 100644 --- a/engine/framegen/settings.py +++ b/engine/framegen/settings.py @@ -585,6 +585,30 @@ def _laid_out(specs: tuple[Spec, ...]) -> tuple[Spec, ...]: return tuple(out) + tuple(s for s in specs if s.key not in placed) +# framegen/optimize.py: what the overlay's Optimize tab asks for (its run itself is the "Find my settings" row). Kept +# in specs_json too (the launcher may start a run with them); the --optimize grammar is under "optimize" there. +OPTIMIZE_SPECS = ( + Spec("opt_min_res", "Minimum resolution", ("1280x720", "1600x900", "1920x1080", "2560x1440", "3840x2160"), + "1920x1080", OUTPUT_NAMES, group="Optimize", sub="Your minimums", + help="The smallest output Optimize may pick. It never goes below this, whatever your priority."), + Spec("opt_min_fps", "Minimum frame rate", (30, 60, 90, 120, 144, 165, 240), 60, + {v: f"{v} fps" for v in (30, 60, 90, 120, 144, 165, 240)}, group="Optimize", sub="Your minimums", + help="Frames a second on screen that Optimize must hold, judged by the 1% low (the slowest frames) with " + "about 10% to spare, not the average. More than your display's refresh rate can't be shown."), + Spec("opt_max_delay", "Most added delay", (0, 30, 40, 50, 70, 100), 0, + {0: "No limit", **{v: f"{v} ms" for v in (30, 40, 50, 70, 100)}}, group="Optimize", sub="Your minimums", + help="The most delay Summit itself may add (frame generation adds some). No limit: not checked."), + Spec("opt_priority", "Priority", ("fps", "resolution", "quality", "delay"), "quality", + {"fps": "Frame rate", "resolution": "Resolution", "quality": "Quality", "delay": "Lowest delay"}, + group="Optimize", sub="Then improve", + help="Once your minimums hold, what Optimize raises as far as it goes. Quality follows a fixed ranking: the " + "display's own resolution, then RTX VSR over FSR 1, then Full motion detail, then anti-aliasing. Only " + "Summit's settings are tried: Summit can't change the game's own graphics options."), + Spec("opt_budget", "Time to spend", (60, 120, 180, 300), 120, + {60: "1 minute", 120: "2 minutes", 180: "3 minutes", 300: "5 minutes"}, group="Optimize", sub="Then improve", + help="How long Optimize may take. Each try takes about 7 seconds, one that restarts the pipeline about 20."), +) +SPECS = SPECS + OPTIMIZE_SPECS SPECS = _laid_out(SPECS) BY_KEY = {s.key: s for s in SPECS} @@ -669,6 +693,11 @@ class Settings: print(f"[settings] couldn't save {self.path}: {e}") +def _optimize_registry() -> dict: + from . import optimize + return optimize.registry() + + def specs_json(specs: tuple[Spec, ...] = SPECS) -> dict: """The registry for the launcher's Settings page: every setting with its choices in display order, and where the saved file is. Values are JSON types; the launcher sends a choice back exactly as given here.""" @@ -685,6 +714,7 @@ def specs_json(specs: tuple[Spec, ...] = SPECS) -> dict: "choices": [{"value": v, "name": s.name(v), "hint": s.hints.get(v, "")} for v in s.choices]} for s in specs], "compare": compare.registry(), # --compare's dimensions and choices (framegen/compare.py) + "optimize": _optimize_registry(), # --optimize's grammar and where its results go (framegen/optimize.py) } diff --git a/engine/run.py b/engine/run.py index 1cfe1ad..b6c7b55 100644 --- a/engine/run.py +++ b/engine/run.py @@ -379,6 +379,14 @@ def main() -> int: "write the session summary (JSON and a text table, in Summit's data folder, or beside --results) " "and show a result card for a few seconds. A video file is played in real time and repeated if " "it is shorter.") + ap.add_argument("--optimize", metavar="GOAL", default=None, + help='find settings: "min=1920x1080@60,priority=quality" (priority: fps, resolution, quality or ' + 'delay; optional delay=MS, the most added delay, and display=WxH@HZ instead of the real ' + "screen). Tries Summit's own settings a few seconds each, then shows the best 3 on a card and " + "writes them to Summit's data folder (optimize/, docs/optimizer.md), and beside --results. " + "Needs --display (or --out, 60 fps only). A video file is played in real time and repeated") + ap.add_argument("--optimize-budget", metavar="SECONDS", type=float, default=None, + help="how long --optimize may take (default 120)") ap.add_argument("--result-card", metavar="SECONDS", type=float, default=8.0, help="how long --benchmark's result card stays on screen (default 8; 0 for none)") ap.add_argument("--frametime-log", metavar="CSV", nargs="?", const="auto", default=None, @@ -392,6 +400,17 @@ def main() -> int: ap.error("--benchmark SECONDS: more than 0") if a.benchmark and not (a.display or a.display_cv or a.out): ap.error("--benchmark counts frames as they are shown: add --display (or --out FILE to run without a window)") + opt_goal = None + if a.optimize is not None: + from framegen import optimize as opt_lib + try: + opt_goal = opt_lib.parse_goal(a.optimize) + except ValueError as e: + ap.error(f"--optimize: {e}") + if not (a.display or a.out) or a.display_cv: + ap.error("--optimize measures frames as they are shown: add --display (or --out FILE, 60 fps only)") + if a.benchmark: + ap.error("--optimize and --benchmark: one at a time") if a.output_res is not None and a.output_res != "screen" and parse_res(a.output_res) is None: ap.error(f"--output-res {a.output_res}: a size like 2560x1440 (320x240 to 7680x4320), or 'screen'") if a.hz is not None and not valid_hz(a.hz): @@ -419,7 +438,7 @@ def main() -> int: a.chiaki_decoder = "d3d11va" kind = a.source or ("chiaki" if a.chiaki else "capture" if a.capture is not None else "file" if a.video else None) - if a.benchmark and kind == "file": + if (a.benchmark or a.optimize) and kind == "file": a.realtime = True # a benchmark plays a file the way a game would arrive, not as fast as it can be read picked = kind # as asked for: an app's compressed frames on the tap become "chiaki" below, without chiaki-ng # Test mode ("Simulate a 30 fps game") works with any 60 Hz source; a video file simulates a PS5 by itself @@ -782,7 +801,12 @@ def main() -> int: def save_summary(reason: str) -> str: """The session so far as summit-session-