okami.mom/strata

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

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

main
34.9 KiB568 linesraw
1"""setup.py for an Intel Arc: upstream's installer, steered onto the SYCL port from outside.
2
3    ./setup.sh --backend sycl [setup.py's options]       (this file, run through setup.sh's virtual environment)
4
5The SYCL port keeps out of the shared files (upstream merges stay clean), so this does not edit setup.py: it imports
6it and replaces the few steps that are NVIDIA/AMD-specific, then runs setup's own main().  Everything else - the
7model choice, the download, the pack, the tokenizer, the MTP draft layer, the context and KV questions - is
8setup.py's, unchanged.  What is replaced:
9
10  - the GPU check: the Intel Arc is offered through setup's AMD path (the one that compiles locally), named and
11    sized from sysfs;
12  - the engine step: the SYCL build (build-sycl-aot/strata, run in the strata-sycl-dev image by
13    sycl/serve/strata-sycl.sh; docs/INTEL.md) instead of a CUDA/HIP build;
14  - pictures (on by default on every Arc card, see pictures_on_by_default): read by the portable CPU reader (`strata-vision`, the program the
15    AMD packages carry beside their engine, compiled here by setup's own step) on the host; it hands the image embeddings to the engine through
16    /dev/shm, which strata-sycl.sh shares with the container.  The reader choice is strata_control/vision_reader.py's one rule (CPU reader under
17    24 GB of VRAM); an Arc of 24 GB or more also keeps the CPU reader unless --vision gpu asks for the SYCL one (`strata-vision-sycl`, compiled
18    on the host when the oneAPI compiler is there).  --vision no is the off switch;
19  - the RAM rule: the CUDA engine keeps every expert in RAM, the SYCL port streams them from the GGUF into VRAM
20    (--stream-experts), so RAM only bounds the KV streaming;
21  - the config: the container's paths, the SYCL flags, backend "sycl"; the run script starts
22    sycl/serve/server_intel.py (serve/server.py plus the Intel Monitor readings and the model menu).
23
24When setup.py changes the steps this relies on, this stops with a message rather than writing a wrong config.
25"""
26from __future__ import annotations
27
28import json
29import os
30import re
31import subprocess
32import sys
33from pathlib import Path
34
35ROOT = Path(__file__).resolve().parent.parent
36sys.path.insert(0, str(ROOT))
37import setup as S  # noqa: E402
38from strata_control import intel_spec, vram_fit  # noqa: E402
39
40SYCL_WRAPPER = ROOT / "sycl" / "serve" / "strata-sycl.sh"
41SYCL_IMAGE = "strata-sycl-dev"
42SERVER = ROOT / "sycl" / "serve" / "server_intel.py"
43MOUNT = Path(os.environ.get("STRATA_SYCL_ROOT") or ROOT.parent)   # what strata-sycl.sh mounts at /work
44
45# Battlemage / Alchemist PCI device ids -> (name, VRAM GB). lspci's database lags new cards (an Arc Pro B70 reads
46# "Intel Corporation Device [8086:e223]"), so the sysfs id is the reliable signal and the name table is ours.
47INTEL_ARC = {"e223": ("Arc Pro B70", 32.0), "e222": ("Arc Pro B65", 32.0), "e221": ("Arc Pro B60", 24.0), "e211": ("Arc Pro B60", 24.0),
48             "e20b": ("Arc B580", 12.0),
49             "e20c": ("Arc B570", 10.0), "e212": ("Arc B50", 16.0),
50             "56a0": ("Arc A770", 16.0), "56a1": ("Arc A750", 8.0), "56a2": ("Arc A580", 8.0),
51             "56a5": ("Arc A380", 6.0), "56a6": ("Arc A310", 4.0), "5690": ("Arc A770M", 16.0)}
52
53# Alchemist (DG2, the A-series) has no FP64 hardware and carries the driver's FP64 emulation. On i915 (the A750) a
54# single sycl::malloc_host past ~3 GiB also fails, so the experts load into a CPU-computed RAM arena instead of the
55# pinned mirror (--mmap-experts + STRATA_VERIFY_NO_HOST=0 - docs/INTEL.md, "Arc A750"). On xe (the A770) the mirror is
56# built in chunks past that limit and the A-series uses the ordinary streamed path; see to_sycl().
57ALCHEMIST_IDS = frozenset({"56a0", "56a1", "56a2", "56a5", "56a6", "5690"})
58
59
60def intel_gpus():
61    """Intel discrete GPUs from sysfs: vendor 0x8086 under the xe or i915 driver, named by PCI device id. VRAM comes
62    from the id table, else from the size of the card's VRAM BAR."""
63    found = []
64    for card in sorted(Path("/sys/class/drm").glob("card[0-9]*")):
65        if "-" in card.name:                            # connectors (card0-DP-1) share the card's device
66            continue
67        dev = card / "device"
68        try:
69            vendor = (dev / "vendor").read_text().strip().lower()
70            devid = (dev / "device").read_text().strip().lower().replace("0x", "")
71            driver = os.path.basename(os.path.realpath(dev / "driver")) if (dev / "driver").exists() else ""
72        except OSError:
73            continue
74        if vendor != "0x8086" or driver not in ("xe", "i915"):
75            continue
76        name, vram = INTEL_ARC.get(devid, (None, 0.0))
77        if name is None:
78            if driver != "xe":                          # i915 without a known Arc id is an integrated GPU
79                continue
80            name = f"Intel GPU {devid} (xe)"
81        if not vram:                                    # resource line 2 (BAR 2) is the VRAM aperture on xe cards
82            try:
83                start, end, _ = (dev / "resource").read_text().splitlines()[2].split()
84                vram = (int(end, 16) - int(start, 16) + 1) / 2**30
85            except (OSError, IndexError, ValueError):
86                vram = 0.0
87        found.append({"index": len(found), "name": f"Intel {name}", "vram_gb": vram, "arch": driver, "driver": driver,
88                      "devid": devid})
89    return found
90
91
92def real_mem_have(mem_have, real_ram: float, fake_ram: float):
93    """setup.mem_have for the Intel path: the RAM it is given is the 1024 GB stand-in of setup's RAM rule, so a model that counts VRAM + RAM
94    (Gyro) would never warn; it gets the real RAM."""
95    return lambda model, ram, vram=0.0: mem_have(model, real_ram if ram >= fake_ram else ram, vram)
96
97
98def sycl_engine():
99    """The SYCL build: (binary, why-not)."""
100    if S.WIN:
101        return None, "the SYCL port runs on Linux only"
102    exe = next((b for b in (ROOT / "build-sycl-aot" / "strata", ROOT / "build-sycl" / "strata") if b.exists()), None)
103    if exe is None:
104        return None, "it is not built (docs/INTEL.md, \"How to build it\": Docker, then sycl/tools/build.sh in the image)"
105    return exe, None
106
107
108def sycl_path(path) -> str:
109    """A host path as the engine's container sees it: the folder above the Strata checkout (or STRATA_SYCL_ROOT) is
110    mounted at /work."""
111    p, root = Path(path).resolve(), MOUNT.resolve()
112    try:
113        return "/work/" + p.relative_to(root).as_posix()
114    except ValueError:
115        S.fail(f"{p} is outside {root}, which the SYCL engine's container mounts",
116               f"keep the models and the data folder under {root} (--models-dir / --data-dir)")
117
118
119def sycl_version() -> str:
120    return S.source_version()
121
122
123def flag(args, name):
124    return args[args.index(name) + 1] if name in args else None
125
126
127def drop(args, name, value=False):
128    while name in args:
129        i = args.index(name)
130        del args[i:i + 1 + int(value)]
131
132
133# Pictures on an Intel Arc: the CPU reader encodes on the host and the embeddings reach the engine through /dev/shm.  Tested end to end
134# on the Arc A750 (i915, Alchemist; 2026-10-19, docs/INTEL.md): 47 picture requests (shapes, text, two pictures in one request, a picture in the
135# history, text after pictures) through the CPU reader and the same through the SYCL GPU reader, in the container and outside it, no GPU fault.
136# Owner decision 2026-10-22: an Arc B-series (Battlemage, xe) card is allowed to run like any Arc, pictures included.  The first picture request on the
137# Arc Pro B70 (engine 0.1.45 SYCL, IQ3_S, 2026-10-19) hung the GPU with the CPU reader: an xe engine reset (ccs + bcs) and "Fault response:
138# Unsuccessful -EINVAL", the request ended 503.  That fault has not been looked at again (the B70 is gone), so it is a known risk, not a refusal:
139# pictures are on, the CPU reader is kept, and the person is told once that the card is new to Strata and how to report a problem.
140PICTURES_ON_BY_DEFAULT_IDS = ALCHEMIST_IDS | frozenset(INTEL_ARC)      # every Arc card setup knows
141
142
143def pictures_on_by_default(driver: str, devid: str = "") -> bool:
144    """Pictures are on in setup's default for every Arc card (they were opt-in on a B-series card until 2026-10-22)."""
145    return True
146
147
148def is_b_series(driver: str, devid: str = "") -> bool:
149    """A Battlemage (B-series) card: on xe and not an Alchemist id (an unknown id on xe counts as one: it is newer than the A-series)."""
150    return driver != "i915" and devid not in ALCHEMIST_IDS
151
152
153B_SERIES_LINE = ("This Intel Arc B-series card is new to Strata and we have not tested it ourselves, so pictures and long answers may fail on it. "
154                 "If something fails, run again with --vision no to turn pictures off, and tell us at https://github.com/Niko1221/Strata/issues "
155                 "(say it is a B-series card and attach the engine log).")
156
157
158READER_DIR = ROOT / "engine-sycl"    # the folder setup treats as the engine's: BUILD.json and, for pictures, the CPU reader strata-vision
159
160
161def intel_vision(asked, vram_gb: float = 0.0) -> str:
162    """The picture reader wanted on an Intel Arc, by strata_control/vision_reader.py's rule: "none" when switched off, "cpu" by default (under 24 GB
163    of VRAM the CPU reader is the rule, and an Arc of 24 GB or more keeps it too until the SYCL reader has run on such a card), "gpu" only when
164    asked for.  Takes setup.hip_vision's arguments."""
165    from strata_control import vision_reader as VR
166    return VR.wanted(asked, vram_gb, "intel")
167
168
169def oneapi_compiler():
170    """The oneAPI icx / icpx on this PC (PATH, else /opt/intel/oneapi), or None."""
171    import glob
172    import shutil
173    cc, cxx = shutil.which("icx"), shutil.which("icpx")
174    if not (cc and cxx):
175        found = sorted(glob.glob("/opt/intel/oneapi/compiler/*/bin/icpx"))
176        cxx = found[-1] if found else None
177        cc = str(Path(cxx).with_name("icx")) if cxx else None
178    return (cc, cxx) if cc and cxx and Path(cc).exists() else None
179
180
181def oneapi_environment() -> dict:
182    """The environment setvars.sh makes (the SYCL reader's build needs MKL and the compiler's libraries); {} when there is no setvars.sh."""
183    setvars = Path("/opt/intel/oneapi/setvars.sh")
184    if not setvars.is_file():
185        return {}
186    out = subprocess.run(["/bin/bash", "-c", f". {setvars} >/dev/null 2>&1; env -0"], capture_output=True, check=False).stdout
187    return dict(item.split("=", 1) for item in out.decode("utf-8", "replace").split("\0") if "=" in item)
188
189
190def build_vision_sycl_reader(stub: Path, llama) -> bool:
191    """Compile tools/vision with STRATA_VISION_SYCL into `stub`/strata-vision-sycl.  False (and the reason said) when the oneAPI compiler is
192    not on this PC or the build fails: the CPU reader is there, pictures still work."""
193    import shutil
194    compiler = oneapi_compiler()
195    if compiler is None:
196        S.warn("the GPU picture reader needs the oneAPI compiler (icx / icpx), which is not on this PC: pictures are read on the CPU "
197               "(a few seconds each); install intel-oneapi-compiler-dpcpp-cpp and intel-oneapi-mkl-devel to build it")
198        return False
199    S.say("  Compiling the picture reader for your Intel GPU (a few minutes, once) ...")
200    saved = dict(os.environ)
201    try:
202        os.environ.update(oneapi_environment())
203        S.cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision-sycl", "strata-vision",
204                      [f"-DLLAMA_DIR={S.vision_llama(llama)}", "-DSTRATA_VISION_SYCL=ON", "-DSTRATA_PORTABLE=OFF",
205                       f"-DCMAKE_C_COMPILER={compiler[0]}", f"-DCMAKE_CXX_COMPILER={compiler[1]}"], None, "")
206        shutil.copy2(ROOT / "build-vision-sycl" / "bin" / "strata-vision-sycl", stub / "strata-vision-sycl")
207    except SystemExit:
208        raise
209    except Exception as e:                               # noqa: BLE001 - the CPU reader is there; pictures work without the GPU one
210        S.warn(f"the GPU picture reader did not compile ({e}): pictures are read on the CPU")
211        return False
212    finally:
213        os.environ.clear()
214        os.environ.update(saved)
215    return True
216
217
218def build_vision_sycl(stub: Path, stamp: Path, llama, vsrc) -> None:
219    meta = json.loads(stamp.read_text(encoding="utf-8"))
220    if (stub / "strata-vision-sycl").exists() and meta.get("vision_gpu_src") == vsrc:
221        return
222    if build_vision_sycl_reader(stub, llama):
223        stamp.write_text(json.dumps({**meta, "vision": "gpu", "vision_gpu": "strata-vision-sycl", "vision_gpu_src": vsrc}, indent=1))
224        S.ok(f"picture reader (GPU): {stub / 'strata-vision-sycl'}, (CPU fallback): {stub / 'strata-vision'}")
225
226
227SYCL_PROFILE = "expert-profile-sycl.bin"   # data/: the xe cards' expert ranking (to_sycl)
228SMALL_CARD_GB = 12.0       # under this the engine's own advice is --vram-reserve-mib 300 (a 1024 MiB reserve leaves an
229                           # 8 GB card no room for even one expert slot) and the English draft vocabulary
230SMALL_RESERVE_MIB = 300
231
232
233def small_card(vram_gb: float, driver: str) -> bool:
234    return 0 < vram_gb < SMALL_CARD_GB or driver == "i915"
235
236
237# #1980: on a layer split the host mirror covers the first stage only, so with STRATA_VERIFY_NO_HOST=1 (strata-sycl.sh's
238# default) a later stage that cannot hold all of its layers' experts is REFUSED at the start.  Measured on 2x Arc Pro B60
239# 24 GB with the trim and a 1024 MiB reserve: IQ3_XXS (42.9 GB of experts, 89% of the 48 GB) stage 1 2230-3731 experts
240# short and refused; NO_HOST=0 runs it at 39-50 tok/s with 0 faults.  IQ2_XS (35.5 GB, 74%) loads 100% resident.
241SPLIT_SHORT_FRACTION = 0.80
242
243
244def split_likely_short(arena_gb: float, vram_gbs: list) -> bool:
245    """True when the model's experts take so much of the split cards' VRAM that a later stage will not hold all of its
246    layers' experts (the dense weights, the KV, the prompt buffers, the drafter and the reserve take the rest)."""
247    total = sum(v for v in vram_gbs if v and v > 0)
248    return arena_gb > 0 and total > 0 and arena_gb > SPLIT_SHORT_FRACTION * total
249
250
251PREFILL_BMG_MIN_GB = 24.0   # a Battlemage card with this much VRAM runs the prompt in 8,192-token chunks (to_sycl)
252
253
254def recommended_prefill(vram_gb: float, ctx: int, driver: str = "xe", devid: str = "") -> tuple:
255    """(chunk size, one plain line saying why or "").  4096 everywhere (to_sycl's old rule), except a Battlemage card (xe
256    driver, not an A-series) with 24 GB or more and a context over 32K, where the prompt borrows cache slots: 8192.
257    Measured on the Arc Pro B70 (IQ3_S, 128K context, setup's flags, 2 interleaved rounds): a 16K prompt 1,222 -> 1,347-1,362
258    tok/s (+10-11%), a 32K prompt 1,187 -> 1,361-1,383 (+15-16%), the same 32 greedy tokens, the same 11,795 cache slots (the
259    lent slots are refilled after the prompt), decode after it unchanged (38 tok/s).  With the 32K context (own prompt
260    buffers) a bigger chunk takes 1,400 cache slots from the decode (-9..-16% decode for +20% prompt), so that stays 4096."""
261    bmg = driver != "i915" and devid not in ALCHEMIST_IDS and devid in INTEL_ARC
262    if bmg and vram_gb >= PREFILL_BMG_MIN_GB and ctx > 32768:
263        return 8192, ("prompt reading: chunks of 8,192 tokens on this Arc (the prompt borrows cache slots, so decode keeps all "
264                      "of them): 10-16% faster on 16K-32K prompts than 4,096 (change --prefill in the config to pick another)")
265    return 4096, ""
266
267
268def _model_title(model: str, args: list) -> str:
269    """The plain name for the fit line: Gyro-M / Gyro-S from the catalog name or the GGUF's file name, else the catalog name."""
270    low = (model + " " + (flag(args, "--native") or "")).lower()
271    for key, title in (("gyro-m", "Gyro-M"), ("gyro-s", "Gyro-S")):
272        if key in low:
273            return title
274    return model if model and "/" not in model and chr(92) not in model else ""
275
276
277def to_sycl(cfg: dict, exe: Path, ram: float, keep: dict, vram_gb: float = 0.0, driver: str = "xe",
278            devid: str = "", fit_notes: list | None = None, model: str = "", ctx_asked: bool = False,
279            auto_reserve: bool = False, fit: bool = True) -> dict:
280    """setup's config (written for its HIP path) -> the SYCL port's: the container's paths, experts streamed from the
281    GGUF into VRAM (--stream-experts: the engine reads them from the GGUF and keeps what does not fit in a pinned RAM
282    mirror; the VRAM reserve is the smallest that leaves the KV and the prompt buffers room - docs/INTEL.md), KV
283    streaming from 64K up when the RAM holds the KV (the B70 at 256K decodes at 40+ tok/s with it, 4-9 without).
284    A reserve the user asked for (--vram-reserve-mib) is kept.
285
286    0.2.2: a model that does not fit the card at the default context (Gyro-M on the 8 GB A750 is ~750 MiB short of one cache
287    slot) gets a smaller prompt chunk and then a lower reserve until it does, never a smaller context (owner, 2026-11-02;
288    strata_control/vram_fit.py); one plain line per change goes to `fit_notes`.  A config that fits comes back as it was.
289    `ctx_asked` / a reserve without `auto_reserve`: the user chose it, it is kept.  `fit=False`: a layer split.
290
291    An Alchemist card (the A-series, i915 or xe) has no FP64 hardware, so its config carries the driver's FP64
292    emulation (a kernel on the sampled path declares double). On i915 (the A750) the experts load into a RAM arena
293    and the CPU computes the ones the card does not hold (--ple-io ram, STRATA_VERIFY_NO_HOST=0 - docs/INTEL.md,
294    "Arc A750"). On xe (the A770) the experts are streamed into VRAM like any other Arc; the mirror is built in
295    chunks so DG2's >3 GiB single pinned-host allocation limit is not hit, and the build passes
296    -ze-opt-greater-than-4GB-buffer-required so the prompt path is correct past the cache's 4 GiB (docs/INTEL.md,
297    "Kernels misread memory more than 4 GiB into an allocation")."""
298    args = list(cfg["args"])
299    for f in ("--resident-experts", "--mmap-experts"):  # setup's low-RAM mode is the CUDA engine's
300        drop(args, f)
301    drop(args, "--kv-resident", True)                   # decided below on the real RAM
302    if driver != "i915" and "--expert-profile" in args and (ROOT / "data" / SYCL_PROFILE).is_file():
303        # 0.1.43: a card on xe runs every expert on the GPU (the ones the cache does not hold are read from the pinned mirror
304        # by the same kernels), so WHICH experts the cache holds changes speed and no token: data/expert-profile-sycl.bin
305        # ranks them from the routing of 45 varied prompts (chat, code, maths, six languages) and eight document summaries,
306        # where the shipped profile holds 60% of a chat prompt's experts and 85% of a summary's (B70: +9..25% decode on prompts left
307        # out of it, same tokens).  Another profile the user chose is kept; i915 keeps the shipped one (there the CPU
308        # computes the misses, so the residency moves roundings).
309        i = args.index("--expert-profile") + 1
310        if args[i].replace("\\", "/").rsplit("/", 1)[-1] == "expert-profile.bin":
311            args[i] = args[i][:-len("expert-profile.bin")] + SYCL_PROFILE
312    for f in ("--pack", "--native", "--ple-gguf", "--expert-profile", "--mtp", "--control-vector-scaled"):
313        if f in args:
314            v = args[args.index(f) + 1]
315            path, _, scale = v.rpartition(":") if f == "--control-vector-scaled" else (v, "", "")
316            args[args.index(f) + 1] = sycl_path(path) + (f":{scale}" if scale else "")
317    ctx = int(flag(args, "--max-context") or 32768)
318    kv = flag(args, "--kv") or "int8"
319    asked_reserve = flag(args, "--vram-reserve-mib")    # setup writes it only when the user gave it
320    drop(args, "--vram-reserve-mib", True)
321    reserve = asked_reserve or (str(SMALL_RESERVE_MIB) if small_card(vram_gb, driver) else
322                                "1024" if ctx <= 32768 else "2048")
323    new_prefill = None
324    if fit and vram_gb:
325        pf = flag(args, "--prefill")
326        fr = vram_fit.plan(model or (flag(args, "--native") or ""), vram_gb, ctx, kv, int(reserve), pf or "auto", "intel",
327                           title=_model_title(model, args), ctx_fixed=ctx_asked,
328                           reserve_fixed=bool(asked_reserve) and not auto_reserve,
329                           prefill_fixed=pf not in (None, "auto"))
330        if fr.changed:
331            if fr.ctx != ctx:
332                if "--max-context" in args:
333                    args[args.index("--max-context") + 1] = str(fr.ctx)
334                else:
335                    args += ["--max-context", str(fr.ctx)]
336                ctx = fr.ctx
337            reserve = str(fr.reserve_mib)
338            new_prefill = fr.prefill
339            if fit_notes is not None:
340                fit_notes.append(fr.line)
341    kv_ram = ctx * (13 * (576 if kv == "q4_0" else 1056)) / 1e9
342    if kv != "k8v4" and ctx >= 65536 and ram >= kv_ram + 6:
343        args += ["--kv-resident", "32768"]
344    alchemist = driver == "i915" or devid in ALCHEMIST_IDS
345    if driver == "i915":
346        # Arc A-series on i915 (the A750): the experts load into an ordinary RAM arena and the CPU computes the ones
347        # the card does not hold; the n-gram table is kept in RAM (setup's rotational-disk rule) and no mirror is built.
348        # Gyro: its n-gram table is half of the 58-92 GB file and stays on the SSD (read row by row); the RAM holds the
349        # experts' arena (24 GB for Gyro-S) and the CPU's work, so a table in RAM would not fit beside them on a 64 GB PC
350        gyro = "gyro" in (flag(args, "--native") or "").lower()
351        if "--ple-io" not in args and not gyro:
352            args += ["--ple-io", "ram"]
353        args += ["--vram-reserve-mib", reserve]
354    else:
355        args += ["--stream-experts", "--vram-reserve-mib", reserve]
356    if ctx > 32768 or vram_gb >= 24:                    # long contexts: 4096-token chunks keep the prompt buffers small; a
357        # 24 GB+ card with part of the experts in the RAM mirror streams those over PCIe once per chunk, so fewer, bigger
358        # chunks read the prompt faster (Arc Pro B70, IQ3_S, a 4,095-token prompt: 2,048-token chunks 618 tok/s, 4,096: 1,002;
359        # docs/INTEL.md); it costs ~700 cache slots.  A Battlemage card with the prompt borrowing cache slots reads 8,192.
360        # A chunk size the user already put in the config is kept: this is a recommendation, not a rule.
361        if flag(args, "--prefill") in (None, "auto", "2048", "4096", "8192"):
362            drop(args, "--prefill", True)
363            args += ["--prefill", str(recommended_prefill(vram_gb, ctx, driver, devid)[0])]
364    if new_prefill:                                     # the fit rule's smaller prompt chunk (the card cannot spare 2048-token buffers)
365        if "--prefill" in args:
366            args[args.index("--prefill") + 1] = new_prefill
367        else:
368            args += ["--prefill", new_prefill]
369    out = {k: v for k, v in cfg.items() if k not in ("lib_dirs", "env", "gpus")}   # "vision" stays: the CPU reader runs on the host
370    out.update({"backend": "sycl", "exe": str(SYCL_WRAPPER), "args": args, "sycl_root": str(MOUNT)})
371    env = {}
372    if alchemist:
373        if driver == "i915":
374            # on i915 the CPU computes the misses and the GPU waits for them at every layer (NO_HOST=0). On xe the
375            # experts are streamed and the mirror is used, so strata-sycl.sh's NO_HOST=1 default stands.
376            env["STRATA_VERIFY_NO_HOST"] = "0"
377        # an Alchemist has no FP64 hardware: a kernel that declares double (one is on the sampled path) is refused at its
378        # first launch - "'double' is not supported in ... device", the engine dies on the first request with a
379        # temperature - unless the driver emulates it (docs/INTEL.md)
380        env.update({"IGC_EnableDPEmulation": "1", "OverrideDefaultFP64Settings": "1", "NEOReadDebugKeys": "1"})
381    if exe != ROOT / "build-sycl-aot" / "strata":
382        env["STRATA_SYCL_BIN"] = exe.relative_to(ROOT).as_posix()
383    if MOUNT.resolve() != ROOT.parent.resolve():
384        env["STRATA_SYCL_ROOT"] = str(MOUNT)
385    if env:
386        out["env"] = env
387    out.update(keep)
388    return out
389
390
391def install(argv) -> None:
392    intel = [] if S.WIN else intel_gpus()
393    if not intel:
394        S.fail("no Intel Arc found (an xe or i915 card in /sys/class/drm)", "on an NVIDIA or AMD card, run ./setup.sh")
395    exe, why = sycl_engine()
396    if exe is None:
397        S.fail(f"Strata's SYCL engine cannot be used: {why}", "docs/INTEL.md: build it, then run this again")
398    for name in ("gpus", "amd_gpus", "amd_problem", "hip_vision", "build_engine_hip", "hipblaslt_table", "ram_gb",
399                 "write_run_script", "start", "say", "main"):
400        if not callable(getattr(S, name, None)):
401            S.fail(f"setup.py has no {name}() any more: sycl/setup_intel.py needs updating for this setup.py")
402
403    real_ram = S.ram_gb()
404    # what the person chose on the command line is kept by the fit rule (vram_fit); the small-card reserve added below is not theirs
405    asked_ctx = any(a == "--context" or a.startswith("--context=") or a == "--max-context" for a in argv)
406    asked_reserve = any(a == "--vram-reserve-mib" or a.startswith("--vram-reserve-mib=") for a in argv)
407    keep = {}                                          # hand-set keys setup does not write: kept across a rerun
408    for p in ROOT.glob("strata-*.json"):
409        try:
410            c = json.loads(p.read_text(encoding="utf-8-sig"))
411            keep[p.name] = {k: c[k] for k in ("model_switcher", "sampling") if k in c}
412        except (OSError, ValueError):
413            pass
414    stub = READER_DIR                                   # setup reads the engine's BUILD.json; the SYCL build has none.  A folder that
415    stub.mkdir(exist_ok=True)                           # stays: the picture reader in it is what the run config points at
416    try:
417        stamped = json.loads((stub / "BUILD.json").read_text(encoding="utf-8"))   # keeps what the reader's build recorded
418    except (OSError, ValueError):
419        stamped = {}
420    (stub / "BUILD.json").write_text(json.dumps({**stamped, "version": sycl_version(), "source": "local", "lib_dirs": []}))
421
422    say = S.say
423    fake_ram = max(real_ram, 1024.0)
424    alch = intel[0]["driver"] == "i915" or intel[0].get("devid") in ALCHEMIST_IDS
425
426    def say_intel(msg=""):
427        """setup's words for its AMD path and its RAM rule, said for the Intel card."""
428        msg = str(msg).replace("(AMD, experimental: docs/AMD_HIP.md)", "(Intel Arc: the SYCL port, docs/INTEL.md)")
429        msg = msg.replace("Your AMD GPUs:", "Your Intel GPUs:").replace("just run ./setup.sh", "just run ./setup.sh --backend sycl")
430        msg = re.sub(r"\b(xe|i915) \(AMD: docs/AMD_HIP\.md\)", r"\1 driver (Intel Arc: docs/INTEL.md)", msg)
431        where = ("the experts the card does not hold are computed on the CPU" if alch
432                 else "the experts are streamed into VRAM")
433        msg = msg.replace(f"RAM: {fake_ram:.0f} GB", f"RAM: {real_ram:.0f} GB ({where})")
434        msg = msg.replace(f"({fake_ram:.0f} GB RAM +", f"({real_ram:.0f} GB RAM +").replace(f"you have {fake_ram:.0f} GB RAM", f"you have {real_ram:.0f} GB RAM")
435        if re.match(r"\s+\S+\s+needs ~\d+ GB RAM:", msg):   # --check's CUDA verdicts: replaced by the Intel one
436            m = msg.split()[0]
437            d = S.MODELS.get(m, {})
438            shard1 = d.get("download_gb", 0) - 28.8          # all but the per-layer lookup table (read from disk)
439            room = intel[0]["vram_gb"] - 3 + max(0.0, real_ram - 10)   # VRAM, plus a pinned host mirror (or the CPU)
440            msg = (f"  {m:8s} ~{shard1:.0f} GB of weights: " +
441                   ("fits in VRAM" if shard1 <= intel[0]["vram_gb"] - 1.5 else
442                    "fits, the experts the card does not hold are computed on the CPU (slower)" if alch and shard1 <= room else
443                    "fits with part of its experts mirrored in RAM (slower)" if shard1 <= room else "does not fit"))
444        say(msg)
445    S.say = say_intel
446    S.gpus = lambda *a, **k: []
447    S.amd_gpus = lambda *a, **k: intel
448    S.amd_problem = lambda g: None
449    S.hip_vision = intel_vision                         # pictures on by default, read on the CPU (setup's hip_reader settles it)
450
451    def build_engine_hip(gpu, llama, vision="none"):
452        """No engine to compile here (the SYCL build is separate); the picture readers are: the portable CPU reader, once, and for
453        --vision gpu the SYCL GPU reader (a few minutes, once; it needs the oneAPI compiler on this PC, else the CPU reader stays)."""
454        if vision != "none":
455            stamp = stub / "BUILD.json"
456            vsrc = S.source_hash(S.VISION_SOURCES)
457            S.build_vision_cpu(stub, stamp, json.loads(stamp.read_text(encoding="utf-8")), llama, vsrc)
458            if vision == "gpu":
459                build_vision_sycl(stub, stamp, llama, vsrc)
460        return stub
461    S.build_engine_hip = build_engine_hip
462    S.hipblaslt_table = lambda *a, **k: None
463    S.ram_gb = lambda: fake_ram                         # the experts are in VRAM: setup's RAM rule does not apply
464    # Gyro (mem_total) counts VRAM + RAM together and is the one family whose experts are NOT streamed from the file into VRAM: on
465    # an Arc they sit in the RAM arena and the CPU computes what the card does not hold.  Its memory warning ("needs 27.6 GB of VRAM +
466    # RAM together, you have ...", never a refusal) therefore reads the real RAM, not the 1024 GB above.
467    S.mem_have = real_mem_have(S.mem_have, real_ram, fake_ram)
468
469    bench_tips = S.bench_tips
470
471    def bench_tips_intel(args, env, ram, *a, **k):
472        """The tips as written for the CUDA engine, said with the real RAM (the 1024 GB above is only for the RAM rule);
473        the --prefill auto:32768 one was measured on the CUDA engine and is left out."""
474        return [t for t in bench_tips(args, env, real_ram, *a, **k) if "auto:32768" not in t]
475    S.bench_tips = bench_tips_intel
476
477    write = S.write_run_script
478
479    def write_run_script(model, cfg_path, port, open_browser=True):   # setup.write_run_script's signature (#870)
480        cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8"))
481        # the card setup selected (--gpu / the first usable), not intel[0]: on a PC with two Arcs the config must match
482        # the chosen one (docs/INTEL.md, "Two cards"). intel_gpus() lists them in sysfs card order and cfg["gpu"] is
483        # that index (setup.py's amd path); a layer split writes a list, and then every listed card is used.
484        gsel = cfg.get("gpu")
485        split = isinstance(gsel, list)
486        idx = gsel if isinstance(gsel, int) and 0 <= gsel < len(intel) else 0
487        sel = intel[idx]
488        fit_notes = []
489        cfg = to_sycl(cfg, exe, real_ram, keep.get(Path(cfg_path).name, {}), sel["vram_gb"], sel["driver"],
490                      sel.get("devid", ""), fit_notes=fit_notes, model=model, ctx_asked=asked_ctx,
491                      auto_reserve=not asked_reserve, fit=not split)
492        for line in fit_notes:                              # one plain line: what was chosen and why (never a refusal)
493            S.say("  " + line)
494        if len(intel) > 1:                                  # pin the SYCL device(s)
495            # the Level Zero order followed the sysfs card order on the tested machines; a machine where it does not
496            # needs an explicit ONEAPI_DEVICE_SELECTOR (kept if the user set one)
497            selector = "level_zero:*" if split else f"level_zero:{idx}"
498            cfg.setdefault("env", {}).setdefault("ONEAPI_DEVICE_SELECTOR", selector)
499        if split:
500            # #1980: without it every card keeps a full copy of the dense weights (1.4 GiB each on Flash-Next IQ2_XS) and the
501            # load stops at 96-97% resident; the later stage's missing experts have no host mirror (STRATA_VERIFY_NO_HOST)
502            cfg.setdefault("env", {}).setdefault("STRATA_STAGE_TRIM", "1")
503            # #1980: a later stage short of VRAM is refused under NO_HOST=1; with the host path on it runs (the host
504            # computes those experts).  Only when the experts will likely not fit; a value the user set is kept.
505            cards = [intel[i]["vram_gb"] for i in gsel if isinstance(i, int) and 0 <= i < len(intel)]
506            arena = S.MODELS.get(model, {}).get("arena_gb", 0)
507            if split_likely_short(arena, cards) and "STRATA_VERIFY_NO_HOST" not in cfg["env"]:
508                cfg["env"]["STRATA_VERIFY_NO_HOST"] = "0"
509                S.say(f"  {model}'s {arena:.0f} GB of experts will likely not all fit the {len(cards)} cards' "
510                      f"{sum(cards):.0f} GB of VRAM: the config sets STRATA_VERIFY_NO_HOST=0, so the CPU computes the "
511                      "experts the later card does not hold instead of the start being refused (#1980). Set it to 1 "
512                      "in the config's env if your cards hold everything; a smaller model fits fully (docs/INTEL_ARC.md)")
513            # exactly two Battlemage cards: --spec 2 (the engine pipelines the two cards' windows by default there and then answers
514            # as a 2-token window whatever --spec says; strata_control/intel_spec.py).  The person's own --spec always wins.
515            cards_used = [intel[i] for i in gsel if isinstance(i, int) and 0 <= i < len(intel)]
516            spec_note = intel_spec.apply_to_config(cfg, cards_used)
517            if spec_note:
518                S.say("  " + spec_note)
519        need = S.MODELS.get(model, {}).get("ram_gb", 0)
520        sel_alch = sel["driver"] == "i915" or sel.get("devid") in ALCHEMIST_IDS
521        if sel_alch and need and real_ram < need:
522            S.warn(f"{model} on this Arc computes the experts the card does not hold on the CPU (about {need} GB of "
523                   f"weights; this PC has {real_ram:.0f} GB of RAM): the start will be slow or fail - a smaller model "
524                   "(--model) fits better (docs/INTEL.md)")
525        if flag(cfg["args"], "--prefill") == "8192":
526            why = recommended_prefill(sel["vram_gb"], int(flag(cfg["args"], "--max-context") or 32768), sel["driver"],
527                                      sel.get("devid", ""))[1]
528            if why:
529                S.say("  " + why)
530        Path(cfg_path).write_text(json.dumps(cfg, indent=1), encoding="utf-8")
531        script = write(model, cfg_path, port, open_browser)
532        script.write_text(script.read_text().replace(str(ROOT / "serve" / "server.py"), str(SERVER)))
533        return script
534    S.write_run_script = write_run_script
535
536    start = S.start
537
538    def start_sycl(cfg_path, *a, **k):
539        cfg = json.loads(Path(cfg_path).read_text(encoding="utf-8-sig"))
540        if cfg.get("backend") != "sycl":
541            return start(cfg_path, *a, **k)
542        script = ROOT / f"run-{Path(cfg_path).stem[len('strata-'):]}.sh"
543        S.say(f"\nstarting {script.name} ...")
544        os.execv("/bin/sh", ["/bin/sh", str(script)])
545    S.start = start_sycl
546
547    argv = list(argv)
548    if small_card(intel[0]["vram_gb"], intel[0]["driver"]):   # the engine's own advice for a card this size
549        if "--draft-vocab" not in argv:
550            argv += ["--draft-vocab", "en"]             # ~110 MiB less VRAM than the default CJK subset
551        if "--vram-reserve-mib" not in argv:
552            argv += ["--vram-reserve-mib", str(SMALL_RESERVE_MIB)]
553    sys.argv = [str(ROOT / "setup.py"), *argv]
554    if "--backend" not in argv:
555        sys.argv += ["--backend", "hip"]
556    if is_b_series(intel[0]["driver"], intel[0].get("devid", "")):
557        S.say("  " + B_SERIES_LINE)
558    if "--low-ram" not in argv:
559        sys.argv += ["--low-ram", "off"]
560    sys.exit(S.main())
561
562
563if __name__ == "__main__":
564    try:
565        install(sys.argv[1:])
566    except KeyboardInterrupt:
567        S.say("\nstopped.")
568        sys.exit(1)