okami.mom/strata

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

Niko1221Merge f-022-int into f-022-gyrocuda: Pascal path kept for cc 6.0, 8-lane trellis rows for every other CUDA card01f8c3255

main
6.3 KiB134 linesraw
1"""The engine options a person set by hand in a model's run config (strata-<model>.json).
2
3Setup and the app write ``"args"`` from their own choices, and used to write it again on every run, so an option added by
4hand (the control vector options, a --vram-reserve-mib of 0, --spec, ...) was gone after the next Load (#3216 #3215 #3270).
5The run config now keeps what the person set apart from what was generated:
6
7* ``"user_args"``: the person's options, in the same form as ``"args"`` (``["--vram-reserve-mib", "0", ...]``).  Every start
8  (serve/server.py engine_args) and every setup run applies them on top of the generated ones; for the same flag the
9  person's value wins.  The person can edit this list by hand; the app's settings window writes the options it shows here.
10* ``"args_written"``: the whole ``"args"`` as setup or the app last wrote it.  An option in ``"args"`` that is not in this
11  copy was added or changed by hand since: ``capture`` moves it into ``"user_args"``.  A config without the copy (one an
12  older Strata wrote) has nothing to compare with: setup then keeps the options of the old file that its new arguments do not
13  have (see ``dropped_by_setup``).
14
15Writers that change ``"args"`` themselves (setup, the app's resource profile, a tuning run) call ``stamp`` after they have
16captured, so their own changes are never mistaken for the person's.
17"""
18
19from __future__ import annotations
20
21import re
22from typing import Any
23
24USER_KEY = "user_args"
25WRITTEN_KEY = "args_written"
26
27#: option groups the engine takes more than one of, or that make sense only together: kept whole
28#: (the control vector options of the experimental speed projection and the person's own vectors, #3216)
29USER_KEPT_FLAGS = frozenset({"--control-vector", "--control-vector-scaled", "--control-vector-layer-range", "--cvec-mode",
30                             "--cvec-dir"})
31
32
33#: options that take more than one value, and how many (``--control-vector-layer-range 4 44``): written as separate argv
34#: entries, never as one ``4,44``, and removed with all of their values (#3504)
35MULTI_VALUE_FLAGS = {"--control-vector-layer-range": 2}
36
37
38def value_tokens(flag: str, value: Any) -> list[str]:
39    """The argv entries that follow ``flag`` for ``value``: one, or the several a multi-value option takes (``4 44``, ``4,44``,
40    ``4-44`` or a list)."""
41    n = MULTI_VALUE_FLAGS.get(flag, 1)
42    if n == 1:
43        return [str(value)]
44    parts = [str(v) for v in value] if isinstance(value, (list, tuple)) else re.split(r"[,;\s]+|(?<=\d)-(?=\d)", str(value).strip())
45    return [t for t in parts if t]
46
47
48def groups(args: Any) -> list[list[str]]:
49    """Split an argument list into groups: an option and the values after it (up to the next ``--option``)."""
50    out: list[list[str]] = []
51    for a in args if isinstance(args, list) else []:
52        a = str(a)
53        if a.startswith("--") or not out:
54            out.append([a])
55        else:
56            out[-1].append(a)
57    return out
58
59
60def flat(gs: list[list[str]]) -> list[str]:
61    return [t for g in gs for t in g]
62
63
64def flag_of(group: list[str]) -> str:
65    return group[0] if group and group[0].startswith("--") else ""
66
67
68def merge(args: Any, user: Any) -> list[str]:
69    """``args`` with the person's options on top: every group of ``args`` whose option the person set is replaced."""
70    ug = groups(user)
71    mine = {flag_of(g) for g in ug if flag_of(g)}
72    kept = [g for g in groups(args) if flag_of(g) not in mine]
73    return flat(kept + ug)
74
75
76def apply(cfg: dict) -> list[str]:
77    """Puts the config's ``user_args`` over its ``args`` (in place); returns the options applied."""
78    ug = groups(cfg.get(USER_KEY))
79    if not ug or not isinstance(cfg.get("args"), list):
80        return []
81    cfg["args"] = merge(cfg["args"], flat(ug))
82    return [flag_of(g) for g in ug if flag_of(g)]
83
84
85def _by_flag(gs: list[list[str]]) -> dict[str, list[list[str]]]:
86    d: dict[str, list[list[str]]] = {}
87    for g in gs:
88        d.setdefault(flag_of(g), []).append(g)
89    return d
90
91
92def capture(cfg: dict, skip=frozenset()) -> list[str]:
93    """The person's options of a config: its ``user_args``, with the options of ``args`` that differ from ``args_written``
94    (added or changed by hand since the last write) on top.  Without ``args_written`` only ``user_args`` is returned.
95    ``skip``: options the caller chooses itself (setup's context, KV type, pictures, draft layer), never taken from ``args``."""
96    mine = _by_flag(groups(cfg.get(USER_KEY)))
97    written = cfg.get(WRITTEN_KEY)
98    if isinstance(written, list) and isinstance(cfg.get("args"), list):
99        cur, was = _by_flag(groups(cfg["args"])), _by_flag(groups(written))
100        for flag, gs in cur.items():
101            if flag and flag not in skip and was.get(flag) != gs:
102                mine[flag] = gs                       # added, or its value changed, by hand
103        for flag in list(mine):
104            if flag in was and flag not in cur:
105                del mine[flag]                        # taken out of "args" by hand: the person no longer wants it
106    return flat([g for gs in mine.values() for g in gs])
107
108
109def stamp(cfg: dict, user: list[str] | None = None) -> None:
110    """Records ``cfg["args"]`` as written (call after the last change to it) and ``user`` as the person's options."""
111    if user is not None:
112        if user:
113            cfg[USER_KEY] = list(user)
114        else:
115            cfg.pop(USER_KEY, None)
116    if isinstance(cfg.get("args"), list):
117        cfg[WRITTEN_KEY] = list(cfg["args"])
118
119
120def dropped_by_setup(old_args: Any, new_args: Any, setup_flags: set[str] | frozenset[str], skip=frozenset()) -> list[str]:
121    """For an old config with no ``args_written``: its options that the new arguments do not have and that setup never
122    writes (``setup_flags``: every option setup.py names), plus the control vector options.  These were added by hand."""
123    have = {flag_of(g) for g in groups(new_args)}
124    out = [g for g in groups(old_args) if flag_of(g) and flag_of(g) not in have and flag_of(g) not in skip
125           and (flag_of(g) not in setup_flags or flag_of(g) in USER_KEPT_FLAGS)]
126    return flat(out)
127
128
129def set_flag(user: list[str], flag: str, value: Any) -> list[str]:
130    """``user`` with ``flag`` set to ``value`` (None: the person's option removed)."""
131    rest = [g for g in groups(user) if flag_of(g) != flag]
132    if value is not None:
133        rest.append([flag, *value_tokens(flag, value)])
134    return flat(rest)