From 59b97061ca77a60392e8e68117141a24d67c3533 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 26 Nov 2026 06:00:26 +0000 Subject: [PATCH 1/5] Optimize: the search, its verdict, the result file and headroom check (pure, tested with a fake measurer) --- engine/framegen/optimize.py | 992 ++++++++++++++++++++++++++++++++++ engine/tests/test_optimize.py | 289 ++++++++++ 2 files changed, 1281 insertions(+) create mode 100644 engine/framegen/optimize.py create mode 100644 engine/tests/test_optimize.py diff --git a/engine/framegen/optimize.py b/engine/framegen/optimize.py new file mode 100644 index 0000000..7266961 --- /dev/null +++ b/engine/framegen/optimize.py @@ -0,0 +1,992 @@ +"""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 = 100.0, 10.0 # also wait until frames no longer queue (a backlog), at most this 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 ({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 + 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") + 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") # 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) + y["short_by"], y["short_pct"] = _r(by), _r(100 * by / need if need 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" + return Candidate(mult=mult, out=self._sizes[0], scaler="fsr", motion=motion, model=model) + + # -- 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 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 + return Measurement(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] = [] + s = lambda key, value, text: sug.append({"key": key, "value": value, "text": text}) # noqa: E731 + 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: + 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 = "" + return {"state": state, "load_pct": pct, "display_hz": hz, "output_fps": out_fps, "suggestions": sug, + "line": line, "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 + + # -- 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 = "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 = "warm", now, WARM_RESTART_S + return None + if self.state == "warm": + settled = getattr(self.coll, "_cap_last", 0.0) < WARM_CAPTURE_MS or now - self.t_change > self.warm + WARM_MAX_S + if now - self.t_change >= self.warm and settled: + 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 = now - self.t_apply + 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 + + 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.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 diff --git a/engine/tests/test_optimize.py b/engine/tests/test_optimize.py new file mode 100644 index 0000000..87ac7dc --- /dev/null +++ b/engine/tests/test_optimize.py @@ -0,0 +1,289 @@ +"""framegen/optimize.py: the search, the verdict, the result file, the live runner and the headroom check, with a fake +measurer (a made-up cost model, no GPU, no window).""" +from __future__ import annotations + +import json + +import pytest + +from framegen import optimize as O +from framegen import stats as S +from framegen.settings import BY_KEY, Settings + + +# ---- a fake PC: cost of a configuration in ms of work per second -------------------------------------------------------- +def fake_cost(c: O.Candidate, m: O.Machine, speed: float = 1.0) -> float: + target = c.fps(m.src_fps) + gen_per_s = m.src_fps * (c.mult - 1) + ai = {"vfg": 7.0}.get(c.model, 10.0 if c.motion == "full" else 6.0) * (0.88 if c.engine == "trt" else 1.0) + mp = O.px(c.out) / 2.07e6 + up = (0.1 if c.scaler == "fsr" else 0.8 + 0.4 * c.vsr_q) * mp + aa = {"off": 0.0, "fxaa": 0.3, "smaa": 0.8}[c.aa] * mp + return (ai * gen_per_s + (up + aa) * target) / speed + + +def fake_measure(m: O.Machine, speed: float = 1.0, log: list | None = None, seconds: float = 7.0): + def measure(c: O.Candidate) -> O.Measurement: + if log is not None: + log.append(c) + target = c.fps(m.src_fps) + load = fake_cost(c, m, speed) / 1000.0 + avg = target if load <= 1 else target / load + low1 = avg * (1 - max(0.0, load - 0.7)) + frames = int(avg * 5) + dropped = 0 if load < 0.95 else int(frames * (load - 0.9)) + delay = 20 + (15 if c.mult > 2 else 0) + 4 * load + (5 if c.motion == "full" else 0) + return O.Measurement(fps_avg=avg, low1=low1, frames=frames, dropped=dropped, delay_ms=delay, load=load, + stages={"interp": 6.0}, vram_mb=1200.0, seconds=5.0, took_s=seconds) + return measure + + +PC = O.Machine(display=(2560, 1440), display_hz=144, source=(1920, 1080), src_fps=30, vsr=True, trt=True) + + +def search(goal: str, machine: O.Machine = PC, budget: float = 300, speed: float = 1.0, log=None, took: float = 7.0): + g, _ = O.parse_goal(goal) + s = O.Search(g, machine, budget) + return s, O.run_search(s, fake_measure(machine, speed, log, took)) + + +# ---- parsing ------------------------------------------------------------------------------------------------------------- +def test_the_goal_is_read_from_the_command_line_text(): + g, d = O.parse_goal("min=1920x1080@60,priority=quality") + assert g == O.Goal((1920, 1080), 60, None, "quality") and d is None + g, d = O.parse_goal("min=1440p@90, priority=frame-rate, delay=50, display=2560x1440@144") + assert (g.min_res, g.min_fps, g.max_delay_ms, g.priority) == ((2560, 1440), 90, 50.0, "fps") + assert d == ((2560, 1440), 144.0) + for bad in ("min=huge", "priority=speed", "colour=red", "min", "min=1080p@5"): + with pytest.raises(ValueError): + O.parse_goal(bad) + + +# ---- the verdict --------------------------------------------------------------------------------------------------------- +def test_the_average_alone_is_not_enough_the_1pct_low_needs_headroom(): + g = O.Goal((1920, 1080), 60) + c = O.Candidate(mult=3, out=(1920, 1080)) # 90 fps: room above 60 + 10% + good = O.Measurement(fps_avg=90, low1=70, frames=450) + assert O.judge(g, PC, c, good) == [] + low = O.Measurement(fps_avg=90, low1=64, frames=450) # over 60 but not 66 + assert [f["requirement"] for f in O.judge(g, PC, c, low)] == ["low1"] + drops = O.Measurement(fps_avg=90, low1=80, frames=450, dropped=20) + assert [f["requirement"] for f in O.judge(g, PC, c, drops)] == ["dropped"] + few = O.Measurement(fps_avg=90, low1=80, frames=20) + assert O.judge(g, PC, c, few)[0]["requirement"] == "frames" + + +def test_a_display_at_the_minimum_moves_the_headroom_to_the_frame_budget(): + m60 = O.Machine(display=(1920, 1080), display_hz=60, src_fps=30) + g = O.Goal((1920, 1080), 60) + c = O.Candidate(mult=2, out=(1920, 1080)) + assert O.judge(g, m60, c, O.Measurement(fps_avg=60, low1=59, frames=300, load=0.5)) == [] + busy = O.judge(g, m60, c, O.Measurement(fps_avg=60, low1=59, frames=300, load=0.95)) + assert [f["requirement"] for f in busy] == ["load"] + + +def test_delay_limit(): + g = O.Goal((1920, 1080), 60, 30.0) + c = O.Candidate(mult=3, out=(1920, 1080)) + fails = O.judge(g, PC, c, O.Measurement(fps_avg=90, low1=80, frames=450, delay_ms=41)) + assert fails[0]["requirement"] == "delay" and "41" in fails[0]["text"] + + +# ---- the search ---------------------------------------------------------------------------------------------------------- +def test_quality_starts_cheap_then_climbs_the_ranking_in_order(): + log: list = [] + s, r = search("min=1920x1080@60,priority=quality", log=log) + assert log[0] == O.Candidate(mult=2, out=(1920, 1080), scaler="fsr", motion="half") # the cheapest that meets it + best = r["top"][0] + assert r["met"] and best["settings"]["output_res"] == "2560x1440" # the display's own size first + assert best["settings"]["scaler"] == "vsr" and best["settings"]["motion"] == "full" + assert best["settings"]["hz"] == 60 # quality never raises the multiplier + assert s.restarts <= 2 # motion detail is the only restart setting climbed + assert len(r["top"]) <= 3 and r["quality_ranking"] == list(O.QUALITY_RANKING) + for t in r["top"]: # every settings dict is one the engine takes + for k, v in t["settings"].items(): + assert BY_KEY[k].accepts(v), (k, v) + + +def test_frame_rate_stops_at_the_display_refresh_rate(): + m60 = O.Machine(display=(1920, 1080), display_hz=60, source=(1920, 1080), src_fps=30) + log: list = [] + s, r = search("min=1920x1080@60,priority=fps", m60, log=log) + assert max(c.mult for c in log) == 2 # 90 fps would be more than a 60 Hz display shows + m144 = O.Machine(display=(1920, 1080), display_hz=144, source=(1920, 1080), src_fps=30) + s, r = search("min=1920x1080@60,priority=fps", m144) + assert r["top"][0]["settings"]["hz"] == 120 # 4x = 120; 5x = 150 > 144 Hz + + +def test_frame_rate_stops_where_the_card_can_not_keep_up(): + m = O.Machine(display=(1920, 1080), display_hz=240, source=(1920, 1080), src_fps=30) + s, r = search("min=1920x1080@60,priority=fps", m, speed=1.0) + top = r["top"][0]["settings"]["hz"] + assert 60 < top < 240 + assert any(not t["passed"] and t["settings"]["hz"] == top + 30 for t in r["tried"]) + + +def test_a_heavier_candidate_than_a_failure_is_skipped_without_measuring(): + s = O.Search(O.Goal((1920, 1080), 60), PC) + bad = O.Candidate(mult=4, out=(1920, 1080)) + s.tried.append(O.Tried(bad, O.Measurement(frames=500), [{"requirement": "low1", "text": "x"}])) + gen = s._try(O.Candidate(mult=5, out=(2560, 1440)), "test") + with pytest.raises(StopIteration) as e: + next(gen) + assert e.value.value is None and "at least as heavy" in s.skipped[-1]["reason"] + gen = s._try(O.Candidate(mult=3, out=(2560, 1440)), "test") # lighter in one dimension: measured + assert next(gen) == O.Candidate(mult=3, out=(2560, 1440)) + + +def test_nothing_meets_the_minimum_says_what_fails_and_by_how_much(): + s, r = search("min=3840x2160@120,priority=quality", O.Machine(display=(3840, 2160), display_hz=120, src_fps=30), + speed=0.2) + assert not r["met"] and r["top"] == [] + assert r["closest"] is not None and r["failures"] + f = r["failures"][0] + assert f["short_pct"] > 0 and f["text"] + + +def test_a_display_slower_than_the_minimum_is_said_up_front(): + s, r = search("min=1920x1080@120", O.Machine(display=(1920, 1080), display_hz=60, src_fps=30)) + assert not r["met"] and any("60 Hz" in n for n in r["notes"]) + assert any(f["requirement"] == "fps" for f in r["failures"]) + + +def test_the_time_budget_is_kept_and_what_was_left_out_is_said(): + s, r = search("min=1920x1080@60,priority=quality", budget=20, took=7.0) + assert s.elapsed <= 20 + 0.01 and len(r["tried"]) == 2 + assert any("time" in x["reason"] for x in r["skipped"]) + + +def test_lowest_delay_turns_frame_generation_off_when_the_game_is_fast_enough(): + m = O.Machine(display=(1920, 1080), display_hz=60, source=(1920, 1080), src_fps=60) + s, r = search("min=1920x1080@60,priority=delay", m) + assert r["top"][0]["settings"]["interp"] is False + + +def test_lowest_delay_refuses_picture_changes_that_add_delay(): + s, r = search("min=1920x1080@60,priority=delay") + full = [t for t in r["tried"] if t["settings"]["motion"] == "full"] + assert full and all(not t["passed"] for t in full) # +5 ms in the fake model + + +def test_the_result_file_has_a_version_and_is_json(tmp_path): + s, r = search("min=1920x1080@60,priority=resolution") + p = O.write_result(r, tmp_path) + back = json.loads(p.read_text()) + assert back["format"] == "summit-optimize" and back["version"] == 1 + assert json.loads((tmp_path / "latest.json").read_text()) == back + assert back["top"][0]["settings"]["output_res"] == "2560x1440" + assert {"fps_avg", "low1", "delay_ms", "stages", "vram_mb", "load"} <= set(back["top"][0]["measured"]) + assert "Tried:" in O.format_text(back) + + +# ---- the live runner, with the real collector and settings -------------------------------------------------------------- +class FakeSession: + """Feeds the real stats.Collector 60 frames a second, at a frame rate that depends on the settings.""" + + def __init__(self, settings: Settings) -> None: + self.settings, self.coll, self.t = settings, S.Collector(window_s=30), 100.0 + self.started = {k: settings.values()[k] for k in O.RESTART_KEYS} + self.restarts = 0 + + def restart_needed(self) -> bool: + return any(self.settings.values()[k] != v for k, v in self.started.items()) + + def run(self, runner: O.Runner, seconds: float, until=None) -> list: + cmds = [] + end = self.t + seconds + while self.t < end: + fps = 30 * (self.settings.hz // 30 if self.settings.interp else 1) + self.t += 1.0 / fps + self.coll.present(self.t, False) + cmd = runner.step(self.t) + if cmd: + cmds.append(cmd) + if cmd == "restart": + self.restarts += 1 + self.started = {k: self.settings.values()[k] for k in O.RESTART_KEYS} + self.t += 3.0 + if until is not None and until(runner): + break + return cmds + + +def make_runner(sess: FakeSession, goal="min=1920x1080@60,priority=quality", budget=60.0, card_s=None, saved=None): + g, _ = O.parse_goal(goal) + m = O.Machine(display=(1920, 1080), display_hz=60, source=(1920, 1080), src_fps=30) + return O.Runner(O.Search(g, m, budget), sess.settings, sess.coll, sess.restart_needed, + on_result=lambda r: saved.append(r) or "here" if saved is not None else "here", card_s=card_s, + clock=lambda: sess.t) + + +def test_cancel_puts_every_setting_back_exactly(tmp_path): + st = Settings({"scaler": "bilinear", "motion": "full", "hz": 90, "aa": "cas", "output_res": "screen"}, + tmp_path / "s.json") + st.override("interp", False) + before, saved_file = st.values(), st._saved.copy() + sess = FakeSession(st) + r = make_runner(sess) + sess.run(r, 20) + assert st.values() != before and r.state in ("warm", "measure", "restarting") + r.command("optimize_cancel") + sess.run(r, 1) + assert st.values() == before and st._saved == saved_file # nothing was saved either + assert r.result["cancelled"] and r.state == "done" + + +def test_a_full_run_shows_the_best_and_apply_saves_it(tmp_path): + st = Settings({}, tmp_path / "s.json") + sess, saved = FakeSession(st), [] + r = make_runner(sess, saved=saved) + cmds = sess.run(r, 200, until=lambda x: x.state == "card") + assert r.state == "card" and saved and saved[0]["tried"] + assert all(t["measured"]["frames"] >= O.MIN_FRAMES for t in saved[0]["tried"]) + top = r.result["top"][0]["settings"] + assert all(st.values()[k] == v for k, v in top.items()) # previewed + r.command("optimize_apply") + on_disk = json.loads((tmp_path / "s.json").read_text()) + assert all(on_disk[k] == v for k, v in top.items()) + assert "restart" in cmds or sess.restarts == 0 + + +def test_a_command_line_run_quits_after_its_card(): + st = Settings({}) + sess = FakeSession(st) + r = make_runner(sess, card_s=3.0) + cmds = sess.run(r, 300, until=lambda x: x.state == "done") + assert cmds[-1] == "quit" + + +# ---- headroom ------------------------------------------------------------------------------------------------------------ +def test_headroom_on_a_60hz_display_suggests_a_better_picture(): + m = O.Machine(display=(2560, 1440), display_hz=60, src_fps=30, vsr=True) + h = O.headroom(60.0, 0.4, 0.0, {"interp": True, "hz": 60, "output_res": "1920x1080", "scaler": "fsr", + "motion": "half", "aa": "off"}, m) + assert h["state"] == "room" and "60 Hz" in h["line"] and "40%" in h["line"] + keys = [s["key"] for s in h["suggestions"]] + assert "hz" not in keys # 90 fps can't be shown at 60 Hz + assert {"output_res", "scaler", "motion", "aa"} <= set(keys) + + +def test_headroom_when_falling_behind_suggests_lighter_settings(): + m = O.Machine(display=(1920, 1080), display_hz=144, src_fps=30) + h = O.headroom(90.0, 0.97, 0.05, {"interp": True, "hz": 120, "output_res": "1920x1080", "scaler": "vsr", + "motion": "full", "aa": "smaa"}, m) + assert h["state"] == "behind" + assert [s["key"] for s in h["suggestions"]][:2] == ["motion", "scaler"] + + +def test_headroom_says_when_the_multiplier_is_more_than_the_display_shows(): + m = O.Machine(display=(1920, 1080), display_hz=60, src_fps=30) + h = O.headroom(119.0, 0.5, 0.0, {"interp": True, "hz": 120, "output_res": "1920x1080", "scaler": "fsr"}, m) + assert h["suggestions"][0]["key"] == "hz" and h["suggestions"][0]["value"] == 60 + + +def test_headroom_reads_a_real_session_summary(): + from pathlib import Path + p = Path(__file__).resolve().parents[2] / "docs/media/stats/real-session-summary.json" + summ = json.loads(p.read_text()) + h = O.headroom_of_summary(summ, O.Machine(display=(1280, 720), display_hz=60, src_fps=30)) + assert h["state"] in ("room", "fits", "behind") and h["load_pct"] is not None From 6b61636afe3ff45907b11bfa45455ffea2f9a900 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 26 Nov 2026 06:05:13 +0000 Subject: [PATCH 2/5] Optimize: --optimize, the overlay's Optimize tab, the countdown, the result card with Apply/Cancel, headroom in summaries --- engine/framegen/io.py | 47 ++++++++++++++++ engine/framegen/menu.py | 20 ++++++- engine/framegen/optimize.py | 83 +++++++++++++++++++++++++++- engine/framegen/pipeline.py | 8 +++ engine/framegen/settings.py | 30 ++++++++++ engine/run.py | 101 +++++++++++++++++++++++++++++++++- engine/tests/test_optimize.py | 53 +++++++++++++++++- 7 files changed, 334 insertions(+), 8 deletions(-) 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 index 7266961..f7babfb 100644 --- a/engine/framegen/optimize.py +++ b/engine/framegen/optimize.py @@ -316,7 +316,8 @@ def shortfall(fails: list[dict]) -> list[dict]: 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) - y["short_by"], y["short_pct"] = _r(by), _r(100 * by / need if need else None) + 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 @@ -712,8 +713,10 @@ def headroom(fps_avg: float | None, load: float | None, dropped_share: float, se 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, "note": "Suggestions only; nothing is changed without you. Estimates: Optimize measures."} + "line": line, "short": short, "note": "Suggestions only; nothing is changed without you. Estimates: Optimize measures."} def headroom_of_summary(summary: dict, machine: Machine) -> dict: @@ -953,6 +956,8 @@ class Control: 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 @@ -961,6 +966,9 @@ class Control: 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: @@ -990,3 +998,74 @@ class Control: 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", card memory {me['vram_mb'] / 1024:.1f} GB" 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/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..13f554b 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-