mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
tune: an account of every tune is saved and strata tune report shows it; progress says "run N of M" (#5232, report and progress)
After a tune that changed nothing there was nothing to read: the result holds every setting's outcome, the skipped ones with reasons and the noise
figures, but only four lines were shown and the temp folder went with the run. Now (words approved by the coordinator):
- tune_report.build() turns the result the tuner already holds into plain lines: what your settings measured (answers and prompts, the runs), the bar a
setting had to clear and the noise it had to beat, one verdict per setting tried, what was left out and why, and one next step for every way a tune
can end. It is saved after every tune as last-tune-report.txt in the presets folder (private_files.restrict_to_current_user: 0600 / a DACL for this
user on Windows; no argument lists, paths or keys) and printed again by `strata tune report` ("No tune has been run yet." when there is none;
--output json gives {"report": text|null}).
- `strata tune auto` points to it on its last line ("Why each setting was or was not chosen: strata tune report"; human output only).
- the progress lines say which run of how many ("run 3 of 9").
- the tune's noise gains "threshold_pct" (the bar a setting had to clear); nothing is removed or renamed in the JSON the app reads.
Not taken from the issue (a later step): the Markdown form for a [Benchmark] report and suggestions from stored benchmark data. The author's fork branch
is not reachable, so this is written from the issue's text and example.
Tests: tests/tuning/test_tune_report.py (9): collection fails on efdde5c31 (no tune_report module), 361 passed with the change in a clean tree (p1006).
This commit is contained in:
1 parent
efdde5c316
commit
0e7d5ca9c7
5 files changed
+295
-2
No files matched your search
@@ -1672,6 +1672,9 @@ def _tune(a: argparse.Namespace) -> int:
|
||||
if a.tune_command == "auto":
|
||||
return tune_commands.auto(a)
|
||||
|
||||
if a.tune_command == "report":
|
||||
return tune_commands.report(a)
|
||||
|
||||
if a.tune_command == "list":
|
||||
root = state_root()
|
||||
jobs = []
|
||||
|
||||
@@ -46,6 +46,8 @@ def add_tune_auto(tune_sp: argparse._SubParsersAction) -> None:
|
||||
p.add_argument("--status-file", default=None, help="progress as JSON, rewritten at every step (for the desktop app)")
|
||||
p.add_argument("--boot-timeout", type=float, default=900.0)
|
||||
p.add_argument("--output", choices=("human", "json"), default="human")
|
||||
rp = tune_sp.add_parser("report", help="show the account of the last tune")
|
||||
rp.add_argument("--output", choices=("human", "json"), default="human")
|
||||
|
||||
|
||||
def add_presets(sp: argparse._SubParsersAction) -> None:
|
||||
@@ -217,6 +219,22 @@ def _keep_failed_log(session: Any) -> Path | None:
|
||||
return None
|
||||
|
||||
|
||||
def run_words(p: dict[str, Any]) -> str:
|
||||
"""#5232: "run 3 of 9" for a progress line (the run that is being measured, of those planned); nothing while the plan is not known."""
|
||||
planned = int(p.get("runs_planned") or 0)
|
||||
return f"run {min(int(p.get('runs_done') or 0) + 1, planned)} of {planned}" if planned else ""
|
||||
|
||||
|
||||
def report(a: argparse.Namespace) -> int:
|
||||
"""`strata tune report`: the account of the last tune, as it was saved after that tune (strata_control/tune_report.py)."""
|
||||
from strata_control import tune_report
|
||||
text = tune_report.read()
|
||||
if a.output == "json":
|
||||
return _print({"report": text}, True, "")
|
||||
print(text if text else tune_report.NONE_YET, end="" if text else "\n")
|
||||
return 0
|
||||
|
||||
|
||||
def _write_status(path: str | None, payload: dict[str, Any]) -> None:
|
||||
if not path:
|
||||
return
|
||||
@@ -288,7 +306,8 @@ def auto(a: argparse.Namespace) -> int:
|
||||
state["text"] = (f"Finding the fastest settings for your PC… {minutes_text(p.get('eta_s'))}"
|
||||
if p.get("eta_s") is not None else "Finding the fastest settings for your PC…")
|
||||
_write_status(a.status_file, state)
|
||||
say(f"[{p.get('elapsed_s', 0) // 60:>3d}m] {p['message']}" + (f" ({minutes_text(p['eta_s'])})" if p.get("eta_s") else ""))
|
||||
brackets = ", ".join(x for x in (run_words(p), minutes_text(p["eta_s"]) if p.get("eta_s") else "") if x)
|
||||
say(f"[{p.get('elapsed_s', 0) // 60:>3d}m] {p['message']}" + (f" ({brackets})" if brackets else ""))
|
||||
|
||||
workdir = Path(a.work_dir) if a.work_dir else Path(tempfile.mkdtemp(prefix="strata-tune-"))
|
||||
if not a.work_dir:
|
||||
@@ -333,12 +352,14 @@ def auto(a: argparse.Namespace) -> int:
|
||||
autotune.Tuner.finalize(result)
|
||||
out.update({"code": result.code, "reason_code": result.reason_code, "values": result.values})
|
||||
out["values"]["preset_name"] = saved["name"] if saved else None
|
||||
from strata_control import tune_report
|
||||
account_saved = tune_report.save(tune_report.build(out, saved["name"] if saved else None))
|
||||
state.update({"state": "done", "result": out, "stage": "done"})
|
||||
_write_status(a.status_file, state)
|
||||
if machine:
|
||||
print(json.dumps({"schema_version": 1, "ok": True, "result": out}, ensure_ascii=False, default=str))
|
||||
else:
|
||||
print(_human_result(out, saved))
|
||||
print(_human_result(out, saved) + (f"\n {tune_report.POINTER}" if account_saved else ""))
|
||||
return {"improved": 0, "default_confirmed": 0, "cancelled": 130}.get(result.outcome, 6)
|
||||
|
||||
|
||||
|
||||
@@ -531,6 +531,7 @@ class Tuner:
|
||||
r.noise = {"aa_gap": round(aa, 4), "drift": round(drift, 4), "spread": round(spread, 4),
|
||||
"base_runs": [round(x, 2) for x in mb], "noisy": spread > STAGE_GAP_NOISY}
|
||||
threshold = accept_threshold(o.margin, aa, drift)
|
||||
r.noise["threshold_pct"] = round((threshold - 1.0) * 100.0, 1) # the bar a setting had to clear (shown by `strata tune report`)
|
||||
|
||||
# ---- evaluate the candidates
|
||||
winners: list[ArmReport] = []
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The account of a tune (#5232): what your settings measured, what a setting had to beat, what was tried and what was left out, and one next step.
|
||||
|
||||
Built from the result the tuner already holds (``autotune.TuneResult.to_dict()``), so nothing is measured again; saved privately after every tune
|
||||
(``last-tune-report.txt`` in the presets folder, no argument lists, no paths, no keys) and printed again by ``strata tune report``."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
FILE_NAME = "last-tune-report.txt"
|
||||
NONE_YET = "No tune has been run yet."
|
||||
#: the last line of `strata tune auto`'s own answer
|
||||
POINTER = "Why each setting was or was not chosen: strata tune report"
|
||||
|
||||
|
||||
def _rate(value: Any) -> str | None:
|
||||
try:
|
||||
return f"{float(value):.1f}" if value else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _runs_text(runs: Any) -> str:
|
||||
vals = [f"{float(x):g}" for x in (runs or []) if isinstance(x, (int, float))]
|
||||
return f" (measured {len(vals)} times: {', '.join(vals)})" if len(vals) >= 2 else ""
|
||||
|
||||
|
||||
def _verdict(arm: dict[str, Any]) -> str:
|
||||
status = arm.get("status")
|
||||
ratio = arm.get("ratio_decode")
|
||||
pairs, faster = int(arm.get("pairs") or 0), int(arm.get("faster") or 0)
|
||||
against = f"{(ratio - 1.0) * 100:+.1f}% against your settings, faster in {faster} of {pairs} rounds" if ratio and pairs else ""
|
||||
if status == "failed":
|
||||
return f"could not run: {arm.get('reason') or 'the engine stopped'}"
|
||||
if arm.get("won"):
|
||||
return f"faster, {against}" if against else "faster"
|
||||
if status == "dropped":
|
||||
return "slower, stopped after one round"
|
||||
return f"not faster by enough: {against}" if against else "not faster by enough"
|
||||
|
||||
|
||||
def _next_step(r: dict[str, Any], name: str | None) -> str:
|
||||
outcome = r.get("outcome")
|
||||
if outcome == "improved":
|
||||
return (f"'{name}' is applied at every start. See it with 'strata presets show', or go back with 'strata presets undo'." if name
|
||||
else "The faster settings were not saved.")
|
||||
if outcome == "default_confirmed":
|
||||
return "Nothing was changed. Your settings are already the fastest of what was tried."
|
||||
if outcome == "inconclusive":
|
||||
return "Nothing was changed. Close other programs and tune again."
|
||||
if outcome == "base_failed":
|
||||
return "Nothing was changed. Fix the problem above and tune again."
|
||||
return "Nothing was changed."
|
||||
|
||||
|
||||
def build(result: dict[str, Any], preset_name: str | None = None) -> str:
|
||||
"""The account, as plain lines. ``result`` is ``TuneResult.to_dict()`` (also the dict the app reads)."""
|
||||
base = result.get("base") or {}
|
||||
noise = result.get("noise") or {}
|
||||
lines: list[str] = []
|
||||
decode, prompt = _rate(base.get("decode_tok_s")), _rate(base.get("pp_tok_s"))
|
||||
if decode:
|
||||
lines.append(f"Your settings: answers at {decode} tok/s" + (f", prompts read at {prompt} tok/s" if prompt else "") + _runs_text(noise.get("base_runs")))
|
||||
if noise.get("threshold_pct") is not None:
|
||||
lines.append(f"To count, a setting had to be at least +{float(noise['threshold_pct']):.1f}% faster; identical runs on this PC differed by "
|
||||
f"{float(noise.get('aa_gap') or 0.0) * 100:.1f}%.")
|
||||
elif result.get("message"):
|
||||
lines.append(str(result["message"]))
|
||||
arms = [a for a in result.get("arms") or [] if a.get("status") != "skipped"]
|
||||
if arms:
|
||||
lines.append("What was tried:")
|
||||
lines += [f" {a.get('label') or a.get('id')} {_verdict(a)}" for a in arms]
|
||||
skipped = [s for s in result.get("skipped") or [] if s.get("label")]
|
||||
if skipped:
|
||||
lines.append("Left out:")
|
||||
lines += [f" {s['label']}: {s.get('reason', '')}".rstrip(": ") for s in skipped]
|
||||
lines.append("Next: " + _next_step(result, preset_name))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def report_path() -> Path:
|
||||
from strata_control import presets
|
||||
return presets.preset_dir() / FILE_NAME
|
||||
|
||||
|
||||
def save(text: str) -> Path | None:
|
||||
"""Write the account privately (0600 where the system has modes), replacing the last one. None when the folder cannot be written."""
|
||||
try:
|
||||
from strata_control import presets
|
||||
path = report_path()
|
||||
presets._atomic(path, text.encode("utf-8")) # noqa: SLF001 - the presets folder's own atomic write
|
||||
from strata_control import private_files
|
||||
private_files.restrict_to_current_user(path) # 0600, or a DACL for this user only on Windows, as the other private files
|
||||
return path
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def read() -> str | None:
|
||||
try:
|
||||
return report_path().read_text(encoding="utf-8")
|
||||
except OSError:
|
||||
return None
|
||||
@@ -0,0 +1,163 @@
|
||||
"""#5232: the account of a tune (strata_control/tune_report.py), the file it is saved in, `strata tune report`, and the run counts in the progress lines.
|
||||
Doubles only."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from strata_control import autotune, tune_report
|
||||
from tests.tuning.stub_session import FakeClock, StubSession
|
||||
from tests.tuning.test_autotune import BASE, make_ctx, run_tuner, speed_with
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def result(**kw):
|
||||
r = {"outcome": "improved", "message": "", "base": {"decode_tok_s": 60.0, "pp_tok_s": 1500.0},
|
||||
"noise": {"base_runs": [60.0, 60.04, 59.98], "aa_gap": 0.001, "threshold_pct": 3.0},
|
||||
"arms": [{"id": "kv", "label": "Keep more of the conversation in graphics memory", "status": "tested", "ratio_decode": 1.10, "pairs": 2,
|
||||
"faster": 2, "won": True, "reason": ""},
|
||||
{"id": "pf", "label": "Bigger prompt chunks", "status": "tested", "ratio_decode": 1.012, "pairs": 2, "faster": 1, "won": False, "reason": ""},
|
||||
{"id": "sp", "label": "Longer drafts", "status": "dropped", "ratio_decode": 0.9, "pairs": 1, "faster": 0, "won": False, "reason": ""},
|
||||
{"id": "x", "label": "Another setting", "status": "failed", "pairs": 0, "faster": 0, "won": False, "reason": "the engine stopped"}],
|
||||
"skipped": [{"label": "Faster but different answers", "reason": "it can change the answers; allowed with --allow-small-differences"}]}
|
||||
r.update(kw)
|
||||
return r
|
||||
|
||||
|
||||
class Account(unittest.TestCase):
|
||||
def test_the_account_has_every_part(self):
|
||||
text = tune_report.build(result(), "IQ3_XXS 128K")
|
||||
self.assertEqual(text.splitlines(), [
|
||||
"Your settings: answers at 60.0 tok/s, prompts read at 1500.0 tok/s (measured 3 times: 60, 60.04, 59.98)",
|
||||
"To count, a setting had to be at least +3.0% faster; identical runs on this PC differed by 0.1%.",
|
||||
"What was tried:",
|
||||
" Keep more of the conversation in graphics memory faster, +10.0% against your settings, faster in 2 of 2 rounds",
|
||||
" Bigger prompt chunks not faster by enough: +1.2% against your settings, faster in 1 of 2 rounds",
|
||||
" Longer drafts slower, stopped after one round",
|
||||
" Another setting could not run: the engine stopped",
|
||||
"Left out:",
|
||||
" Faster but different answers: it can change the answers; allowed with --allow-small-differences",
|
||||
"Next: 'IQ3_XXS 128K' is applied at every start. See it with 'strata presets show', or go back with 'strata presets undo'."])
|
||||
|
||||
def test_one_next_step_for_every_way_a_tune_ends(self):
|
||||
said = {o: tune_report.build(result(outcome=o, arms=[], skipped=[]), None).splitlines()[-1] for o in
|
||||
("improved", "default_confirmed", "inconclusive", "base_failed", "cancelled")}
|
||||
self.assertEqual(said["default_confirmed"], "Next: Nothing was changed. Your settings are already the fastest of what was tried.")
|
||||
self.assertEqual(said["inconclusive"], "Next: Nothing was changed. Close other programs and tune again.")
|
||||
self.assertEqual(said["base_failed"], "Next: Nothing was changed. Fix the problem above and tune again.")
|
||||
self.assertEqual(said["cancelled"], "Next: Nothing was changed.")
|
||||
self.assertTrue(said["improved"].startswith("Next: The faster settings were not saved."))
|
||||
self.assertEqual(len(set(said.values())), 5)
|
||||
|
||||
def test_a_failed_baseline_says_why_and_holds_no_paths_or_keys(self):
|
||||
text = tune_report.build(result(outcome="base_failed", base={}, noise={}, arms=[], skipped=[],
|
||||
message="Your current settings could not be measured: the engine stopped"))
|
||||
self.assertIn("could not be measured", text)
|
||||
self.assertNotIn("args", text.lower())
|
||||
|
||||
|
||||
class SavedAndShown(unittest.TestCase):
|
||||
def test_saved_privately_and_read_again(self):
|
||||
with tempfile.TemporaryDirectory() as d, mock.patch.dict(os.environ, {"STRATA_PRESET_DIR": d}):
|
||||
self.assertIsNone(tune_report.read())
|
||||
path = tune_report.save("an account\n")
|
||||
self.assertEqual(path, Path(d) / "last-tune-report.txt")
|
||||
self.assertEqual(tune_report.read(), "an account\n")
|
||||
tune_report.save("a newer one\n")
|
||||
self.assertEqual(tune_report.read(), "a newer one\n")
|
||||
if os.name != "nt":
|
||||
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||
else:
|
||||
from strata_control import private_files
|
||||
self.assertTrue(private_files.is_private(path))
|
||||
|
||||
def test_the_command_prints_it_or_says_no_tune_has_been_run(self):
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
env = dict(os.environ, STRATA_PRESET_DIR=d, PYTHONPATH=str(ROOT))
|
||||
run = lambda: subprocess.run([sys.executable, str(ROOT / "strata.py"), "tune", "report"], capture_output=True, text=True, env=env, # noqa: E731
|
||||
cwd=str(ROOT), timeout=120)
|
||||
first = run()
|
||||
self.assertEqual((first.returncode, first.stdout.strip()), (0, "No tune has been run yet."))
|
||||
as_json = subprocess.run([sys.executable, str(ROOT / "strata.py"), "tune", "report", "--output", "json"], capture_output=True, text=True,
|
||||
env=env, cwd=str(ROOT), timeout=120)
|
||||
self.assertIn('"report": null', as_json.stdout)
|
||||
(Path(d) / "last-tune-report.txt").write_text("Your settings: x\n", encoding="utf-8")
|
||||
self.assertEqual(run().stdout, "Your settings: x\n")
|
||||
|
||||
|
||||
class AutoKeepsTheAccount(unittest.TestCase):
|
||||
"""`strata tune auto` saves the account after the run and says where to read it; the JSON answer is not given the extra line."""
|
||||
|
||||
def run_auto(self, *extra, outcome_stub=None):
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
from contextlib import redirect_stdout
|
||||
from strata_cli import tune_commands as TC
|
||||
_t, _s, res = run_tuner(speed_with({("--kv-resident", "65536"): 1.10}))
|
||||
|
||||
class FakeTuner(autotune.Tuner):
|
||||
def __init__(self, *a, **kw):
|
||||
self.result = res
|
||||
|
||||
def run(self):
|
||||
return res
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
t = Path(d)
|
||||
(t / "engine.exe").write_bytes(b"x")
|
||||
(t / "model.gguf").write_bytes(b"gguf" * 100)
|
||||
(t / "tok").mkdir()
|
||||
cfg = t / "strata-model.json"
|
||||
cfg.write_text(json.dumps({"exe": str(t / "engine.exe"), "tokenizer": str(t / "tok"), "model_name": "iq3_s-test",
|
||||
"args": ["--native", str(t / "model.gguf"), "--max-context", "65536", "--kv-resident", "32768"]}))
|
||||
ap = argparse.ArgumentParser()
|
||||
TC.add_tune_auto(ap.add_subparsers(dest="c"))
|
||||
a = ap.parse_args(["auto", str(cfg), "--no-save", "--work-dir", str(t / "work"), *extra])
|
||||
out = io.StringIO()
|
||||
with mock.patch.dict(os.environ, {"STRATA_PRESET_DIR": str(t / "presets")}), \
|
||||
mock.patch("strata_control.tuning.engine_flag_inventory", return_value=None), \
|
||||
mock.patch("strata_control.tune_session.WorkerSession", return_value=mock.Mock(failed_log=None)), \
|
||||
mock.patch.object(autotune, "Tuner", FakeTuner), \
|
||||
redirect_stdout(out):
|
||||
code = TC.auto(a)
|
||||
saved = (t / "presets" / "last-tune-report.txt")
|
||||
return code, out.getvalue(), (saved.read_text(encoding="utf-8") if saved.exists() else None)
|
||||
|
||||
def test_the_account_is_saved_and_the_answer_points_to_it(self):
|
||||
code, said, saved = self.run_auto()
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("Your settings: answers at ", saved)
|
||||
self.assertIn("What was tried:", saved)
|
||||
self.assertTrue(said.rstrip().endswith("Why each setting was or was not chosen: strata tune report"))
|
||||
|
||||
def test_the_json_answer_stays_as_it_was(self):
|
||||
import json
|
||||
code, said, saved = self.run_auto("--output", "json")
|
||||
self.assertEqual(code, 0)
|
||||
self.assertTrue(saved)
|
||||
self.assertTrue(json.loads(said)["ok"])
|
||||
self.assertNotIn("strata tune report", said)
|
||||
|
||||
|
||||
class Progress(unittest.TestCase):
|
||||
def test_the_noise_carries_the_bar_a_setting_had_to_clear(self):
|
||||
_t, _s, r = run_tuner(speed_with({("--kv-resident", "65536"): 1.10}))
|
||||
self.assertEqual(r.noise["threshold_pct"], round((autotune.accept_threshold(0.03, r.noise["aa_gap"], r.noise["drift"]) - 1.0) * 100, 1))
|
||||
self.assertGreaterEqual(r.noise["threshold_pct"], 3.0)
|
||||
|
||||
def test_progress_lines_say_which_run_of_how_many(self):
|
||||
from strata_cli import tune_commands as TC
|
||||
self.assertEqual(TC.run_words({"runs_done": 2, "runs_planned": 9}), "run 3 of 9")
|
||||
self.assertEqual(TC.run_words({"runs_done": 9, "runs_planned": 9}), "run 9 of 9")
|
||||
self.assertEqual(TC.run_words({"runs_done": 0, "runs_planned": 0}), "")
|
||||
self.assertEqual(TC.run_words({}), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user