mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 23:08:36 +00:00
tune: strata tune auto --concurrency N judges every setting on N requests decoding at once (opt-in); a load-tuned preset is applied only to starts that run requests together (#4821)
The tuner started the worker with the request slots but sent one request at a time, so a setting that only shows under load (the issue's numbers: pipelined
groups, +20% at 4 streams, +0% solo) could not win. Opt-in, and without the flag nothing changes (no loaded phase, the same metric, the same preset key):
- `--concurrency N` (2 to 8; anything else: "--concurrency is a number of requests from 2 to 8"): the worker config gets "parallel": N, each engine run gets a
loaded phase after the solo one (N requests at once, 3 rounds, all their tokens per second, the median; RunResult.load_tok_s), and the tuner's metric is
that rate (autotune.metric), with the same A/A noise rules and thresholds. An engine that logs fewer batch_slots than asked stops the tune with the number
it got and one next step. The result, the saved preset's choices ("concurrency") and the account name N ("Measured with N requests at once.").
- presets.overlay: a preset whose choices say concurrency N >= 2 is not applied to a start that runs one request (config "parallel" / --batch / --slots
below 2): the solo preset it replaced ("previous") stands in when there is one, else `presets effective` says "not applied: it was tuned for N requests at
once, and this start runs one request at a time" (a why_not that was in the JSON only is now also a line of the human answer). The key of a preset is
unchanged, so no existing preset stops applying.
Words approved by the coordinator (C1-C4, W1). The batch settings the issue names (--batch-groups, --batch-mtp, STRATA_PIPED_MTP) are not added as
candidates here: that needs the loaded A/B this change makes possible, on a box with the slots (0.2.17).
Tests (tests/tuning/test_tune_concurrency.py, 17): 15 fail and 2 pass on 0e7d5ca9c with the new test files (p1006-20261117-0833-e1eb), all pass with the
change; tests/tuning + test_calibration 378 passed (p1006-20261117-0842-3607). Gated in a clean tree (0e7d5ca9c + exactly these files) with tools/check on
l620 (l620-20261117-0844-fab8): py-tests 3830 passed, py-serve 1839 passed, py-tools 1725 passed, 0 failed.
Real run (l620-20261117-0833-2571, the shared BASE-05 IQ3_S setup read only, `tune auto --concurrency 4 --time 14`): 4 slots, 261.6 tok/s in all against
155.1 tok/s solo, 7 engine runs with "run N of 7", "already the fastest" (both candidates -0.6% / -1.3% under load), the account saved with mode 0600.
This commit is contained in:
1 parent
0e7d5ca9c7
commit
0d23ecda31
7 files changed
+399
-6
No files matched your search
@@ -32,6 +32,8 @@ def add_tune_auto(tune_sp: argparse._SubParsersAction) -> None:
|
||||
"(leave that much graphics memory free)")
|
||||
p.add_argument("--leave-ram", type=int, default=0, metavar="PERCENT", help="leave this share of system memory free (0-50)")
|
||||
p.add_argument("--use", choices=("chat", "coding"), default="chat", help="coding judges long-prompt speed as well")
|
||||
p.add_argument("--concurrency", type=int, default=1, metavar="N",
|
||||
help="judge every setting on N requests at once (2 to 8), not one at a time; for a model that serves several people or agents together")
|
||||
p.add_argument("--allow-small-differences", action="store_true",
|
||||
help="also try settings that can change answers slightly (expert cache split, speculative window)")
|
||||
p.add_argument("--allow-not-repeatable", action="store_true", help="also try settings whose answers are not repeatable")
|
||||
@@ -274,6 +276,10 @@ def auto(a: argparse.Namespace) -> int:
|
||||
return _fail("--leave-ram is a percentage from 0 to 50", 2, machine)
|
||||
if a.leave_ram and goal == "speed":
|
||||
goal = "room"
|
||||
concurrency = getattr(a, "concurrency", 1)
|
||||
concurrency = 1 if concurrency is None else int(concurrency)
|
||||
if concurrency != 1 and not 2 <= concurrency <= 8:
|
||||
return _fail("--concurrency is a number of requests from 2 to 8", 2, machine)
|
||||
exe = _engine_exe(cfg)
|
||||
if not Path(exe).exists():
|
||||
return _fail(f"no engine was found at {exe}", 5, machine)
|
||||
@@ -282,7 +288,7 @@ def auto(a: argparse.Namespace) -> int:
|
||||
flags = tuning.engine_flag_inventory(Path(exe), wanted=tuning.dimension_flags() | tune_knobs.arm_flags())
|
||||
opts = autotune.Options(mode=a.mode, goal=goal, reserve_mib=reserve, ram_wish_pct=a.leave_ram, use=a.use,
|
||||
allow_placement=a.allow_small_differences, allow_nonrepeatable=a.allow_not_repeatable,
|
||||
budget_s=(a.minutes * 60.0 if a.minutes else None), check_busy=not a.no_quiet_check)
|
||||
budget_s=(a.minutes * 60.0 if a.minutes else None), check_busy=not a.no_quiet_check, concurrency=concurrency)
|
||||
ctx = autotune.context_from_config(cfg, engine_backend=backend, opts=opts, engine_flags=flags)
|
||||
hw = _hw_hash(identity)
|
||||
digest = (identity.get("model") or {}).get("sha256_shard1")
|
||||
@@ -312,7 +318,8 @@ def auto(a: argparse.Namespace) -> int:
|
||||
workdir = Path(a.work_dir) if a.work_dir else Path(tempfile.mkdtemp(prefix="strata-tune-"))
|
||||
if not a.work_dir:
|
||||
atexit.register(shutil.rmtree, workdir, True) # its own scratch folder goes with the run (--work-dir keeps the logs)
|
||||
session = WorkerSession(base_config=cfg, python=sys.executable, serve_dir=_serve_dir(a), workdir=workdir,
|
||||
worker_cfg = {**cfg, "parallel": concurrency} if concurrency > 1 else cfg # #4821: the worker holds as many request slots as the tune asks for
|
||||
session = WorkerSession(base_config=worker_cfg, python=sys.executable, serve_dir=_serve_dir(a), workdir=workdir,
|
||||
boot_timeout_s=a.boot_timeout, lock=_lock_factory(a, say), log=say)
|
||||
base_args = [str(x) for x in cfg.get("args") or []]
|
||||
# the wish becomes part of the base: leave-room asks the engine for the reserve if the configuration has none yet
|
||||
@@ -335,6 +342,8 @@ def auto(a: argparse.Namespace) -> int:
|
||||
out = result.to_dict()
|
||||
choices = presets.choices_from_config(cfg, use=a.use)
|
||||
choices["goal"], choices["reserve_mib"] = goal, reserve
|
||||
if concurrency > 1:
|
||||
choices["concurrency"] = concurrency # presets.overlay applies such a preset only to a start that runs requests together
|
||||
if a.leave_ram:
|
||||
choices["leave_ram_pct"] = a.leave_ram
|
||||
saved = None
|
||||
@@ -388,6 +397,8 @@ def _human_result(r: dict[str, Any], saved: dict[str, Any] | None) -> str:
|
||||
s = r["settings"]
|
||||
shown = {**{k: v for k, v in s["args"].items()}, **s["env"], **{f"per request {k}": v for k, v in s["per_request"].items()}}
|
||||
lines.append(" Changed: " + ", ".join(f"{k} {v}" for k, v in shown.items()))
|
||||
if (r.get("concurrency") or 1) > 1:
|
||||
lines.append(f" Measured with {r['concurrency']} requests at once.")
|
||||
lines.append(f" Measured: {r['base'].get('decode_tok_s')} -> {r['chosen'].get('decode_tok_s')} tok/s "
|
||||
f"({r['faster_pairs']} of {r['pairs']} pairs faster)")
|
||||
from strata_control.tune_knobs import ANSWER_NOTICE
|
||||
@@ -497,6 +508,8 @@ def _effective(a: argparse.Namespace, machine: bool) -> int:
|
||||
"args": merged.get("args"), "env": merged.get("env") or {},
|
||||
"sampling": merged.get("sampling") or {}, "changed": changed, "per_request": info.get("per_request") or {}, "sources": where}
|
||||
human = (f"Using your tuning '{info['preset']['name']}'" if info.get("applied") else "No saved tuning is applied; the standard settings run.")
|
||||
if not info.get("applied") and info.get("why_not"):
|
||||
human += f"\n {info['why_not']}" # #4821: a tuning that was not applied says why (the sentence was in the JSON only)
|
||||
human += "\n" + _sources_words(where, after)
|
||||
return _print(payload, machine, human)
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ class Options:
|
||||
busy_pct: float = 25.0
|
||||
wait_busy_s: float = 300.0
|
||||
check_busy: bool = True
|
||||
concurrency: int = 1 # #4821 (opt-in): more than 1 judges every setting on this many requests decoding at once
|
||||
|
||||
def resolved(self) -> "Options":
|
||||
o = Options(**self.__dict__)
|
||||
@@ -102,6 +103,7 @@ class ArmReport:
|
||||
|
||||
@dataclass
|
||||
class TuneResult:
|
||||
concurrency: int = 1 # the number of requests at once the tune judged on (1: one request at a time, as always)
|
||||
outcome: str = "default_confirmed" # improved | default_confirmed | inconclusive | base_failed | cancelled
|
||||
#: what a screen shows, one of: faster | already_fastest | busy_pc | failed | stopped (see `finalize`)
|
||||
code: str = "already_fastest"
|
||||
@@ -151,6 +153,8 @@ def metric(run: dict[str, Any] | RunResult, use: str) -> float | None:
|
||||
d = get("decode_tok_s")
|
||||
if not d:
|
||||
return None
|
||||
if get("load_tok_s"): # #4821: a tune run with --concurrency judges on all the requests' tokens per second
|
||||
return float(get("load_tok_s"))
|
||||
if use == "coding":
|
||||
p = get("pp_long_tok_s") or get("pp_tok_s")
|
||||
if p:
|
||||
@@ -207,7 +211,7 @@ class Tuner:
|
||||
self.clock = clock
|
||||
self.sleep = sleep
|
||||
self.system = system or session.system
|
||||
self.result = TuneResult(mode=self.o.mode)
|
||||
self.result = TuneResult(mode=self.o.mode, concurrency=max(1, int(self.o.concurrency or 1)))
|
||||
self.started = 0.0
|
||||
self.run_times: list[float] = []
|
||||
self.planned_runs = 0
|
||||
@@ -387,7 +391,8 @@ class Tuner:
|
||||
elif self.o.use == "coding" and self.o.mode == "thorough":
|
||||
long_tokens = min(28000, int(0.8 * self.ctx.context_tokens))
|
||||
return RequestSet(warmups=2 if self.o.mode == "thorough" else 1, decodes=5, decode_tokens=200,
|
||||
pp_tokens=4096 if self.ctx.context_tokens >= 6000 else 1024, long_tokens=long_tokens)
|
||||
pp_tokens=4096 if self.ctx.context_tokens >= 6000 else 1024, long_tokens=long_tokens,
|
||||
clients=max(1, int(self.o.concurrency or 1)))
|
||||
|
||||
def _run_stages(self) -> None:
|
||||
r, o = self.result, self.o
|
||||
|
||||
@@ -442,6 +442,24 @@ def notice(preset: dict[str, Any]) -> str:
|
||||
return tune_knobs.ANSWER_NOTICE.get(a.get("class", "exact"), "")
|
||||
|
||||
|
||||
def start_requests(cfg: dict[str, Any]) -> int:
|
||||
"""How many requests a start of this run config decodes together: its "parallel", else its --batch / --slots, else one."""
|
||||
n = cfg.get("parallel")
|
||||
if isinstance(n, int) and not isinstance(n, bool) and n >= 1:
|
||||
return n
|
||||
args = [str(a) for a in cfg.get("args") or []]
|
||||
for flag in ("--batch", "--slots"):
|
||||
if flag in args and args.index(flag) + 1 < len(args) and args[args.index(flag) + 1].isdigit():
|
||||
return int(args[args.index(flag) + 1])
|
||||
return 1
|
||||
|
||||
|
||||
def _tuned_for_load(preset: dict[str, Any], cfg: dict[str, Any]) -> int | None:
|
||||
"""N when the preset was tuned on N >= 2 requests at once (`strata tune auto --concurrency N`) and this start runs fewer than two."""
|
||||
n = (preset.get("choices") or {}).get("concurrency")
|
||||
return n if isinstance(n, int) and not isinstance(n, bool) and n > 1 and start_requests(cfg) < 2 else None
|
||||
|
||||
|
||||
def overlay(cfg: dict[str, Any], *, now: dict[str, Any] | None = None, use: str = "chat") -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""The run configuration with the active preset for its choices put on top, and what was done.
|
||||
|
||||
@@ -460,6 +478,20 @@ def overlay(cfg: dict[str, Any], *, now: dict[str, Any] | None = None, use: str
|
||||
if not isinstance(entry, dict) or not entry.get("active"):
|
||||
return cfg, info
|
||||
preset = load(entry["active"])
|
||||
tuned_for = _tuned_for_load(preset, cfg)
|
||||
if tuned_for:
|
||||
# #4821: a tune judged on N requests at once is not applied to a start that runs one at a time; the solo preset it replaced stands in, if there is one
|
||||
stand_in = None
|
||||
if preset.get("previous"):
|
||||
try:
|
||||
stand_in = load(preset["previous"])
|
||||
except Exception: # noqa: BLE001 - a missing old preset is "none"
|
||||
stand_in = None
|
||||
if stand_in is None or _tuned_for_load(stand_in, cfg):
|
||||
info.update({"preset": {"id": preset["id"], "name": preset["name"]},
|
||||
"why_not": f"not applied: it was tuned for {tuned_for} requests at once, and this start runs one request at a time"})
|
||||
return cfg, info
|
||||
preset = stand_in
|
||||
stale = staleness(preset, now)
|
||||
info.update({"preset": {"id": preset["id"], "name": preset["name"]}, "state": stale["state"], "reasons": stale["reasons"]})
|
||||
if stale["state"] == "hard":
|
||||
|
||||
@@ -62,7 +62,11 @@ def build(result: dict[str, Any], preset_name: str | None = None) -> str:
|
||||
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")))
|
||||
loaded = (result.get("concurrency") or 1) > 1 and _rate(base.get("load_tok_s"))
|
||||
# with --concurrency the tune's repeated measurements (noise.base_runs) are of the loaded rate, so they belong on the loaded line
|
||||
lines.append(f"Your settings: answers at {decode} tok/s" + (f", prompts read at {prompt} tok/s" if prompt else "") + ("" if loaded else _runs_text(noise.get("base_runs"))))
|
||||
if loaded:
|
||||
lines.append(f"With {result['concurrency']} requests at once: {_rate(base.get('load_tok_s'))} tok/s in all" + _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}%.")
|
||||
|
||||
@@ -55,6 +55,8 @@ class RequestSet:
|
||||
decode_tokens: int = 200
|
||||
pp_tokens: int = 4096
|
||||
long_tokens: int = 0 # 0 = no long prompt
|
||||
clients: int = 1 # #4821: more than 1 adds a phase where this many requests decode at once (opt-in: `tune auto --concurrency N`)
|
||||
load_rounds: int = 3 # ... measured this many times (the median counts)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -68,6 +70,8 @@ class RunResult:
|
||||
pp_cold_tok_s: float | None = None
|
||||
ttft_s: float | None = None
|
||||
pp_long_tok_s: float | None = None
|
||||
load_tok_s: float | None = None # #4821: all requests' tokens per second while `clients` decode at once (median of the loaded rounds); None for a solo run
|
||||
load_runs: list[float] = field(default_factory=list)
|
||||
rss_peak_mib: float | None = None
|
||||
vram_used_mib: float | None = None # this run's total graphics memory in use (all cards, absolute)
|
||||
vram_added_mib: float | None = None # ... minus what was in use before the engine started
|
||||
@@ -104,6 +108,7 @@ _FACTS = [
|
||||
("chunk", re.compile(r"prompt chunk auto: (\d+) tokens"), int),
|
||||
("avail_gib", re.compile(r"available ([\d.]+) GiB \(MemAvailable"), float),
|
||||
("loaded_gib", re.compile(r"loaded ([\d.]+) GiB at"), float),
|
||||
("batch_slots", re.compile(r"batch_slots=(\d+)"), int), # #4821: how many requests the engine really decodes together
|
||||
]
|
||||
|
||||
|
||||
@@ -378,6 +383,31 @@ class WorkerEngine:
|
||||
return float(rate)
|
||||
return None
|
||||
|
||||
def load_once(self, clients: int, tokens: int = 200) -> float | None:
|
||||
"""#4821: `clients` requests started together, each asking for `tokens` tokens of its own prompt. All their tokens over the time until the last
|
||||
one ends: what a person serving that many users gets. None when some request produced too little to count."""
|
||||
counts: list[int] = [0] * clients
|
||||
errors: list[BaseException] = []
|
||||
|
||||
def one(i: int) -> None:
|
||||
try:
|
||||
data = self.chat(DECODE_PROMPTS[i % len(DECODE_PROMPTS)], tokens)
|
||||
counts[i] = int((data.get("timings") or {}).get("predicted_n") or 0)
|
||||
except BaseException as e: # noqa: BLE001 - re-raised below, in the tuner's thread
|
||||
errors.append(e)
|
||||
threads = [threading.Thread(target=one, args=(i,), daemon=True) for i in range(clients)]
|
||||
t0 = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
wall = time.monotonic() - t0
|
||||
if errors:
|
||||
raise errors[0]
|
||||
if min(counts) < max(32, tokens // 2) or wall <= 0:
|
||||
return None
|
||||
return sum(counts) / wall
|
||||
|
||||
def prompt_once(self, tokens: int) -> dict[str, float | None]:
|
||||
self.salt_n += 1
|
||||
salt = secrets.token_hex(6)
|
||||
@@ -412,6 +442,18 @@ class WorkerEngine:
|
||||
res.status, res.reason = "NO_TOKENS", "the engine produced no measurable decode"
|
||||
else:
|
||||
res.decode_tok_s = round(statistics.median(runs), 3)
|
||||
if spec.clients > 1 and runs:
|
||||
slots = parse_facts(self.log_text()).get("batch_slots")
|
||||
if slots is not None and slots < spec.clients: # the engine could not hold them: this would measure a queue, not the load asked for
|
||||
ask = f"Ask for {slots} or fewer with --concurrency, or free graphics memory." if slots >= 2 else "Tune without --concurrency, or free graphics memory."
|
||||
raise StartFailed("NO_TOKENS", f"the engine runs {slots} request{'' if slots == 1 else 's'} at once, not the {spec.clients} asked for. {ask}")
|
||||
self.load_once(spec.clients, 64) # warm the slots
|
||||
loads = [x for x in (self.load_once(spec.clients, spec.decode_tokens) for _ in range(spec.load_rounds)) if x]
|
||||
res.load_runs = [round(x, 3) for x in loads]
|
||||
if loads:
|
||||
res.load_tok_s = round(statistics.median(loads), 3)
|
||||
else:
|
||||
res.status, res.reason = "NO_TOKENS", f"the engine produced no measurable output with {spec.clients} requests at once"
|
||||
if spec.pp_tokens:
|
||||
cold = self.prompt_once(spec.pp_tokens)
|
||||
warm = self.prompt_once(spec.pp_tokens)
|
||||
|
||||
@@ -33,6 +33,10 @@ class StubEngine:
|
||||
ttft_s=4096 / pp, rss_peak_mib=self.s.rss(self.args, self.env), vram_used_mib=self.s.vram(self.args),
|
||||
vram_added_mib=self.s.vram(self.args) - 400, min_avail_mib=self.s.avail - self.s.rss(self.args, self.env),
|
||||
facts=dict(self.facts), wall_s=self.s.run_s)
|
||||
if spec.clients > 1:
|
||||
per = self.s.load(self.args, self.env) if self.s.load else 3.0 * self.s.model(self.args, self.env, None)
|
||||
r.load_tok_s = per * (1.0 + self.s.rng.gauss(0.0, self.s.noise))
|
||||
r.load_runs = [r.load_tok_s]
|
||||
return r
|
||||
|
||||
|
||||
@@ -40,8 +44,9 @@ class StubSession:
|
||||
def __init__(self, *, model: Callable[..., float], pp: Callable[..., float] | None = None, noise: float = 0.005,
|
||||
seed: int = 1, facts: dict[str, Any] | None = None, fail: Callable[[list[str], dict], StartFailed | None] | None = None,
|
||||
rss: Callable[..., float] | None = None, vram: Callable[..., float] | None = None, avail: float = 40000,
|
||||
run_s: float = 90.0, clock: Any = None) -> None:
|
||||
run_s: float = 90.0, clock: Any = None, load: Callable[..., float] | None = None) -> None:
|
||||
self.clock = clock
|
||||
self.load = load # #4821: all requests' tokens/s with `clients` decoding at once, from the flags (default: 3 x the solo speed)
|
||||
self.model = model
|
||||
self.pp = pp or (lambda a, e: 1500.0)
|
||||
self.noise = noise
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""#4821 (opt-in): `strata tune auto --concurrency N` judges every setting on N requests decoding at once, not on one request at a time.
|
||||
|
||||
The solo tune is untouched (clients 1, no loaded phase, the same metric). With N > 1 the engine run gets a loaded phase (all requests' tokens per second,
|
||||
median of three), the metric becomes that figure, and the report names N. Doubles only: a stub session and a tiny threaded HTTP worker."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from strata_control import autotune
|
||||
from strata_control.tune_session import RequestSet, StartFailed, WorkerEngine, WorkerSession
|
||||
from tests.tuning.stub_session import FakeClock, StubSession, flag
|
||||
from tests.tuning.test_autotune import BASE, make_ctx, speed_with
|
||||
|
||||
|
||||
class Worker(BaseHTTPRequestHandler):
|
||||
delay = 0.2
|
||||
|
||||
def log_message(self, *a): # noqa: ANN002
|
||||
pass
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
body = json.dumps({"data": [{"id": "m"}]}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self): # noqa: N802
|
||||
self.rfile.read(int(self.headers["content-length"]))
|
||||
time.sleep(self.delay)
|
||||
body = json.dumps({"timings": {"predicted_n": 200, "predicted_per_second": 1000.0 / self.delay}}).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
class FakeProc:
|
||||
pid = 0
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
|
||||
class LoadedPhase(unittest.TestCase):
|
||||
def engine(self, log_text="loading\n"):
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), Worker)
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
self.addCleanup(srv.shutdown)
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
log = Path(tmp.name) / "engine.log"
|
||||
log.write_text(log_text)
|
||||
session = WorkerSession(base_config={"args": []}, serve_dir=".", workdir=tmp.name)
|
||||
return WorkerEngine(session, FakeProc(), srv.server_address[1], "k", [log], 1.0, None, lambda x: None)
|
||||
|
||||
def test_the_requests_run_together_and_all_their_tokens_count(self):
|
||||
rate = self.engine().load_once(3, 200)
|
||||
self.assertGreater(rate, 1800, "3 x 200 tokens in about 0.2 s, not one after the other (that would be about 1000 per second)")
|
||||
self.assertLess(rate, 3100)
|
||||
|
||||
def test_a_request_that_gave_too_little_makes_the_run_unmeasurable(self):
|
||||
eng = self.engine()
|
||||
self.assertIsNone(eng.load_once(2, 500), "200 tokens of 500 asked is below half: not a measurement")
|
||||
|
||||
def test_a_solo_set_has_no_loaded_phase_and_a_loaded_one_has(self):
|
||||
eng = self.engine()
|
||||
solo = eng.measure(RequestSet(warmups=0, decodes=1, decode_tokens=64, pp_tokens=0))
|
||||
self.assertIsNone(solo.load_tok_s)
|
||||
loaded = eng.measure(RequestSet(warmups=0, decodes=1, decode_tokens=64, pp_tokens=0, clients=3, load_rounds=2))
|
||||
self.assertGreater(loaded.load_tok_s, 100)
|
||||
self.assertEqual(len(loaded.load_runs), 2)
|
||||
|
||||
def test_an_engine_with_fewer_slots_than_asked_is_refused_with_the_number(self):
|
||||
eng = self.engine("INFO engine=0.1.60 batch_slots=2\n")
|
||||
eng.facts = {}
|
||||
with self.assertRaises(StartFailed) as cm:
|
||||
eng.measure(RequestSet(warmups=0, decodes=1, decode_tokens=64, pp_tokens=0, clients=4, load_rounds=1))
|
||||
self.assertIn("runs 2 requests at once, not the 4 asked for", cm.exception.reason)
|
||||
|
||||
|
||||
class JudgedOnTheLoad(unittest.TestCase):
|
||||
def test_the_metric_is_the_loaded_rate_when_there_is_one(self):
|
||||
self.assertEqual(autotune.metric({"decode_tok_s": 60.0, "load_tok_s": 180.0}, "chat"), 180.0)
|
||||
self.assertEqual(autotune.metric({"decode_tok_s": 60.0, "load_tok_s": 180.0}, "coding"), 180.0)
|
||||
self.assertEqual(autotune.metric({"decode_tok_s": 60.0}, "chat"), 60.0)
|
||||
self.assertEqual(autotune.metric({"decode_tok_s": 60.0, "load_tok_s": None, "pp_tok_s": 1500.0}, "chat"), 60.0)
|
||||
self.assertEqual(autotune.metric({"decode_tok_s": 60.0, "load_tok_s": 180.0, "pp_tok_s": 1500.0}, "prompt"), 1500.0)
|
||||
|
||||
def tune(self, concurrency):
|
||||
# --kv-resident 65536 is the same solo and 12 % faster with 4 requests at once (the issue's point: a solo run cannot see it)
|
||||
solo = speed_with({})
|
||||
load = lambda args, env: 3.0 * 60.0 * (1.12 if flag(args, "--kv-resident") == "65536" else 1.0) # noqa: E731
|
||||
clock = FakeClock()
|
||||
session = StubSession(model=solo, clock=clock, load=load)
|
||||
t = autotune.Tuner(session, BASE, {}, make_ctx(), autotune.Options(concurrency=concurrency), clock=clock, sleep=clock.sleep, system=session.system,
|
||||
total_ram_mib=64000, total_vram_mib=12000, quiet=lambda: None)
|
||||
return t.run(), session
|
||||
|
||||
def test_a_setting_only_the_load_shows_is_taken_with_concurrency_and_not_without(self):
|
||||
solo_r, _s = self.tune(1)
|
||||
self.assertNotEqual(solo_r.outcome, "improved")
|
||||
self.assertNotIn("--kv-resident", solo_r.settings["args"])
|
||||
loaded_r, _s = self.tune(4)
|
||||
self.assertEqual(loaded_r.outcome, "improved")
|
||||
self.assertEqual(loaded_r.settings["args"].get("--kv-resident"), 65536)
|
||||
self.assertGreater(loaded_r.gain_pct, 8.0)
|
||||
self.assertEqual(loaded_r.concurrency, 4)
|
||||
self.assertGreater(loaded_r.base["load_tok_s"], 0)
|
||||
|
||||
def test_the_solo_result_is_as_it_was(self):
|
||||
r, _s = self.tune(1)
|
||||
self.assertEqual(r.concurrency, 1)
|
||||
self.assertIsNone(r.base.get("load_tok_s"))
|
||||
|
||||
|
||||
class TheCommand(unittest.TestCase):
|
||||
def run_auto(self, *extra, tuner_result=None):
|
||||
import argparse
|
||||
import io
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from strata_cli import tune_commands as TC
|
||||
from tests.tuning.test_autotune import run_tuner
|
||||
res = tuner_result or run_tuner(speed_with({}), ctx=None)[2]
|
||||
seen = {}
|
||||
|
||||
class FakeTuner(autotune.Tuner):
|
||||
def __init__(self, session, base_args, env, ctx, opts, **kw):
|
||||
self.result = res
|
||||
seen["opts"] = opts
|
||||
|
||||
def run(self):
|
||||
return res
|
||||
|
||||
def session(**kw):
|
||||
seen["session"] = kw
|
||||
return mock.Mock(failed_log=None)
|
||||
|
||||
def create(result, *, choices, **kw):
|
||||
seen["choices"] = dict(choices)
|
||||
return {"id": "i", "name": "n"}
|
||||
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"]}))
|
||||
ap = argparse.ArgumentParser()
|
||||
TC.add_tune_auto(ap.add_subparsers(dest="c"))
|
||||
a = ap.parse_args(["auto", str(cfg), "--work-dir", str(t / "work"), *extra])
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
import os
|
||||
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", side_effect=session), mock.patch.object(autotune, "Tuner", FakeTuner), \
|
||||
mock.patch("strata_control.presets.create", side_effect=create), redirect_stdout(out), redirect_stderr(err):
|
||||
code = TC.auto(a)
|
||||
return code, out.getvalue(), err.getvalue(), seen
|
||||
|
||||
def test_a_number_outside_two_to_eight_is_refused_in_plain_words(self):
|
||||
for n in ("0", "9", "-3"):
|
||||
code, _out, err, seen = self.run_auto("--concurrency", n)
|
||||
self.assertEqual(code, 2, n)
|
||||
self.assertIn("--concurrency is a number of requests from 2 to 8", err)
|
||||
self.assertNotIn("session", seen, "nothing was started")
|
||||
|
||||
def test_without_the_flag_nothing_is_different(self):
|
||||
code, _out, _err, seen = self.run_auto()
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(seen["opts"].concurrency, 1)
|
||||
self.assertNotIn("parallel", seen["session"]["base_config"])
|
||||
self.assertNotIn("concurrency", seen["choices"])
|
||||
|
||||
def test_with_the_flag_the_worker_gets_the_slots_and_the_preset_records_it(self):
|
||||
_t, _s, res = autotune_result_improved()
|
||||
res.concurrency = 4 # (what a real Tuner records from its Options)
|
||||
code, out, _err, seen = self.run_auto("--concurrency", "4", tuner_result=res)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(seen["opts"].concurrency, 4)
|
||||
self.assertEqual(seen["session"]["base_config"]["parallel"], 4)
|
||||
self.assertEqual(seen["choices"]["concurrency"], 4)
|
||||
self.assertIn("Measured with 4 requests at once.", out)
|
||||
|
||||
|
||||
def autotune_result_improved():
|
||||
from tests.tuning.test_autotune import run_tuner
|
||||
return run_tuner(speed_with({("--kv-resident", "65536"): 1.10}))
|
||||
|
||||
|
||||
class TheAccountNamesIt(unittest.TestCase):
|
||||
def test_the_line_comes_after_the_solo_one(self):
|
||||
from strata_control import tune_report
|
||||
r = {"outcome": "default_confirmed", "concurrency": 4, "base": {"decode_tok_s": 60.0, "load_tok_s": 180.0},
|
||||
"noise": {"threshold_pct": 3.0, "aa_gap": 0.001, "base_runs": [179.0, 180.0, 181.0]}, "arms": [], "skipped": []}
|
||||
lines = tune_report.build(r).splitlines()
|
||||
self.assertEqual(lines[0], "Your settings: answers at 60.0 tok/s")
|
||||
self.assertEqual(lines[1], "With 4 requests at once: 180.0 tok/s in all (measured 3 times: 179, 180, 181)")
|
||||
self.assertTrue(lines[2].startswith("To count, a setting had to be at least +3.0% faster"))
|
||||
self.assertNotIn("requests at once", tune_report.build({**r, "concurrency": 1}))
|
||||
|
||||
|
||||
class AppliedToTheRightStart(unittest.TestCase):
|
||||
"""A preset tuned on N requests at once is applied to starts that run requests together, not to a one-request start (where its solo predecessor,
|
||||
if any, stands in); a solo preset behaves as before on every start."""
|
||||
|
||||
def setUp(self):
|
||||
import copy
|
||||
import os
|
||||
from strata_control import presets
|
||||
from tests.tuning.test_presets import CFG, RESULT, identity
|
||||
self.presets, self.CFG, self.RESULT, self.identity, self.copy = presets, CFG, RESULT, identity, copy
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
os.environ["STRATA_PRESET_DIR"] = str(Path(self.tmp.name) / "presets")
|
||||
self.addCleanup(lambda: os.environ.pop("STRATA_PRESET_DIR", None))
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.choices = presets.choices_from_config(CFG)
|
||||
|
||||
def save(self, args, **choices):
|
||||
res = self.copy.deepcopy(self.RESULT)
|
||||
res["settings"]["args"] = args
|
||||
return self.presets.create(res, choices={**self.choices, **choices}, identity=self.identity())
|
||||
|
||||
def at(self, cfg):
|
||||
out, info = self.presets.overlay(cfg, now=self.identity())
|
||||
return out["args"], info
|
||||
|
||||
def parallel(self, n):
|
||||
cfg = self.copy.deepcopy(self.CFG)
|
||||
cfg["parallel"] = n
|
||||
return cfg
|
||||
|
||||
def test_how_many_requests_a_start_runs(self):
|
||||
batch = self.copy.deepcopy(self.CFG)
|
||||
batch["args"] += ["--batch", "4"]
|
||||
self.assertEqual([self.presets.start_requests(c) for c in (self.CFG, self.parallel(1), self.parallel(4), batch)], [1, 1, 4, 4])
|
||||
|
||||
def test_a_load_tuned_preset_is_skipped_on_a_solo_start_and_its_solo_predecessor_stands_in(self):
|
||||
self.save({"--host-core": "last"})
|
||||
self.save({"--kv-resident": 65536}, concurrency=4)
|
||||
args, info = self.at(self.CFG)
|
||||
self.assertTrue(info["applied"])
|
||||
self.assertIn("--host-core", args)
|
||||
self.assertNotIn("--kv-resident", args)
|
||||
|
||||
def test_it_is_applied_where_requests_run_together(self):
|
||||
self.save({"--host-core": "last"})
|
||||
self.save({"--kv-resident": 65536}, concurrency=4)
|
||||
for cfg in (self.parallel(4), self.parallel(2)):
|
||||
args, info = self.at(cfg)
|
||||
self.assertTrue(info["applied"], cfg.get("parallel"))
|
||||
self.assertIn("--kv-resident", args)
|
||||
self.assertNotIn("--host-core", args)
|
||||
|
||||
def test_with_no_solo_predecessor_a_solo_start_gets_nothing_and_is_told_why(self):
|
||||
self.save({"--kv-resident": 65536}, concurrency=4)
|
||||
args, info = self.at(self.CFG)
|
||||
self.assertFalse(info["applied"])
|
||||
self.assertEqual(info["why_not"], "not applied: it was tuned for 4 requests at once, and this start runs one request at a time")
|
||||
self.assertEqual(args, self.CFG["args"])
|
||||
self.assertTrue(self.at(self.parallel(4))[1]["applied"])
|
||||
|
||||
def test_a_solo_preset_is_applied_to_every_start_as_before(self):
|
||||
self.save({"--host-core": "last"})
|
||||
for cfg in (self.CFG, self.parallel(1), self.parallel(4)):
|
||||
args, info = self.at(cfg)
|
||||
self.assertTrue(info["applied"])
|
||||
self.assertIn("--host-core", args)
|
||||
|
||||
def test_effective_says_so_in_words(self):
|
||||
import io
|
||||
from contextlib import redirect_stdout
|
||||
from strata_cli import tune_commands as TC
|
||||
why = "not applied: it was tuned for 4 requests at once, and this start runs one request at a time"
|
||||
out = io.StringIO()
|
||||
with mock.patch.object(TC, "_load_target", return_value=(Path("x.json"), self.CFG)), \
|
||||
mock.patch.object(self.presets, "overlay", return_value=(self.CFG, {"applied": False, "why_not": why})), redirect_stdout(out):
|
||||
TC._effective(type("A", (), {"target": "x.json"})(), False)
|
||||
self.assertIn(why, out.getvalue())
|
||||
self.assertIn("No saved tuning is applied; the standard settings run.", out.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user