okami.mom/strata

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

Niko1221update: --backend amd on a PC with an NVIDIA and an AMD card picks the AMD card's packagefdfca1d9d

main
22.0 KiB380 linesraw
1"""The engines installed on this computer: list them, switch to any of them, delete one. Local only: nothing here downloads.
2
3One truth for the app (Settings > Engine) and the Terminal (`strata components engines | use | remove | rollback`). Updates keep every older
4engine (strata_control/updater.py), so a person can go back to an older engine to test something and return to the newest later.
5
6The Qwen engine (every model): packages in ``<components>/engine/<version>-<platform>-<backend>[-<variant>]/``. What a start runs is the pinned
7package (``.updates/state.json`` engine.pinned), else the newest that fits this PC (engine_component.resolve).  The engine of a model shape has the
8same mechanism in its own folder.  (DeepSeek's engine-dsv41/ folder, from Strata 0.2.13 and earlier, is not listed and never touched here.)
9
10A switch warns, it does not refuse, wherever the engine can run at all. What cannot be switched to is a package this computer cannot run (another
11operating system or make of graphics card, a driver that is too old, damaged files, a Strata that is too old for it). The engine in use cannot be
12deleted, nor one a running program uses.
13"""
14from __future__ import annotations
15
16import os
17import shutil
18import uuid
19from pathlib import Path
20
21from strata_control import engine_component as ec, folder_use, longpath, retired, shape_engine, signing
22from strata_control import updater
23from strata_control.targets import backend_supported, host_platform
24
25QWEN = "qwen"
26FAMILIES = (QWEN,)
27TITLES = {QWEN: "Qwen and other models"}
28#: The engine of a Qwen4 model shape (strata_control/shape_engine.py): family "shape:<shape>", one per installed shape, listed after the two above. The family
29#: string is an id for the app and the Terminal, never shown: the app titles the group with the model's own catalog title ("title" here is None).
30SHAPE_PREFIX = "shape:"
31
32
33def shape_of_family(family) -> str | None:
34    """shape:q4_lite -> q4_lite; None for anything else."""
35    if not isinstance(family, str) or not family.startswith(SHAPE_PREFIX):
36        return None
37    shape = family[len(SHAPE_PREFIX):]
38    return shape if shape_engine.valid(shape) else None
39
40
41def _walk_bytes(folder: Path) -> int:
42    total = 0
43    try:
44        for base, _dirs, files in os.walk(longpath.long_path(folder)):
45            for name in files:
46                try:
47                    total += os.lstat(os.path.join(base, name)).st_size
48                except OSError:
49                    continue
50    except OSError:
51        pass
52    return total
53
54
55def _version_of(folder_name: str) -> str:
56    return str(folder_name).split("-")[0]
57
58
59def _label(version: str, backend: str, variant: str = "") -> str:
60    return version + (f" ({backend}{'-' + variant if variant else ''})" if backend else "")
61
62
63# ----------------------------------------------------------------------------------------------- Qwen engine
64
65def _unfit(item: ec.EngineComponent, *, wanted: str | None, target: str, runtime: str | None, cuda_here: list[str], driver_here: str | None,
66           hip_here: list[str], other_makes: frozenset = frozenset()) -> tuple[str, str, list[str]] | None:
67    """Why this computer cannot run the package, as (plain English, a code the app translates, its values), or None. The same checks as
68    engine_component.resolve, one package at a time. ``other_makes``: the other makes of graphics card this PC also has (a PC with an NVIDIA
69    card and an AMD card); an engine for one of them runs on that card, so it is not "for a different kind of graphics card"."""
70    if item.platform != target:
71        return ("It was made for a different operating system.", "os", [])
72    ok, _why = backend_supported(item.backend, target)
73    if not ok or (wanted and item.backend != wanted and item.backend not in other_makes):
74        return ("It was made for a different kind of graphics card than this computer has.", "gpu_make", [])
75    if item.min_runtime and runtime and ec._version_key(runtime) < ec._version_key(item.min_runtime):
76        return (f"It needs Strata {item.min_runtime} or newer; this is {runtime}.", "strata", [item.min_runtime, runtime])
77    if item.cuda_archs and cuda_here and not ec.arch_covers(item.cuda_archs, cuda_here):
78        return ("It does not include support for this computer's graphics card.", "gpu_arch", [])
79    if item.hip_archs and hip_here and not set(item.hip_archs) & set(hip_here):
80        return ("It does not include support for this computer's graphics card.", "gpu_arch", [])
81    need = item.min_driver.get("nvidia")
82    if need and driver_here and ec._version_key(driver_here) < ec._version_key(need):
83        return (f"It needs NVIDIA driver {need} or newer; this computer has {driver_here}.", "driver", [need, driver_here])
84    try:
85        ec.verify(item, full=False)
86    except ec.ComponentProblem:
87        return ("Some of its files are missing or changed, so it is not safe to start.", "files", [])
88    return None
89
90
91def _process_uses(folder: Path) -> bool:
92    try:
93        return folder_use.in_use(folder)
94    except Exception:                                   # noqa: BLE001 - unknown means not blocked by this check
95        return False
96
97
98def _qwen_entries(ctx: "updater.Context", root: Path | None = None, component_id: str = ec.COMPONENT_ID, family: str = QWEN) -> list[dict]:
99    """The Qwen engine's packages; with root, component_id and family those of a model shape's engine (the same package layout and checks)."""
100    root = ctx.components if root is None else root
101    found, problems = ec.scan(root, component_id)
102    wanted = ctx.hardware.get("backend")
103    runtime = ctx.hardware.get("runtime") or ec.runtime_version()
104    target = ctx.hardware.get("platform") or host_platform()
105    other_makes = frozenset(m for m in (ctx.hardware.get("makes") or []) if m in updater.GPU_MAKES and m != wanted)
106    seen = {wanted, *other_makes}
107    cuda_here = ec.cuda_archs_present() if "cuda" in seen else []
108    driver_here = ec.nvidia_driver_version() if "cuda" in seen else None
109    hip_here = ec.hip_archs_present() if "hip" in seen else []
110    try:
111        active = ec.resolve(root, backend=wanted, full=False, runtime=ctx.hardware.get("runtime"), component_id=component_id).root.name
112    except ec.EngineMissing:
113        active = None
114    pin = ec.pinned_folder(root)
115    rows = []
116    for item in found:
117        why, code, args = _unfit(item, wanted=wanted, target=target, runtime=runtime, cuda_here=cuda_here, driver_here=driver_here,
118                                 hip_here=hip_here, other_makes=other_makes) or (None, None, [])
119        rows.append({"family": family, "folder": item.root.name, "version": item.version, "backend": item.backend, "platform": item.platform,
120                     "variant": item.variant, "bytes": sum(f[2] for f in item.files), "signed": bool(item.signature), "fits": why is None,
121                     "why_not": why, "why_code": code, "why_args": args, "active": item.root.name == active, "build_id": item.build_id, "path": longpath.plain(item.root),
122                     "other_card": bool(wanted and item.backend != wanted and item.backend in other_makes)})
123    for bad in problems:
124        folder = Path(bad["folder"])
125        rows.append({"family": family, "folder": folder.name, "version": _version_of(folder.name), "backend": "", "platform": "", "variant": "",
126                     "bytes": _walk_bytes(folder), "signed": False, "fits": False, "active": False, "build_id": "", "path": longpath.plain(folder),
127                     "why_not": "Its description is missing or damaged, so it cannot be started.", "why_code": "manifest", "why_args": [],
128                     "detail": bad["problem"]})
129    fitting = [r for r in rows if r["fits"] and not r.get("other_card")] or [r for r in rows if r["fits"]]     # "newest" = what updates follow
130    newest = max(fitting, key=lambda r: (ec._version_key(r["version"]), r["folder"]), default=None)
131    for row in rows:
132        row["newest"] = row is newest
133        row["pinned"] = row["folder"] == pin
134    return rows
135
136
137# ----------------------------------------------------------------------------------------------- the list
138
139def _decorate(rows: list[dict], serving: bool) -> None:
140    for row in rows:
141        busy = _process_uses(Path(row["path"]))
142        row["running"] = busy
143        if row["active"]:
144            row["can_delete"], row["delete_blocked"], row["blocked_code"] = False, "This is the engine in use. Switch to another one first.", "active"
145        elif busy:
146            row["can_delete"], row["delete_blocked"], row["blocked_code"] = False, "A running program is using it. Stop the model first.", "running"
147        else:
148            row["can_delete"], row["delete_blocked"], row["blocked_code"] = True, None, None
149        row["can_use"] = bool(row["fits"]) and not row["active"]
150
151
152def list_engines(ctx: "updater.Context") -> dict:
153    """Every installed engine package, by family: ``{"families": [{"family", "title", "engines": [...]}], "total_bytes", "serving"}``. A family with
154    no package is left out, except the Qwen one, which is always there. Reads files only; nothing is changed or downloaded."""
155    try:
156        serving = bool(ctx.serving())
157    except Exception:                                   # noqa: BLE001
158        serving = False
159    qwen = _qwen_entries(ctx)
160    shapes = _shape_families(ctx)
161    for rows in (qwen, *(f["engines"] for f in shapes)):
162        _decorate(rows, serving)
163        rows.sort(key=lambda r: (ec._version_key(r["version"]), r["folder"]), reverse=True)
164    families = [{"family": QWEN, "title": TITLES[QWEN], "engines": qwen}]
165    families += shapes                                  # none on a PC that never had a model of another shape: the list is what it was
166    return {"schema_version": 1, "components_dir": str(ctx.components), "families": families,
167            "total_bytes": sum(r["bytes"] for fam in families for r in fam["engines"]), "serving": serving}
168
169
170def _shape_families(ctx: "updater.Context") -> list[dict]:
171    """One family per model shape whose engine is installed here (shape_engine.py: <components>/shapes/<shape>/engine/), each with its packages."""
172    out = []
173    try:
174        shapes = shape_engine.installed_shapes(ctx.components)
175    except Exception:                                   # noqa: BLE001 - a shapes folder that cannot be read lists nothing, as before
176        return []
177    for shape in shapes:
178        rows = _qwen_entries(ctx, shape_engine.root(shape, ctx.components), shape_engine.component_id(shape), SHAPE_PREFIX + shape)
179        if rows:
180            out.append({"family": SHAPE_PREFIX + shape, "shape": shape, "title": None, "engines": rows})
181    return out
182
183
184def find_entry(listing: dict, spec: str, family: str | None = None) -> dict:
185    """The one entry a person's words name: a folder name, a version, or ``newest``. Ambiguous or unknown is an UpdateError (exit 2) that says what to type."""
186    entries = [e for fam in listing["families"] for e in fam["engines"] if family in (None, fam["family"])]
187    spec = str(spec).strip()
188    if spec.lower() in ("newest", "latest"):
189        picks = [e for e in entries if e["newest"]]
190    else:
191        picks = [e for e in entries if e["folder"] == spec] or [e for e in entries if e["version"] == spec]
192    if not picks:
193        have = ", ".join(sorted({e["version"] for e in entries})) or "none"
194        raise updater.UpdateError(f"no installed engine matches {spec!r} (installed: {have}); `strata components engines` lists them", 2)
195    if len(picks) > 1:
196        raise updater.UpdateError(f"{spec!r} matches more than one installed engine ({', '.join(p['folder'] for p in picks)}); use the folder name", 2)
197    return picks[0]
198
199
200# ----------------------------------------------------------------------------------------------- switch
201
202class SwitchBusy(updater.Busy):
203    """A model is running, so the engine is not switched. One plain answer; the running model keeps the engine it started with."""
204
205    def __init__(self, serving: list[dict]):
206        updater.UpdateError.__init__(self, "A model is running, so the engine was not switched. Stop the model first (`strata launch --stop`, or Unload in the app), "
207                                           "then switch. The running model keeps the engine it started with. Nothing was changed.", 7)
208        self.serving = serving
209
210
211def use_engine(ctx: "updater.Context", family: str, folder: str, root: str | None = None) -> dict:
212    """Make an installed engine the one that starts from now on. Nothing is downloaded or deleted. Waits for / refuses while a model is running
213    (`updater.Busy`, exit 7); the running model keeps the engine it started with. The newest engine is selected without a pin, so it follows updates again."""
214    shape = shape_of_family(family)
215    if retired.is_name(family):
216        raise updater.UpdateError(retired.NOT_OFFERED, 2)
217    if family not in FAMILIES and shape is None:
218        raise updater.UpdateError("choose the Qwen engine", 2)
219    if not folder or folder != Path(folder).name or folder.startswith("."):
220        raise updater.UpdateError("that is not an installed engine", 2)
221    with updater.update_lock(ctx.components):
222        try:
223            updater.wait_until_idle(ctx.serving, wait=ctx.wait, emit=ctx.emit, cancel=ctx.cancel, poll=ctx.poll)
224        except updater.Busy as busy:
225            raise SwitchBusy(busy.serving) from None
226        if shape is not None:
227            return _use_shape(ctx, shape, folder)
228        return _use_qwen(ctx, folder)
229
230
231def _use_shape(ctx: "updater.Context", shape: str, folder: str) -> dict:
232    """The switch for a model shape's engine: the same pin as the Qwen engine's (``.updates/state.json`` engine.pinned), in the shape's own folder, which
233    engine_component.resolve reads at every start of a model of that shape. The newest package is selected without a pin, so it follows updates again."""
234    base, cid, family = shape_engine.root(shape, ctx.components), shape_engine.component_id(shape), SHAPE_PREFIX + shape
235    found, _ = ec.scan(base, cid)
236    target = next((item for item in found if item.root.name == folder), None)
237    if target is None:
238        raise updater.UpdateError("that engine is not installed (it may have been deleted already)", 2)
239    backend, runtime = ctx.hardware.get("backend"), ctx.hardware.get("runtime")
240
241    def picked() -> str | None:
242        try:
243            return ec.resolve(base, backend=backend, full=True, runtime=runtime, component_id=cid).root.name
244        except ec.EngineMissing:
245            return None
246    before = picked()
247    if before == folder:
248        return {"component": cid, "family": family, "status": "already", "changed": False, "to": target.version, "folder": folder}
249    try:
250        signing.ensure_component_verifier()
251        ec.verify_signature(target)
252        ec.verify(target, full=True)
253    except (ec.ComponentProblem, signing.SignatureError, OSError) as exc:
254        raise updater.UpdateError(f"engine {target.version} can no longer be used: {exc}", 5) from None
255    state = updater.State(base)
256    section = state.section("engine")
257    old_pin = section.pop("pinned", None)
258    state.save()
259    automatic = picked() == folder
260    if not automatic:
261        section["pinned"] = folder
262        state.save()
263    if picked() != folder:
264        if old_pin:
265            section["pinned"] = old_pin
266        else:
267            section.pop("pinned", None)
268        state.save()
269        raise updater.UpdateError(f"engine {target.version} can no longer be used: a start would not pick it", 5)
270    state.history({"at": (ctx.now or updater.dt.datetime.now(updater.dt.timezone.utc)).isoformat(), "action": "use-shape-engine", "shape": shape,
271                   "from": _version_of(before) if before else None, "to": target.version, "ok": True})
272    state.save()
273    return {"component": cid, "family": family, "status": "switched", "changed": True, "automatic": automatic,
274            "from": _version_of(before) if before else None, "to": target.version, "folder": folder}
275
276
277def _use_qwen(ctx: "updater.Context", folder: str) -> dict:
278    found, _ = ec.scan(ctx.components)
279    target = next((item for item in found if item.root.name == folder), None)
280    wanted = ctx.hardware.get("backend")
281    if target is not None and wanted and target.backend != wanted and target.backend in (ctx.hardware.get("makes") or []):
282        # An engine for this PC's other card (an AMD card beside an NVIDIA one): choosing it is choosing that card, the same choice
283        # `strata launch --backend amd` keeps ("now and next time"). Without it a start would go on picking the engine of the first make.
284        before = ec.saved_backend()
285        ec.save_backend(target.backend)
286        ctx.hardware = {**updater.detect_hardware(), "backend_source": "saved choice"}
287        try:
288            out = use_qwen_unlocked(ctx, updater.State(ctx.components), folder)
289        except BaseException:
290            ec.save_backend(before)                     # nothing was switched: the make chosen before stays
291            raise
292        return {**out, "backend_saved": target.backend}
293    return use_qwen_unlocked(ctx, updater.State(ctx.components), folder)
294
295
296def use_qwen_unlocked(ctx: "updater.Context", state: "updater.State", folder: str) -> dict:
297    """The switch itself, for a caller that already holds the update lock (the update that finds its engine already installed)."""
298    found, _ = ec.scan(ctx.components)
299    target = next((item for item in found if item.root.name == folder), None)
300    if target is None:
301        raise updater.UpdateError("that engine is not installed (it may have been deleted already)", 2)
302    current, _why = updater.installed_engine(ctx.components, ctx.hardware)
303    if current is not None and current.root.name == folder:
304        return {"component": "engine", "family": QWEN, "status": "already", "changed": False, "to": target.version, "folder": folder}
305    try:
306        signing.ensure_component_verifier()
307        ec.verify_signature(target)
308        ec.verify(target, full=True)
309    except (ec.ComponentProblem, signing.SignatureError, OSError) as exc:
310        raise updater.UpdateError(f"engine {target.version} can no longer be used: {exc}", 5) from None
311    out = updater.switch_engine(ctx, state, folder, target, unpin_if_automatic=True)
312    return {**out, "family": QWEN, "changed": True, "status": "switched"}
313
314
315# ----------------------------------------------------------------------------------------------- delete
316
317def delete_engine(ctx: "updater.Context", family: str, folder: str, root: str | None = None) -> dict:
318    """Delete one installed engine package. Refused (exit 2, nothing changed) for the engine in use and for one a running program uses. Models, settings
319    and the other family are not touched. The folder is renamed away first, so a package that is held open is left whole, not half removed."""
320    shape = shape_of_family(family)
321    if retired.is_name(family):
322        raise updater.UpdateError(retired.NOT_OFFERED, 2)
323    if family not in FAMILIES and shape is None:
324        raise updater.UpdateError("choose the Qwen engine", 2)
325    if not folder or folder != Path(folder).name or folder.startswith("."):
326        raise updater.UpdateError("that is not an installed engine", 2)
327    with updater.update_lock(ctx.components):
328        listing = list_engines(ctx)
329        fam = next((f for f in listing["families"] if f["family"] == family), None)
330        rows = [e for e in (fam["engines"] if fam else []) if e["folder"] == folder and (root is None or e.get("root") in (None, root))]
331        if not rows:
332            raise updater.UpdateError("that engine is not installed (it may have been deleted already)", 2)
333        row = rows[0]
334        if not row["can_delete"]:
335            raise updater.UpdateError(row["delete_blocked"], 2)
336        target = Path(row["path"])
337        aside = target.with_name(f".deleting-{uuid.uuid4().hex[:8]}")
338        try:
339            os.replace(longpath.long_path(target), longpath.long_path(aside))
340        except OSError as exc:
341            raise updater.UpdateError(f"the engine could not be removed because something is using it ({longpath.describe_oserror(exc)}). "
342                                      "Close programs that use Strata and try again; nothing was changed.", 6) from None
343        shutil.rmtree(longpath.long_path(aside), ignore_errors=True)      # a file that is held stays in .deleting-*; the next delete sweeps it
344        _sweep(target.parent)
345        if family == QWEN:
346            state = updater.State(ctx.components)
347            section = state.section("engine")
348            if section.get("previous") == folder:
349                section["previous"] = None
350            if section.get("pinned") == folder:
351                section.pop("pinned", None)
352            if row["version"] not in {e["version"] for e in rows_of(list_engines(ctx), QWEN)}:
353                (section.get("failed") or {}).pop(row["version"], None)
354            state.history({"at": (ctx.now or updater.dt.datetime.now(updater.dt.timezone.utc)).isoformat(), "action": "delete-engine",
355                           "from": row["version"], "to": None, "ok": True})
356            state.save()
357        elif shape is not None:
358            state = updater.State(shape_engine.root(shape, ctx.components))
359            section = state.section("engine")
360            if section.get("pinned") == folder:
361                section.pop("pinned", None)
362            state.history({"at": (ctx.now or updater.dt.datetime.now(updater.dt.timezone.utc)).isoformat(), "action": "delete-shape-engine", "shape": shape,
363                           "from": row["version"], "to": None, "ok": True})
364            state.save()
365        return {"component": ("engine" if family == QWEN else shape_engine.component_id(shape)), "family": family, "status": "deleted", "changed": True, "folder": folder,
366                "version": row["version"], "freed_bytes": row["bytes"]}
367
368
369def rows_of(listing: dict, family: str) -> list[dict]:
370    return next((f["engines"] for f in listing["families"] if f["family"] == family), [])
371
372
373def _sweep(engine_folder: Path) -> None:
374    """Remove what an earlier delete could not (a file that was held open at the time)."""
375    try:
376        for entry in engine_folder.iterdir():
377            if entry.is_dir() and entry.name.startswith(".deleting-"):
378                shutil.rmtree(longpath.long_path(entry), ignore_errors=True)
379    except OSError:
380        pass