1111 lines
58 KiB
Python
1111 lines
58 KiB
Python
"""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-<stamp>.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)
|