okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
8.1 KiB131 linesraw
1"""One precedence for the engine options of a launch (round 0213, #5178 #5132 #4985).
2
3An engine option can come from four places. For each option the first one that has it wins, and a launch builds its
4run config from them once (``strata_cli/launch/runner.py derive_config``):
5
61. **explicit launch values**: what this command line (``--set``, the typed flags, the Advanced table) says. They are
7   written to the config's ``"user_args"`` as well as to ``"args"``, because the drafter policy (``drafting.apply``) and
8   the server rebuild ``"args"`` at every start and keep only ``"user_args"``. ``"launch_set"`` names them, so a flag
9   given once is not remembered as the person's standing choice: leave it out next time and it is gone.
102. **persisted overrides**: the person's own options, ``"user_args"`` of the installed config plus the hand edits found in
11   the previous launch config (``user_args.capture`` against ``"args_derived"``, the copy a launch stamps when it writes).
123. **calibrated values**: ``engine calibrate --apply-result`` records them in the run config's ``"calibrated"`` entry
13   (settings, model and context they were measured for); a launch puts them over the generated defaults again, never
14   over 1 or 2, and drops them when the model or the context is another.
154. **Auto**: what setup and the policies (drafting, cards, memory fit) generate.
16
17``"args"`` of the written config is the result, so the file, the start and ``strata status`` show the same value for
18an option. ``"user_args"`` stays authoritative at every start (``serve/server.py engine_args``).
19"""
20
21from __future__ import annotations
22
23from typing import Any, Mapping
24
25from strata_control import tune_knobs, user_args
26
27CALIBRATED_KEY = "calibrated"
28EXPLICIT_KEY = "launch_set"
29DERIVED_KEY = "args_derived"       # "args" as the launch wrote them: a difference found next time is a hand edit
30
31
32def _max_context(args: list[str]) -> str | None:
33    for i, a in enumerate(args):
34        if a == "--max-context" and i + 1 < len(args):
35            return str(args[i + 1])
36    return None
37
38
39def calibration_record(settings: Mapping[str, Any], cfg: Mapping[str, Any]) -> dict:
40    """What ``calibrate --apply-result`` writes into the run config next to the changed ``"args"``."""
41    args = [str(a) for a in cfg.get("args") or []]
42    return {"settings": {str(k): str(v) for k, v in settings.items()}, "model_name": cfg.get("model_name"),
43            "max_context": _max_context(args), "images": "--vision" in args}
44
45
46def _calibration_fits(rec: Any, cfg: Mapping[str, Any]) -> bool:
47    """A calibration is valid for the model, context and image setting it was measured with (setup's hardware_key says the same)."""
48    if not isinstance(rec, dict) or not isinstance(rec.get("settings"), dict):
49        return False
50    args = [str(a) for a in cfg.get("args") or []]
51    return (rec.get("model_name") == cfg.get("model_name") and rec.get("max_context") == _max_context(args)
52            and bool(rec.get("images")) == ("--vision" in args))
53
54
55def _hand_edits(prev: Mapping[str, Any] | None) -> list[str]:
56    """The person's options in the previous launch config: its ``user_args`` and the changes made to its ``args`` since the launch wrote
57    them; the flags that launch was given on its command line are not the person's standing choice. A config from before ``args_derived``
58    has nothing to compare with, so only its explicit ``user_args`` count (none: they come from the installed config anyway)."""
59    if not isinstance(prev, Mapping) or not isinstance(prev.get(DERIVED_KEY), list):
60        return []
61    mine = user_args.capture({"args": prev.get("args"), user_args.USER_KEY: prev.get(user_args.USER_KEY),
62                              user_args.WRITTEN_KEY: prev.get(user_args.WRITTEN_KEY)})
63    given = {str(f) for f in prev.get(EXPLICIT_KEY) or []}
64    return user_args.flat([g for g in user_args.groups(mine) if user_args.flag_of(g) not in given])
65
66
67def _put(mine: list[str], flag: str, value: Any, bool_flags: frozenset[str]) -> list[str]:
68    if value is None or value is False:
69        return user_args.set_flag(mine, flag, None)
70    rest = [g for g in user_args.groups(mine) if user_args.flag_of(g) != flag]
71    rest.append([flag] if value is True or flag in bool_flags else [flag, *user_args.value_tokens(flag, value)])
72    return user_args.flat(rest)
73
74
75def layer(cfg: dict, explicit: Mapping[str, Any] | None = None, prev: Mapping[str, Any] | None = None,
76          bool_flags: frozenset[str] = tune_knobs.BOOL_FLAGS) -> dict:
77    """Put the four sources over each other in ``cfg`` (in place; ``cfg["args"]`` is the generated layer on entry).
78    ``explicit``: the launch's own options as ``tune_knobs.apply_to_argv`` changes (value, True for present, None for off).
79    ``prev``: the config this launch wrote last time (or None). ``bool_flags``: the engine's valueless switches. Returns {"calibrated": bool, "persisted": [...], "explicit": [...]}."""
80    explicit = dict(explicit or {})
81    args = [str(a) for a in cfg.get("args") or []]
82    # 3. calibrated values over the generated ones
83    rec = None
84    for source in (prev, cfg):                                # the previous launch config first: apply-result wrote it there
85        if _calibration_fits((source or {}).get(CALIBRATED_KEY), cfg):
86            rec = source[CALIBRATED_KEY]
87            break
88    cfg.pop(CALIBRATED_KEY, None)
89    if rec:
90        args = tune_knobs.apply_to_argv(args, {k: v for k, v in rec["settings"].items()})
91        cfg[CALIBRATED_KEY] = rec
92    # 2. the person's standing options: the installed config's, then the previous launch's hand edits (the newer wins)
93    mine = user_args.merge(user_args.flat(user_args.groups(cfg.get(user_args.USER_KEY))), _hand_edits(prev))
94    # 1. this command line
95    for flag, value in explicit.items():
96        mine = _put(mine, flag, value, bool_flags)
97    args = tune_knobs.apply_to_argv(args, explicit, bool_flags) if explicit else args
98    cfg["args"] = user_args.merge(args, mine)
99    if mine:
100        cfg[user_args.USER_KEY] = mine
101    else:
102        cfg.pop(user_args.USER_KEY, None)
103    if explicit:
104        cfg[EXPLICIT_KEY] = sorted(explicit)
105    else:
106        cfg.pop(EXPLICIT_KEY, None)
107    return {"calibrated": bool(rec), "persisted": [user_args.flag_of(g) for g in user_args.groups(mine) if user_args.flag_of(g) and user_args.flag_of(g) not in explicit],
108            "explicit": sorted(explicit)}
109
110
111def stamp(cfg: dict) -> None:
112    """Called by the launch after its last change to ``cfg["args"]``: records them as written, so only a later hand edit differs."""
113    written = [str(a) for a in cfg.get("args") or []]
114    cfg[DERIVED_KEY] = list(written)                          # (the marker: this config was written by a launch, so "args_written" below is the launch's)
115    cfg[user_args.WRITTEN_KEY] = list(written)                # replaces the installed config's copy, which describes other arguments
116
117
118def record_calibration(candidate: dict, before: Mapping[str, Any], settings: Mapping[str, Any]) -> None:
119    """`engine calibrate --apply-result` on a run config (in place on the candidate that already carries the calibrated ``"args"``): records
120    the calibrated values with the model and context they were measured for, so a launch that builds its config again keeps them (#5132);
121    the hand edits so far are recorded as the person's first, except the options the calibration sets (a calibration the person asks for is
122    their newer choice, as for ``tune_apply``), and ``args_written`` is brought up to date so the calibrated values are never taken for a hand edit."""
123    candidate[CALIBRATED_KEY] = calibration_record(settings, candidate)
124    if before.get(user_args.WRITTEN_KEY) is not None or before.get(user_args.USER_KEY):
125        mine = user_args.capture(dict(before))
126        mine = user_args.flat([g for g in user_args.groups(mine) if user_args.flag_of(g) not in settings])
127        user_args.stamp(candidate, mine)
128        if user_args.WRITTEN_KEY not in before:
129            candidate.pop(user_args.WRITTEN_KEY, None)
130    if isinstance(candidate.get(DERIVED_KEY), list):         # a launch's own config: its copies of "args" follow, or the calibrated values would read as hand edits
131        stamp(candidate)