okami.mom/strata

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

Niko1221launch: the start's safety net fetches the drafter it falls back to4d3e390b2

main
14.8 KiB220 linesraw
1"""``strata drafting plan|fetch``: the DFlash2 drafter file (strata_control/drafting_fetch.py). The app calls it with ``--output jsonl``.
2
3With ``--config`` (a model's run config) and ``--mode`` (the choice, default: the config's own ``drafting``) the command decides what this
4model needs: ``needed`` is true only when the choice would use the drafter and its file is not here yet. ``fetch --if-needed`` then downloads
5only in that case, so the app can call it before every load without asking twice.
6"""
7
8from __future__ import annotations
9
10import argparse
11import json
12import sys
13from pathlib import Path
14
15from strata_control import acquisition, drafting
16from strata_control.discovery import MTP_FETCH_GB
17
18
19def add_parser(sp) -> None:
20    drafting_p = sp.add_parser("drafting", help="the DFlash2 drafter file: what it would download, and fetch it")
21    d_sp = drafting_p.add_subparsers(dest="drafting_command", required=True)
22    for name, text in (("plan", "say what fetching would download; nothing is changed"),
23                       ("fetch", "download the drafter (pinned, checked) and pack it for the engine")):
24        one = d_sp.add_parser(name, help=text)
25        one.add_argument("--data-dir", metavar="DIR", help="the model data folder (default: the one Strata uses)")
26        one.add_argument("--config", metavar="FILE", help="a model's run config: its data folder, model and drafting choice decide what is needed")
27        one.add_argument("--family", metavar="NAME", help="the model family when there is no run config yet (qwen, gyro, coder, ...)")
28        one.add_argument("--model", metavar="NAME", help="the model (size) when there is no run config yet, with --family: so the plan names the drafter this model will really use and its size")
29        one.add_argument("--mode", choices=drafting.MODES, help="the choice to decide for (default: the run config's own)")
30        one.add_argument("--no-split", action="store_true",
31                         help="decide without the all-cards split engine, as if it will not take the start (a person's choice; the app asks this only after the draft layer for the split could not be downloaded, so the plan is DFlash2's again)")
32        one.add_argument("--engines-unloading", action="store_true",
33                         help=argparse.SUPPRESS)
34        if name == "fetch":
35            one.add_argument("--if-needed", action="store_true", help="download only when the choice would use the drafter and it is not here")
36            one.add_argument("--throttle", action="store_true",
37                             help="a load the person did not ask the drafter for (the app's plain load, a restart, a tuning run): skip the feed for 12 hours after it had nothing, and say nothing when it cannot be reached")
38        one.add_argument("--output", choices=("human", "json", "jsonl"), default="human")
39
40
41def _hardware() -> tuple[str | None, list[str]]:
42    return drafting.detect_hardware()
43
44
45def _split_expected(cfg: dict, args: list, unloading: bool = False) -> bool:
46    """Would the all-cards split engine take a start of this run config (strata_control/split_engine.expected, asked before the draft layer is on disk)?"""
47    try:
48        from strata_control import split_engine as SE
49        flags = [str(x) for x in args]
50        flag = lambda name: next((flags[i + 1] for i, x in enumerate(flags[:-1]) if x == name), None)   # noqa: E731
51        gpus = cfg.get("gpu")
52        cards = [int(g) for g in gpus] if isinstance(gpus, list) else ([int(gpus)] if isinstance(gpus, int) and not isinstance(gpus, bool) else None)
53        probe = None
54        if unloading:                                        # memory the app's own engines hold is given back before the new start: the cards count by their size (as Runner.card_probe does)
55            import dataclasses
56            probe = lambda idx: [dataclasses.replace(c, free_mib=None) for c in SE.probe_cards(idx)]   # noqa: E731
57        return SE.expected({"split_engine": cfg.get("split_engine"), "drafting": cfg.get("drafting"), "user_args": cfg.get("user_args"),
58                            "replicas": cfg.get("replicas")}, indexes=cards, native=flag("--native"),
59                           context=int(flag("--max-context") or SE.TESTED_CONTEXT), kv=flag("--kv"), probe=probe)
60    except Exception:                                        # noqa: BLE001 - an early question is never a reason to stop
61        return False
62
63
64def _planned_model_name(a) -> str | None:
65    """The run config's model_name for a model that has no run config yet (``--family qwen --model IQ3_S`` -> ``qwen3.8-flash-next-iq3_s``); a full name is taken as it is. None: not known."""
66    name = getattr(a, "model", None)
67    if not name:
68        return None
69    if str(name).lower().startswith(drafting.MODEL_PREFIX):
70        return str(name)
71    try:
72        from strata_cli.launch.catalog import Catalog
73        cat = Catalog()
74        family, model = cat.resolve(str(name), a.family)
75        return cat.model_name_of(family, model)
76    except Exception:                                        # noqa: BLE001 - an unknown model is only the old, generic plan
77        return None
78
79
80SEVERAL_MODELS = "Several models are set up here. Say which one: strata drafting fetch --model <name>, or --config <file>."
81
82
83def _installed_dflash2_configs(a) -> list[dict]:
84    """A bare ``strata drafting fetch`` (no run config, no model, no family): the installed models DFlash2 is for; [] for any other command line or when none can be read."""
85    if a.config or getattr(a, "model", None) or a.family or a.drafting_command != "fetch":
86        return []
87    try:
88        from strata_cli.launch.catalog import Catalog
89        return [c for c in Catalog().installed_configs() if c.get("path") and drafting.supported_model(c.get("model_name"))]
90    except Exception:                                        # noqa: BLE001 - no answer is the generic fetch
91        return []
92
93
94def _only_installed_config(a) -> str | None:
95    """A bare ``strata drafting fetch``: the run config of the installed model when exactly one model DFlash2 is for is set up here, so the
96    fetch takes the drafter that model would use (the tuned one where it applies) and not the stock one. Several: `run` asks which one (SEVERAL_MODELS); none: None, the fetch is the generic one as before."""
97    found = _installed_dflash2_configs(a)
98    return str(found[0]["path"]) if len(found) == 1 else None
99
100
101def _inputs(a) -> dict:
102    cfg: dict = {}
103    if not a.config:
104        a.config = _only_installed_config(a)
105    if a.config:
106        try:
107            cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig"))
108        except (OSError, ValueError):
109            cfg = {}
110    if a.data_dir:
111        data = Path(a.data_dir)
112    else:
113        data = drafting.data_dir_of(cfg.get("args") or [])
114        if data is None:
115            from strata_cli.launch.catalog import Catalog
116            data = Catalog().data_dir()
117    backend, archs = _hardware()
118    args = cfg.get("args") or []
119    model_name = cfg.get("model_name") or _planned_model_name(a)
120    mode = a.mode if a.mode else cfg.get("drafting")
121    if cfg.get("mtp") is False and drafting.normalize(mode) == "auto":
122        mode = "off"                                         # the Draft layer switch is off and no drafter was chosen since
123    elif drafting.normalize(mode) in ("auto", "mtp") and not getattr(a, "no_split", False) and _split_expected({**cfg, "drafting": mode}, args, bool(getattr(a, "engines_unloading", False))):
124        a._split = True                                      # the plan says so (the app's Models screen and its load read it); asked with the choice in hand, as the Terminal does
125        mode = "mtp"                                         # the all-cards split engine runs the MTP draft layer: the app fetches that, not DFlash2's drafter
126    parallel = cfg.get("parallel") if isinstance(cfg.get("parallel"), int) else 0
127    slot_drafts = False
128    if str(backend or "").lower() == "cuda" and drafting.request_count(args, parallel) in drafting.SLOT_DRAFT_REQUESTS:     # (the card is only read for a start that could be in the class)
129        sig = _signals(a, {"backend": backend, "archs": archs})
130        slot_drafts = drafting.slot_drafts_by_default(mode, backend=backend, archs=archs, vram_mib=sig.get("vram_mib"), args=sig.get("args"), slots=parallel)   # the drafter is fetched before the start
131    return {"mode": mode, "klass": drafting.card_class(archs), "model_name": model_name, "family": a.family, "data_dir": data,
132            "backend": backend, "archs": archs, "mtp_here": drafting.mtp_ready(args) if cfg else None,
133            "blocked": drafting.blocked_by(args, slots=parallel, named=drafting.normalize(mode) == "dflash2", backend=backend, slot_drafts=slot_drafts),
134            "slots_none": drafting.slots_draft_nothing(drafting.merged_args(cfg), parallel)}      # (False when the request count is not in the config: today's line)
135
136
137def _signals(a, want: dict) -> dict:
138    """The arguments and the one card's memory drafting.tuned_applies reads (as the server reads them for the start); {} when there is no run config to read them from."""
139    try:
140        cfg = json.loads(Path(a.config).read_text(encoding="utf-8-sig")) if a.config else {}
141        args = [str(x) for x in cfg.get("args") or []]
142        if cfg.get("user_args"):
143            from strata_control import user_args
144            args = user_args.merge(args, cfg["user_args"])
145        return {"args": args, "vram_mib": drafting.card_vram_mib(cfg, want["backend"], want["archs"])}
146    except Exception:                                        # noqa: BLE001 - no signal: the tuned drafter is not offered
147        return {"args": [], "vram_mib": None}
148
149
150def run(a) -> int:
151    from strata_control import drafting_fetch      # here, not at the top: it pulls in the network code, which a started engine's command line must not load
152    machine = a.output in ("json", "jsonl")
153    if len(_installed_dflash2_configs(a)) > 1:               # which model's drafter? the generic fetch would take the stock one for a set that has a tuned one
154        if machine:
155            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": "which_model", "message": SEVERAL_MODELS}}, ensure_ascii=False))
156        else:
157            print(f"strata: {SEVERAL_MODELS}", file=sys.stderr)
158        return 2
159    want = _inputs(a)
160    folder = want["data_dir"]
161    sig = _signals(a, want)
162    needed = drafting.needs_pack(**want, **sig) or drafting.needs_tuned(**want, **sig)       # (the tuned drafter is a download of its own, where the set and the card use it)
163    tuned_needed = drafting.needs_tuned(**want, **sig)
164    mtp_needed = drafting.needs_mtp(**want, **sig) or (not needed and want["mtp_here"] is False and drafting.normalize(want["mode"]) != "off"
165                                                       and drafting.decide(**want, **sig).drafter == "off")   # the start's safety net (runner.fetch_missing_drafter): never no drafter unless Off was chosen
166    if a.drafting_command == "plan":
167        decision = drafting.decide(**want, **sig)
168        support = drafting.hardware_support(want["backend"], want["archs"], want["model_name"])
169        # serves: this computer's engine can run DFlash2 (the build has the code and the card is one it is made for); the app offers the choice only then
170        result = {**drafting_fetch.plan(folder, drafting.installed_engine_exe(), model_name=want["model_name"], backend=want["backend"], archs=want["archs"], **sig), "needed": needed, "tuned_needed": tuned_needed, "mtp_here": want["mtp_here"], "mtp_needed": mtp_needed, "mtp_gb": MTP_FETCH_GB if mtp_needed else 0.0,
171                  "serves": drafting.ENGINE_SERVES_DFLASH2 and support.can_run, "drafter": decision.drafter,
172                  "choice": drafting.choice_of(want["mode"], model_name=want["model_name"], family=want["family"], backend=want["backend"], archs=want["archs"], **sig),
173                  "split": bool(getattr(a, "_split", False)), "note": decision.note, "line": drafting.summary_line(decision), "support": support.level, "support_line": support.line}
174        if result["split"]:                                # the Terminal's words for the same plan (runner.drafting_plan_line)
175            from strata_control import split_engine as SE
176            result["line"] = SE.split_plan_line(result["mtp_gb"] or None)
177        if (a.config or a.mode or a.model) and not needed:           # asked about a model: nothing to download unless the choice uses the drafter
178            result["gb"] = 0.0
179            if not result["ready"]:                       # (MTP, off, a model DFlash2 is not for): the size of a drafter nobody fetches is not quoted
180                result["text"] = "Nothing to download."
181        if machine:
182            print(json.dumps({"schema_version": 1, "ok": True, **result}, ensure_ascii=False))
183        else:
184            print(result["text"] if needed or not decision.note else result["line"])
185        return 0
186    if getattr(a, "if_needed", False) and not needed:
187        if machine:
188            print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "pack": None, "skipped": True}, ensure_ascii=False))
189        else:
190            print("Nothing to download.")
191        return 0
192
193    def show(step: str, done: int, total: int) -> None:
194        if a.output == "jsonl":
195            print(json.dumps({"event": "progress", "step": step, "done": done, "total": total}, ensure_ascii=False), flush=True)
196        elif not machine and total:
197            print(f"\r{step} {done / 1e9:.2f} of {total / 1e9:.2f} GB", end="", flush=True)
198
199    try:
200        out = drafting_fetch.ensure_for(folder, model_name=want["model_name"], backend=want["backend"], progress=show, archs=want["archs"],
201                                        throttle=bool(getattr(a, "throttle", False)), **sig)
202        if out is None and getattr(a, "throttle", False):    # a load the person did not ask the drafter for: the feed was not reachable (or asked a short while ago): the model starts as it is, nothing is said
203            if machine:
204                print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "pack": None, "skipped": True}, ensure_ascii=False))
205            else:
206                print("Nothing to download.")
207            return 0
208        if out is None:                                    # (a set with a tuned drafter, and nothing answered: an explicit fetch says so)
209            raise drafting_fetch.OfflineError("There is no internet connection, so the DFlash2 drafter can't be downloaded now.")
210    except (drafting_fetch.DraftingError, acquisition.AcquisitionRefused) as exc:
211        if machine:
212            print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": "drafting_failed", "message": str(exc)}}, ensure_ascii=False))
213        else:
214            print(f"\nstrata: {exc}", file=sys.stderr)
215        return 5
216    if machine:
217        print(json.dumps({"schema_version": 1, "ok": True, "event": "result", "pack": str(out)}, ensure_ascii=False))
218    else:
219        print(f"\nThe DFlash2 drafter is ready: {out}")
220    return 0