okami.mom/strata

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

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

main
8.4 KiB147 linesraw
1"""The `setup` entry point: `strata_control.setup_config.config_for` called with what setup would have decided on a simulated machine.
2
3`setup.py` main() cannot run without a GPU, an engine and a model.  Its last stretch (the engine arguments, the speed switches, the cards, the vision section) is
4now `config_for(inputs, lib)`.  Here the inputs are built from the machine class and the model set by calling setup's OWN decision functions where they are pure
5(`low_ram_wanted`, `unsloth_budget`, `budget_choice`, `low_ram_resident`, `flash_vision_encoder`, ...), and the probes of the machine (nvidia-smi, the disk kind,
6the compute mode, a saved calibration) are answered by `ProbeLib`, a view of the setup module with those few functions replaced.  What is assumed is recorded in the
7`inputs` field of the record, so a reviewer sees it.
8
9Not driven: Intel Arc (setup hands over to sycl/setup_intel.py) and the Mac (metal/setup_mac.py and `mac_dsv41_setup`): other scripts write their configs.
10"""
11
12from __future__ import annotations
13
14import contextlib
15import io
16import os
17import sys
18from argparse import Namespace
19from unittest import mock
20
21from .world import ROOT, World, context_for
22
23NOT_DRIVEN = {
24    "arc_a750": "Intel Arc: setup.py hands over to sycl/setup_intel.py (sycl_setup), which writes its own config; it is not behind a seam yet",
25    "mac_small": "Mac: setup.py hands over to metal/setup_mac.py (mac_setup) and, for DeepSeek, to mac_dsv41_setup(); they write their own configs; not behind a seam yet",
26    "mac_large": "Mac: setup.py hands over to metal/setup_mac.py (mac_setup) and, for DeepSeek, to mac_dsv41_setup(); they write their own configs; not behind a seam yet",
27}
28
29
30class ProbeLib:
31    """setup.py as a library, with the functions that look at the machine answering for the simulated one."""
32
33    def __init__(self, setup_module, world: World):
34        self._m, self._w = setup_module, world
35        m = world.machine
36        self.WIN = m.os == "windows"
37        self.CONTROL = False
38        suffix = ".exe" if self.WIN else ""
39        self.EXE, self.VEXE = "strata" + suffix, "strata-vision" + suffix          # the simulated class decides, not the host the test runs on
40        self._over = {
41            "gpu_compute_mode": lambda index: "Default",
42            "gpu_drives_display": lambda g: False,
43            "linux_desktop": lambda env=None: False,
44            "cpu_sockets": lambda: (1, 16),
45            "is_wsl": lambda: False,
46            "rotational_disk": lambda path: None,
47            "ple_ram_platform_ok": lambda: m.os == "linux",
48            "setup_calibration": lambda cfg, hip: None,
49            "setup_images": lambda a, gpu, hip, models_dir: None,
50            "hipblaslt_table": lambda arch, lib_dirs, ver=None, extra_dirs=(): None,
51            "vision_threads": lambda logical=None: 8,
52            "is_gb10": lambda g: m.key == "dgx_spark",
53            "engine_exe": lambda eng: str(eng / self.EXE),
54        }
55
56    def __getattr__(self, name):
57        if name in self._over:
58            return self._over[name]
59        return getattr(self._m, name)
60
61
62class FakeGGUF:
63    """The model file reader: no tensors, so the n-gram table's size is setup's default."""
64
65    def __init__(self, path):
66        self.tensors = []
67
68
69def _args(world: World, ctx: int) -> Namespace:
70    s = world.mset
71    return Namespace(
72        family=s.family, model=s.model, context=ctx, rope_scaling=None, rope_scale=None, kv=None, vision=None, vision_tokens=None, images=None,
73        experimental_speed_projection=None, port=None, gpu=None, gpus=None, gpu_roles=None, layer_split=None, no_remote_expert_opt=False, host=None,
74        api_key=None, browser=None, data_dir=None, models_dir=str(world.models), gguf_dir=None, yes=True, no_start=True, draft_vocab=None, low_ram="auto",
75        resident_budget_gib=None, vram_reserve_mib=None, mtp=None, drafter=None, parallel=None, replicas=None, replica_profile=False, kv_streaming="auto",
76        backend=None, cuda=None, _roles=None, setup=False, update=False, calibrate=False)
77
78
79def _gpu(setup, world: World) -> dict:
80    m = world.machine
81    if m.backend == "hip":
82        g = {"index": 0, "name": m.card, "vram_gb": 2.0 if m.unified else m.vram_gb, "arch": m.arch_field, "count": 1}   # (an APU: its BIOS carve-out, 2 GB as on the maintainers' box)
83        return setup.amd_apply_uma(g, ram=m.ram_gb)
84    g = {"index": 0, "name": m.card, "vram_gb": m.vram_gb, "arch": str(m.arch_field), "driver": "580.0", "count": 1}
85    if m.unified:                                                    # a DGX Spark: one memory for the CPU and the GPU, counted as gpus() counts it
86        shared = max(0.0, m.ram_gb - setup.UMA_OS_LEFT_GB)
87        g.update({"vram_gb": shared, "uma": True, "dedicated_gb": 0.0, "shared_gb": shared})
88    return g
89
90
91def _qwen(setup, world: World, lib: ProbeLib, say) -> tuple[dict, dict]:
92    from strata_control import setup_config
93    m, s = world.machine, world.mset
94    ram = m.ram_gb
95    hip = m.backend == "hip"
96    family, model = s.family, s.model
97    fam = setup.FAMILIES[family]
98    gpu = _gpu(setup, world)
99    ctx = context_for(m, s)
100    a = _args(world, ctx)
101    with contextlib.redirect_stdout(say):
102        in_budget = bool(setup.MODELS[model].get("budget")) and setup.unsloth_budget(model, ram, gpu, None)
103        budget = setup.budget_choice(model, ram, None) if in_budget else None
104        low_ram = setup.low_ram_wanted(model, ram, "auto")
105        kv = "fp16" if ctx <= 8192 else "int8"
106        vision = setup.hip_vision("yes", gpu["vram_gb"]) if hip else setup.flash_vision_encoder("yes", gpu)
107        reader = None
108        if hip:
109            vision, reader = setup.hip_reader(world.engine_dir, vision, gpu)
110        resident = False
111        if low_ram and not fam.get("ready"):
112            vram = setup.low_ram_vram(gpu) - (setup.VISION[vision]["reserve_mib"] / 1024 if vision != "none" else 0)
113            resident = setup.low_ram_resident(model, ram, vram, ctx, kv, True)
114    tag = fam["tag"] + model
115    shards = [world.gguf_dir / x for x in s.shards]
116    ple = shards[min(1, len(shards) - 1)]
117    model_args = ["--pack", str(world.pack), "--native", str(shards[0]), *(["--ple-gguf", str(ple)] if len(shards) <= 2 else [])]
118    inp = setup_config.SetupInputs(
119        a=a, adopted=None, chosen=[gpu], cuda_tk=13, draft_vocab=None, eng=world.engine_dir, engine_ver=(0, 2, 12), esp=None, fam=fam, family=family,
120        gpu=gpu, hip=hip, in_budget=in_budget, lib_dirs=[], low_ram=low_ram, meta={"version": "0.2.12"}, mmproj=world.models / fam.get("mmproj", setup.MMPROJ),
121        model=model, model_args=model_args, models_dir=world.gguf_dir, multi=[], pack=world.pack, ple=ple, port=8080, q4_split=False, ram=ram,
122        reader=reader, ready=False, rope_scale=1.0, rt=world.mtp, scaling=None, shards=shards, tag=tag, vision=vision, ctx=ctx, kv=kv,
123        resident=resident, budget=budget, GGUFFile=FakeGGUF)
124    summary = {"family": family, "model": model, "ram_gb": ram, "gpu": {k: gpu[k] for k in sorted(gpu) if k not in ("driver",)}, "context": ctx, "kv": kv,
125               "vision": vision, "low_ram": low_ram, "resident": resident, "ram_budget_gib": budget, "in_budget": in_budget, "engine_version": "0.2.12"}
126    with contextlib.redirect_stdout(say):
127        built = setup_config.config_for(inp, lib)
128    return built.cfg, summary
129
130
131def drive_setup(world: World) -> dict:
132    from .driver import engine_start
133    command = f"strata setup --family {world.mset.family} --model {world.mset.model} --yes --no-start"
134    if world.machine.key in NOT_DRIVEN:
135        return {"entry": "setup", "command": command, "not_driven": NOT_DRIVEN[world.machine.key]}
136    if str(ROOT) not in sys.path:
137        sys.path.insert(0, str(ROOT))
138    import setup
139    notes = io.StringIO()
140    lib = ProbeLib(setup, world)
141    # not a hybrid CPU (setup adds --pool-workers on one: Boston's 8 P + 16 E cores changed 12 goldens): the class decides, not the host
142    with world.patched(), mock.patch.object(os, "cpu_count", lambda: 16), mock.patch.object(setup, "cpu_cores", lambda: None), \
143            mock.patch.object(setup, "WIN", lib.WIN),             mock.patch.object(setup, "EXE", lib.EXE), mock.patch.object(setup, "VEXE", lib.VEXE):     # setup's own helpers read these globals: the class decides, not the host
144        cfg, summary = _qwen(setup, world, lib, notes)
145        eng = engine_start(world, dict(cfg))
146    return {"entry": "setup", "command": command, "inputs": summary, "config_file": cfg, "engine": eng,
147            "setup_says": [l.strip() for l in notes.getvalue().splitlines() if l.strip()]}