378 lines
18 KiB
Python
378 lines
18 KiB
Python
"""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 * max(0.1, 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["requirement"] == "low1" and 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)
|
|
self.coll.stage("capture", 1.0, self.t)
|
|
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
|
|
|
|
|
|
# ---- wiring: the pipeline steps the driver, the overlay's Optimize tab ------------------------------------------------------
|
|
def test_the_pipeline_steps_the_driver_and_forwards_optimize_commands():
|
|
from test_stats_pipeline import FakeInterp, FakeSink, FakeSource
|
|
from framegen.pipeline import Pipeline
|
|
from framegen.sources import make_detector
|
|
|
|
class Driver:
|
|
def __init__(self, restart_at):
|
|
self.n, self.at, self.cmds = 0, restart_at, []
|
|
|
|
def step(self, now):
|
|
self.n += 1
|
|
return "restart" if self.n == self.at else None
|
|
|
|
def command(self, cmd):
|
|
self.cmds.append(cmd)
|
|
return None
|
|
|
|
pipe = Pipeline(FakeInterp(), make_detector(FakeSource.info))
|
|
pipe.driver = d = Driver(restart_at=20)
|
|
st = pipe.run(FakeSource(60), FakeSink(cmds=[None, "optimize_cancel"]), settings=Settings(), label="X",
|
|
collector=S.Collector())
|
|
assert st.exit == "restart" and d.n == 20 and d.cmds == ["optimize_cancel"]
|
|
|
|
|
|
def test_the_optimize_tab_has_its_rows_and_actions():
|
|
from framegen.menu import ACTION_HELP, Menu
|
|
st = Settings()
|
|
menu = Menu(st)
|
|
assert "Optimize" in menu.sections()
|
|
assert not any(r.kind == "action" for r in menu.tab_rows("Optimize")) # no Control: no run offered
|
|
state = ["idle"]
|
|
menu.optimizer_state = lambda: state[0]
|
|
rows = menu.tab_rows("Optimize")
|
|
keys = [r.key for r in rows]
|
|
assert {"opt_min_res", "opt_min_fps", "opt_max_delay", "opt_priority", "opt_budget"} <= set(keys)
|
|
assert keys[-1] == "optimize" and all(k in ACTION_HELP for k in ("optimize", "optimize_cancel", "optimize_apply"))
|
|
menu.show("Optimize")
|
|
menu.index = len(rows) - 1
|
|
assert menu.key("enter") == "optimize"
|
|
state[0] = "card"
|
|
assert [r.key for r in menu.tab_rows("Optimize") if r.kind == "action"] == ["optimize_apply", "optimize_cancel"]
|
|
assert list(S_PRIORITIES()) == list(O.PRIORITIES)
|
|
|
|
|
|
def S_PRIORITIES():
|
|
return BY_KEY["opt_priority"].choices
|
|
|
|
|
|
def test_the_warm_up_waits_for_a_backlog_to_drain():
|
|
st = Settings({})
|
|
sess = FakeSession(st)
|
|
r = make_runner(sess)
|
|
sess.run(r, 4.0, until=lambda x: x.state == "warm")
|
|
assert r.state == "warm"
|
|
for _ in range(int(60 * O.WARM_RESTART_S) + 30): # long past the warm-up, but frames still queue 300 ms
|
|
sess.t += 1 / 60
|
|
sess.coll.present(sess.t, False)
|
|
sess.coll.stage("capture", 300.0, sess.t)
|
|
r.step(sess.t)
|
|
assert r.state == "warm"
|
|
for _ in range(90): # the queue drains: a second of short waits and it measures
|
|
sess.t += 1 / 60
|
|
sess.coll.present(sess.t, False)
|
|
sess.coll.stage("capture", 2.0, sess.t)
|
|
r.step(sess.t)
|
|
assert r.state == "measure"
|
|
|
|
|
|
def test_frame_generation_off_keeps_the_ai_settings_and_is_followed_by_2x_if_it_fails():
|
|
m = O.Machine(display=(1920, 1080), display_hz=120, source=(1920, 1080), src_fps=30)
|
|
s = O.Search(O.Goal((1920, 1080), 30, None, "fps"), m, 300, current={"motion": "full", "engine": "torch"})
|
|
gen = s.steps()
|
|
base = next(gen)
|
|
assert base.mult == 1 and base.motion == "full" and base.engine == "torch" # no restart for unused settings
|
|
nxt = gen.send(O.Measurement(fps_avg=30, low1=9, frames=150, took_s=7)) # stalls: fails
|
|
assert nxt.mult == 2 and nxt.motion == "half"
|
|
|
|
|
|
def test_headroom_with_frame_generation_off_suggests_turning_it_on_whole():
|
|
m = O.Machine(display=(1920, 1080), display_hz=120, src_fps=30)
|
|
h = O.headroom(30.0, 0.2, 0.0, {"interp": False, "hz": 60, "output_res": "1920x1080", "scaler": "fsr"}, m)
|
|
first = h["suggestions"][0]
|
|
assert first["set"] == {"interp": True, "hz": 60}
|
|
assert all(BY_KEY[k].accepts(v) for x in h["suggestions"] for k, v in x["set"].items())
|