From 83f2a2c73a32cc763efc60ca4cc542c3037b45a9 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 20:33:08 +0200 Subject: [PATCH 01/26] model list: Qwen3.6-35B-A3B has its three sizes (the first-run page showed no versions) The catalog only walked setup.FAMILIES; Qwen3.6 lives in OWN_PATH_FAMILIES, so the app's Qwen3.6 page had an empty list. strata_models now lists its sizes (download, memory, minimum engine 0.1.45, pictures) and strata_install plans them. --- tools/strata_mcp.py | 59 ++++++++++++++++++++++++++++++++-------- tools/test_strata_mcp.py | 33 ++++++++++++++++++++++ 2 files changed, 80 insertions(+), 12 deletions(-) diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 95ddc8e3..6a6ebabe 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -116,6 +116,7 @@ FALLBACK_FAMILIES = { "~80 GB of RAM to keep every expert in RAM", "tag": "nvfp4-"}, } +OWN_PATH_ENGINE = (0, 1, 45) # the first engine that runs Qwen3.6-35B-A3B with pictures and parallel requests (setup.py MIN_ENGINE note) GYRO_ROOM_GB = 4.0 # recommend() suggests a Gyro size only when VRAM + RAM exceed its memory figure by this much FALLBACK_CONTEXTS = [8192, 32768, 65536, 131072, 204800, 262144, 393216, 524288] BENCH_PROMPT = ("Write a short story (about 300 words) about a lighthouse keeper who finds a message in a bottle. " @@ -474,12 +475,37 @@ class Strata: def tables(self): s = self.setup_module() if s is not None: - return s.MODELS, s.FAMILIES, list(s.CONTEXTS), "setup.py" + return s.MODELS, {**s.FAMILIES, **self.own_families()}, list(s.CONTEXTS), "setup.py" return FALLBACK_MODELS, FALLBACK_FAMILIES, FALLBACK_CONTEXTS, "built-in table (setup.py not importable)" - @staticmethod - def sizes_of(models, family) -> list: + def own_families(self) -> dict: + """setup.py's OWN_PATH_FAMILIES (Qwen3.6-35B-A3B): families with an engine path of their own. They are not in FAMILIES + (whose entries are Flash-Next files with packs), so the model list used to leave them out and the app's Qwen3.6 page + showed no versions at all. Each is returned as a family entry (title, about, tag, license) of this server's table.""" + s = self.setup_module() + out = {} + for f, d in (getattr(s, "OWN_PATH_FAMILIES", None) or {}).items(): + out[f] = {"title": d["title"], "about": d.get("about"), "tag": d["tag"], "license": d.get("license"), + "vision": bool(d.get("vision", True)), "own_path": True} + return out + + def own_size(self, family, model) -> dict | None: + """One size of an own-path family as a model-table row for install_plan / model_table (None: not an own-path size). + The download is the GGUF; the picture reader (mmproj, ~0.9 GB) is counted by the plan when pictures are on.""" + d = (getattr(self.setup_module(), "OWN_PATH_FAMILIES", None) or {}).get(family) + if not d or model not in d["models"]: + return None + size_gb = d["sha256"][d["file"].format(q=model)][0] / 1e9 + return {"about": d["models"][model]["about"], "download_gb": round(size_gb, 1), "ram_gb": d["models"][model]["ram_gb"], + # the routed experts are ~93% of the file (setup.own_path_parallel_fits_all); the dense part and buffers ~1 GB more + "arena_gb": round(size_gb * 0.93, 1), "vision": bool(d.get("vision", True)), + "engine": OWN_PATH_ENGINE, "families": (family,)} + + def sizes_of(self, models, family) -> list: """The family's sizes as setup lists them: an experimental one last (never the default).""" + own = (getattr(self.setup_module(), "OWN_PATH_FAMILIES", None) or {}).get(family) + if own: + return list(own["models"]) return sorted((m for m in models if family in models[m].get("families", ("qwen", "swift"))), key=lambda m: bool(models[m].get("experimental"))) @@ -934,14 +960,17 @@ class Strata: for f, fd in families.items(): sizes = [] for m in self.sizes_of(models, f): - d = models[m] + own = self.own_size(f, m) + d = own or models[m] tag = (fd.get("tag", "") + m).lower() verdict = None if ram is not None: have_gb = ram + vram if d.get("mem_total") else ram # Gyro: VRAM and RAM together verdict = "fits" if have_gb >= d["ram_gb"] else "tight" if have_gb >= d["ram_gb"] - 8 else "does not fit" try: - if d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram): + if own: # its own engine path: no budget or low-RAM mode of Flash-Next's to judge by + pass + elif d.get("budget") and S and hasattr(S, "unsloth_budget") and not S.unsloth_budget(m, ram): verdict = ("experimental: " if d.get("experimental") else "") + "fits (all of its experts in RAM)" elif d.get("budget"): verdict = (("experimental: " if d.get("experimental") else "") @@ -967,7 +996,7 @@ class Strata: "on_this_pc": verdict, "installed": tag in have, "id": tag, # which graphics cards to use for it (strata_control/gpu_fit.py, the one rule app / Terminal / setup share): # only with two or more cards that count; "recommended" names the pre-selected option - "gpu_options": self.gpu_options(d, ram, hw)}) + "gpu_options": None if own else self.gpu_options(d, ram, hw)}) # Qwen3.6 runs on one card so far out.append({"family": f, "title": fd["title"], "about": fd.get("about"), "experimental": bool(fd.get("experimental")), "images": any(x["images"] for x in sizes) if sizes else fd.get("vision", True) is not False, @@ -1554,9 +1583,12 @@ class Tools: elif family is None: fams = [f for f in families if model in s.sizes_of(models, f)] family = "qwen" if "qwen" in fams else fams[0] + if family not in families: + raise ToolError(f"unknown family {family}; the families: {', '.join(families)}") sizes = s.sizes_of(models, family) if model not in sizes: raise ToolError(f"{families[family]['title']} has no {model}; its sizes: {', '.join(sizes)}") + md = s.own_size(family, model) or models[model] # Qwen3.6-35B-A3B: its sizes are not in setup's MODELS mac = bool(hw.get("mac")) if mac: # a Mac: no card to pick, no KV choice, no RAM mode: unified memory decides if rec.get("model") is None and model is not None and s.mac() and hw.get("ram_gb", 0) < s.mac().MIN_STREAM_RAM_GB: @@ -1567,10 +1599,10 @@ class Tools: usable = [g for g in hw.get("gpus", []) if g.get("usable")] vram = max((g["vram_gb"] for g in usable), default=12) context = 32768 if vram < 14 else 65536 if vram < 20 else 131072 - if models[model].get("budget") and (not hasattr(s.setup_module(), "unsloth_budget") or + if md.get("budget") and (not hasattr(s.setup_module(), "unsloth_budget") or s.setup_module().unsloth_budget(model, hw.get("ram_gb") or 0.0)): context = 8192 if vram < 14 else 32768 - if vision in ("yes", "gpu", "cpu") and models[model].get("vision", families[family].get("vision")) is False: + if vision in ("yes", "gpu", "cpu") and md.get("vision", families[family].get("vision")) is False: raise ToolError(f"images are not available with {families[family]['title']} {model} yet: use vision=no") if vision is not None and backend == "hip" and vision != "no": # setup.py's hip_vision rules (#990): the AMD backend has no GPU image encoder, but --vision cpu reads @@ -1586,7 +1618,7 @@ class Tools: tag = (families[family].get("tag", "") + model) have_dir = target / "models" / tag partly = (have_dir.is_dir() and any(have_dir.glob("*.gguf*"))) or bool(gguf_dir) # a local folder: nothing to download - need = (8 if partly else models[model]["download_gb"] + 8) + (1 if vision in ("yes", "gpu", "cpu") else 0) + need = (8 if partly else md["download_gb"] + 8) + (1 if vision in ("yes", "gpu", "cpu") else 0) free = s.disk_free(target) short = None if free is not None and free < need: @@ -1596,8 +1628,11 @@ class Tools: "--vision", vision or "no"] if family in ("qwen", "coder"): args += ["--experimental-speed-projection", "off"] + own = bool(s.own_families().get(family)) for flag, v in (("--kv", kv), ("--gpu", gpu), ("--gpus", gpus), ("--low-ram", low_ram), ("--port", port), ("--data-dir", str(target) if data_dir else None)): + if own and flag in ("--kv", "--low-ram"): # Flash-Next settings: Qwen3.6's engine path does not use them (setup would warn) + continue if v is not None: args += [flag, str(v)] if gguf_dir: @@ -1610,11 +1645,11 @@ class Tools: fit = None ram = hw.get("ram_gb") if ram is not None: - need_ram = models[model]["ram_gb"] + need_ram = md["ram_gb"] fit = "fits" if ram >= need_ram else f"needs ~{need_ram} GB of RAM, this PC has {ram:.0f} GB" installed = (s.root / f"strata-{tag.lower()}.json").exists() plan = {"title": f"{families[family]['title']} {model}", "family": family, "model": model, - "context": context, "images": vision or "no", "download_gb": models[model]["download_gb"], + "context": context, "images": vision or "no", "download_gb": md["download_gb"], "partly_downloaded": partly, "ram": fit, "data_folder": str(target), "model_folder": str(have_dir), "disk_free_gb": free, "disk_needed_gb": round(need), "disk_short": short, "already_installed": installed, @@ -1626,7 +1661,7 @@ class Tools: "the options (finished steps are skipped)") if families[family].get("license"): plan["license"] = families[family]["license"] - if families[family].get("experimental") or models[model].get("experimental"): + if families[family].get("experimental") or md.get("experimental"): plan["experimental"] = True return plan, args diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index 57cdef75..b8cc4ed4 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -597,6 +597,39 @@ class Helpers(unittest.TestCase): self.assertEqual(by["UD-Q4_K_XL"]["on_this_pc"], "fits (all of its experts in RAM)") self.assertIn("read from the SSD", by["Q8_0"]["on_this_pc"]) + def test_qwen36_is_listed_with_its_three_sizes(self): + """QA 2026-10-18: the Qwen3.6-35B-A3B page of the first-run setup showed no versions, because setup.py keeps the family + in OWN_PATH_FAMILIES (not FAMILIES) and the model list only walked FAMILIES.""" + s = M.Strata(HERE.parent) + self.assertIn("qwen36", s.tables()[1]) + fam = next(f for f in s.model_table({"ram_gb": 63.7, "gpus": [{"index": 0, "name": "x", "vram_gb": 12.0, "usable": True}]}) + if f["family"] == "qwen36") + by = {x["model"]: x for x in fam["sizes"]} + self.assertEqual(list(by), ["UD-Q4_K_XL", "UD-Q6_K_XL", "Q8_0"]) + self.assertEqual(by["UD-Q4_K_XL"]["id"], "qwen36-ud-q4_k_xl") # the tag the install writes its config under + self.assertEqual(by["UD-Q4_K_XL"]["download_gb"], 22.9) + self.assertTrue(all(x["images"] and x["engine_min"] == "0.1.45" and x["gpu_options"] is None for x in by.values())) + self.assertEqual({x["on_this_pc"] for x in by.values()}, {"fits"}) + small = next(f for f in s.model_table({"ram_gb": 16, "gpus": []}) if f["family"] == "qwen36") + self.assertEqual({x["on_this_pc"] for x in small["sizes"]}, {"does not fit"}) + self.assertEqual(s.sizes_of(s.tables()[0], "unsloth")[-1], "Q8_0") # the Unsloth Flash-Next sizes are untouched + + def test_qwen36_install_plan(self): + s = M.Strata(HERE.parent) + s.hardware = lambda fresh=False: {"ram_gb": 64.0, "gpus": [{"index": 0, "name": "x", "vram_gb": 12.0, "usable": True, "vendor": "nvidia"}], + "cpu": {"avx2": True}} + s.disk_free = lambda p: 1000.0 + plan, args = M.Tools(s).install_plan("qwen36", "UD-Q4_K_XL", 32768, "yes", "int8", None, None, None, "auto", None, None) + self.assertEqual((plan["title"], plan["download_gb"], plan["family"]), ("Qwen3.6-35B-A3B UD-Q4_K_XL", 22.9, "qwen36")) + self.assertEqual(args[:10], ["--yes", "--no-start", "--family", "qwen36", "--model", "UD-Q4_K_XL", "--context", "32768", + "--vision", "yes"]) + for flag in ("--kv", "--low-ram", "--experimental-speed-projection"): # Flash-Next settings: setup would only warn + self.assertNotIn(flag, args) + plan, _a = M.Tools(s).install_plan("qwen36", None, 32768, "no", None, None, None, None, None, None, None) + self.assertEqual(plan["model"], "UD-Q4_K_XL") + with self.assertRaises(M.ToolError): + M.Tools(s).install_plan("qwen36", "IQ3_S", 32768, "no", None, None, None, None, None, None, None) + def test_recommendation_follows_ram(self): s = M.Strata(HERE.parent) gpu = [{"index": 0, "name": "x", "vram_gb": 24.0, "usable": True, "vendor": "nvidia"}] From 1237d9a5fa90bbe06873cc7fa0910caabc635b74 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 20:47:43 +0200 Subject: [PATCH 02/26] downloads and models: live progress, parts counted, choices kept, clear NVFP4 names, More versions list - native state: the host's 'native' events are applied at once; the light poll (1 s while a job runs, none while hidden) is no longer held by a slow forced read; a read that never answers is dropped after 20 s - install progress: every file of the model is counted (parts, picture reader beside the model folders, NVFP4 packs by their pinned sizes); the bar no longer sits at 99 % while the picture reader downloads; the screen names the part (part 2 of 4) and lists the parts - a config is 'ready' only when every part of a multi-part GGUF is whole - Models page keeps version, context, computer use, picture reading and expert choices across tabs; Read pictures is on for a version that is not downloaded yet; the running download is named - version list: smaller rows, a Downloaded tag, NVFP4 / NVFP4-NVIDIA / NVFP4-QAD named by who made them with one line each - first-run page: the four recommended versions, then a More versions list (the Models page list) --- apps/host/server/engine-step.mjs | 5 +- apps/host/server/native-control.mjs | 2 +- apps/host/src/components/DownloadParts.tsx | 17 +++ apps/host/src/components/GuidedSetup.tsx | 16 ++- apps/host/src/components/NativeModels.tsx | 82 ++++++++------ apps/host/src/components/VersionPicker.tsx | 33 ++++-- apps/host/src/lib/client.ts | 2 +- apps/host/src/lib/download-eta.ts | 19 ++++ apps/host/src/lib/kept-state.ts | 23 ++++ apps/host/src/lib/native-catalog.ts | 5 +- apps/host/src/lib/native-fit.ts | 5 + apps/host/src/lib/native-names.ts | 15 +++ apps/host/src/lib/native.ts | 51 ++++++++- apps/host/src/lib/store.ts | 5 +- apps/host/src/locales/de.json | 16 ++- apps/host/src/locales/en.json | 16 ++- apps/host/src/locales/es.json | 16 ++- apps/host/src/locales/ja.json | 16 ++- apps/host/src/locales/ko.json | 16 ++- apps/host/src/locales/pt.json | 16 ++- apps/host/src/locales/ru.json | 16 ++- apps/host/src/locales/zh.json | 16 ++- apps/host/src/styles/app.css | 7 +- apps/host/src/styles/onboarding.css | 8 ++ apps/host/tests/qa1-downloads.test.mjs | 125 +++++++++++++++++++++ apps/host/tests/ui4-fixes.test.mjs | 4 +- tests/desktop/test_control_install.py | 65 +++++++++++ tools/strata_mcp.py | 108 +++++++++++++++++- 28 files changed, 657 insertions(+), 68 deletions(-) create mode 100644 apps/host/src/components/DownloadParts.tsx create mode 100644 apps/host/src/lib/kept-state.ts create mode 100644 apps/host/tests/qa1-downloads.test.mjs diff --git a/apps/host/server/engine-step.mjs b/apps/host/server/engine-step.mjs index da774247..1274c7b5 100644 --- a/apps/host/server/engine-step.mjs +++ b/apps/host/server/engine-step.mjs @@ -75,8 +75,11 @@ export function createEngineStep({ control, signal = null, onChange = () => {} } const modelRemaining = Number.isFinite(model?.remaining_gb) ? model.remaining_gb : null; const active = !['done', 'current', 'skipped', 'failed'].includes(part.state); const engineRemaining = active || part.state === 'done' ? Math.max(0, part.total_gb - part.done_gb) : 0; + /* The install knows its files (strata_mcp files_progress): the model's parts and the picture reader, each counted. Without that, one + model part from the combined figures. The engine is added either way. */ + const own = Array.isArray(install.parts) && install.parts.some(p => p?.kind === 'model') ? install.parts.filter(p => p?.kind !== 'engine') : null; const parts = [ - { kind: 'model', name: model?.file ?? install.model ?? 'Model', state: install.running === false ? 'done' : 'downloading', done_gb: modelDone ?? 0, total_gb: round((modelDone ?? 0) + (modelRemaining ?? 0)) }, + ...(own ?? [{ kind: 'model', name: model?.file ?? install.model ?? 'Model', state: install.running === false ? 'done' : 'downloading', done_gb: modelDone ?? 0, total_gb: round((modelDone ?? 0) + (modelRemaining ?? 0)) }]), { ...part }, ]; const merged = { ...install, engine: { ...part }, parts }; diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index a7c1c8f9..1a99dbba 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -355,7 +355,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} const room=args.resourceProfile==='work'; return autotuner.start(job,job.kind==='recheck'?'recheck':'tune',{configPath:path,presetId:args.presetId,mode:args.mode,use:args.use,goal:room?'room':'speed',leaveRam:room?20:0,allowSmallDifferences:args.allowSmallDifferences===true,name:args.name},{onProgress:p=>{job.summary=p.text??job.summary;emit();}}); } - function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model});} + function operation(kind,args={}){if(!['install','load','benchmark','tune','autotune','recheck','calibrate','update-engine','update-strata','rollback','remove'].includes(kind))throw new Error('Choose a supported native operation.');if(!snapshot.available)throw new Error(snapshot.error??'Connect the native Strata installation first.');if(kind==='install'||kind==='load'){const refusal=engineRefusal(snapshot.catalog,args.model,snapshot.engineInfo);if(refusal)throw new Error(refusal);}return begin(kind,job=>kind==='install'?install(job,args):kind==='load'?loadEngine(job,args):kind==='benchmark'?benchmark(job,args):kind==='tune'?tune(job,args):kind==='autotune'||kind==='recheck'?autotune(job,args):kind==='remove'?removeModel(job,args):program(job,args),{guided:args.guided===true,model:args.model,...(args.family?{family:args.family}:{})});} async function cancel(id){const job=jobs.get(id);if(!job||job.state!=='running')throw new Error('This operation is no longer running.');if(job.kind==='install'){job.engineAbort?.abort();await tool('strata_install',{cancel:true});}else if(job.abort)job.abort.abort();else if(job.process){if(!['tune','calibrate','autotune','recheck'].includes(job.kind))throw new Error('File updates cannot be cancelled safely while files are being replaced.');job.state='cancelled';await stopProcess(job.process);}job.state='cancelled';job.summary=job.kind==='install'?'Stopped. Completed downloads are kept.':'Stopped.';emit();return state();} async function close(){closing=true;clearInterval(timer);const installing=packaged&&child&&[...jobs.values()].some(j=>j.kind==='install'&&j.state==='running');if(installing)await send('tools/call',{name:'strata_install',arguments:{cancel:true}},15000).catch(()=>{});const operations=[];for(const job of jobs.values()){job.abort?.abort();if(job.process)operations.push(stopProcess(job.process));if(job.state==='running')job.state='cancelled';}await Promise.all(operations);await Promise.all([...instances.keys()].map(id=>unload(id,true).catch(()=>{})));disconnect();} // Remove nonserializable process references from public jobs. diff --git a/apps/host/src/components/DownloadParts.tsx b/apps/host/src/components/DownloadParts.tsx new file mode 100644 index 00000000..0827ad02 --- /dev/null +++ b/apps/host/src/components/DownloadParts.tsx @@ -0,0 +1,17 @@ +import { tr } from '../lib/i18n'; + +export interface InstallPart { kind?: string; name?: string; state?: string; done_gb?: number; total_gb?: number; files_done?: number; files_total?: number } + +/** + * The parts of a download, one line each: the model (with "2/4" when it comes in parts), the picture reader, the engine. A model in several + * parts is only downloaded when every line says Done, so a person can see which part is under way instead of one bar that restarts. + */ +export function DownloadParts({ parts }: { parts: InstallPart[] | undefined }) { + if (!parts || parts.length < 2) return null; + return ; +} diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index 15682632..a8586cee 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -12,7 +12,10 @@ import { nativeAction, useNative, type NativeJob } from '../lib/native'; import { completeSetup, completeSetupStep, go, newSession, openSetup, selectRemoteModel, setSettingsSection, useStore } from '../lib/store'; import type { LocalModelFolder, SetupState } from '../lib/types'; import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboarding-download'; -import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; +import { VersionPicker } from './VersionPicker'; +import { DownloadParts } from './DownloadParts'; +import { recommendedVersions } from '../lib/native-fit'; import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; type Choices = NonNullable['onboarding']>; function radioKeys(event: KeyboardEvent) { if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'].includes(event.key)) @@ -161,6 +164,12 @@ export function GuidedSetup() { } }); return () => { cancelled = true; }; }, [step, plan, preparing, native?.available, version?.id, context, directory]); + const recommendedCards = recommendedVersions(selectedFamily?.sizes ?? []).map(x => x.v); + // The recommended four first, then a list with every other version (the Models page's version list); a family without a recommended set shows them all. + const cards = recommendedCards.length ? recommendedCards : selectedFamily?.sizes ?? []; + const others = recommendedCards.length ? (selectedFamily?.sizes ?? []).filter(v => !recommendedCards.includes(v)) : []; + const readyIds = new Set((native?.installed?.models ?? []).filter(m => m.ready).map(m => m.model)); + const versionCard = (v: NonNullable) => ; const counter = downloadCounter(plan?.plan?.download_gb ?? version?.download_gb, progress, preparing); const eta = useDownloadEta(preparing ? progress : undefined, installJob?.id); const title = step === 1 ? 'State of the art. At home.' : step === 2 ? 'Select the model you want to run.' : step === 3 ? 'Downloading the model...' : tuneJob?.state === 'running' ? 'A little tuning. A better fit.' : 'How you would like to work with Strata?'; @@ -179,13 +188,14 @@ export function GuidedSetup() {
{tr("Model")}
({ value: String(n), label: `${n / 1024}K` }))} onChange={value => setContext(Number(value))}/>
{tr(!version || version.needsNewerEngine ?

{tr("This model needs a newer engine. Update your engine or import a local GGUF for this model.")}

: null)}
{tr("Choose a version")}{tr(version ? `${catalogVersionLabel(version)} selected` : '')}
-
{tr(selectedFamily.sizes.map(v => ))}
+
{tr(cards.map(v => versionCard(v)))}
+ {tr(others.length ?
g.usable !== false).map(g => g.vram_gb)) } : null} downloaded={readyIds} showRecommended={false} moreLabel="More versions" onSelect={id => { setSize(id); setPlan(null); }} onOwnGguf={() => setFolderOpen(true)}/>
: null)}
{tr(directory ? 'Your model folder' : 'Already downloaded the model?')}{tr(directory || "Choose the folder and we'll start your models with Strata.")}
setFolderOpen(v => !v)}>{tr(folderOpen ? 'Close' : directory ? 'Change' : 'Choose folder')}
{tr(folderOpen ? void perform(async () => { await nativeAction('directory', { directory: path }); setDirectory(path); setFolderOpen(false); setPlan(null); })}/> : null)} :
{tr("Connect your Strata installation")} void skip(false, 'Engine')}>{tr("Connect engine")}
)}
: step === 3 ?
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
- {tr(preparing ?
{tr(progress ? 'Downloading model files…' : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} + {tr(preparing ?
{tr(progress ? stageText(installStage(installJob?.result?.install)) : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} {tr("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
:
diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index b852f935..42ef8c09 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -6,7 +6,9 @@ import { FamilySwitch } from './FamilySwitch'; import { PcFitCard } from './PcFitCard'; import { fitOn } from '../lib/native-fit'; import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; -import { installProgress, useDownloadEta } from '../lib/download-eta'; +import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; +import { useKept } from '../lib/kept-state'; +import { DownloadParts } from './DownloadParts'; import { sizeGb } from '../lib/format'; import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; @@ -31,12 +33,14 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine onReady?: () => void; }) { const native = useNative(), imageLibrary = useStore(s => s.imageModels), hardware = useStore(s => s.hardware); - const [family, setFamily] = useState(''), [size, setSize] = useState(''), [context, setContext] = useState(32768), [vision, setVision] = useState('yes'); + // The choices are kept while the page is closed (Models -> Monitor -> Models used to start them over and a person lost track of what was downloading). + const [family, setFamily] = useKept('models.family', ''), [size, setSize] = useKept('models.size', ''), [context, setContext] = useKept('models.context', 32768), [vision, setVision] = useKept('models.vision', 'yes'); const manual = useStore(s => s.setup?.choices?.onboarding?.manual ?? false); - const [expert, setExpert] = useState(manual), [multiple, setMultiple] = useState(false), [gpus, setGpus] = useState([]), [kv, setKv] = useState('int8'), [lowRam, setLowRam] = useState('auto'), [split, setSplit] = useState('auto'), [deviceChoice, setDeviceChoice] = useState('auto'); - const [cardsKey, setCardsKey] = useState(null); - const [resourceProfile, setResourceProfile] = useState<'work' | 'performance'>('work'); - const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useState(''), [manage, setManage] = useState(false); + const [expert, setExpert] = useKept('models.expert', manual), [multiple, setMultiple] = useKept('models.multiple', false), [gpus, setGpus] = useKept('models.gpus', []), [kv, setKv] = useKept('models.kv', 'int8'), [lowRam, setLowRam] = useKept('models.lowRam', 'auto'), [split, setSplit] = useKept('models.split', 'auto'), [deviceChoice, setDeviceChoice] = useKept('models.device', 'auto'); + const [cardsKey, setCardsKey] = useKept('models.cards', null); + const [resourceProfile, setResourceProfile] = useKept<'work' | 'performance'>('models.profile', 'work'); + const [pending, setPending] = useState(false), [error, setError] = useState(''), [plan, setPlan] = useState | null>(null), [loadedError, setLoadedError] = useState(''), [tuneOpen, setTuneOpen] = useState(false), [jobId, setJobId] = useKept('models.job', ''), [manage, setManage] = useState(false); + const [toastedJob, setToastedJob] = useKept('models.toasted', ''), [appliedSig, setAppliedSig] = useKept('models.applied', ''); const presetPending = useRef(false); const [deleting, setDeleting] = useState(null); const families = nativeCatalogModels(native?.catalog?.families ?? []); @@ -56,15 +60,11 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const keptUse = keptModels.map(i => { const s = sizeOf(i.model); const card = pcGpus.find(g => g.index === i.gpus[0]); const f = s && pcRam ? fitOn(s, { ram_gb: pcRam, vram_gb: card?.vram_gb ?? pcVram }) : null; return { gpus: i.gpus, ram: f?.ramUseGb ?? 0, vram: f?.vramUseGb ?? 0 }; }); const keptRam = keptUse.reduce((n, u) => n + u.ram, 0); const keptVramOn = (cards: number[]) => keptUse.filter(u => u.gpus.some(g => cards.includes(g))).reduce((n, u) => n + u.vram, 0); + // The versions that are really on this computer: a config whose files are all there (every part of a model in parts). + const readyIds = useMemo(() => new Set(downloaded.filter(m => m.ready).map(m => m.model)), [downloaded]); + // What a running job works on, by its name in the list: "Qwen3.8-Flash-Next · Gyro · Smallest". + const jobLabel = (j: NativeJob) => { const v = allSizes.find(s => s.id === j.model || (s.model === j.model && (!j.family || s.sourceFamily === j.family))); const f = v && families.find(x => x.sizes.includes(v)); return v ? [f?.title, catalogVersionLabel(v)].filter(Boolean).join(' · ') : ''; }; const loadedSelected = native?.instances.find(i => i.model === selectedSize?.id && i.status === 'ready'); - // A model that is already on this PC loads as it was prepared: the page shows its settings, so loading it never asks to download. - useEffect(() => { if (installed?.ready) { - if (installed.context) - setContext(installed.context); - if (installed.kv) - setKv(installed.kv as typeof kv); - setLowRam((installed.lowRamMode ?? 'auto') as typeof lowRam); - } }, [installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.lowRamMode]); // What the running model was really started with is what the page shows: after Load the highlight must still be the profile that was applied. useEffect(() => { if (loadedSelected?.resourceProfile) setResourceProfile(loadedSelected.resourceProfile); }, [loadedSelected?.id, loadedSelected?.resourceProfile]); @@ -93,7 +93,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine const gpuNumbers = (text: string) => text.replace(/\(card (\d+)\)/g, (_m, n) => `(GPU ${Number(n) + 1})`); // The fit sentence for a card choice, less what the kept models take of RAM and of that card's memory. const lessKept = (words: string, cards: number[]) => { const gone = Math.round(keptRam + keptVramOn(cards)); return gone > 0 ? words.replace(/of the (\d+) GB available/, (_m, n) => `of the ${Math.max(0, Number(n) - gone)} GB available`) : words; }; - useEffect(() => { setCardsKey(null); }, [selectedSize?.id]); + const shownSize = useRef(selectedSize?.id); + useEffect(() => { if (shownSize.current !== selectedSize?.id) { shownSize.current = selectedSize?.id; setCardsKey(null); } }, [selectedSize?.id]); const values = useMemo(() => ({ family: selectedSize?.sourceFamily, model: selectedSize?.model, context, vision: selectedSize?.images ? vision : 'no', kv, low_ram: lowRam, resourceProfile, ...(expert && gpus.length ? { gpus: gpus.join(',') } : cardsGpus.length > 1 ? { gpus: cardsGpus.join(',') } : cardsGpus.length === 1 ? { gpu: cardsGpus[0] } : {}), loadAfter: true, multiple: expert && multiple }), [selectedSize?.sourceFamily, selectedSize?.model, context, vision, kv, lowRam, resourceProfile, gpus.join(','), cardsGpus.join(','), expert, multiple]); const downloadValues = { ...values, vision: selectedSize?.images ? 'yes' : 'no', loadVision: selectedSize?.images ? vision : 'no' }; useEffect(() => { if (!native?.catalog || family) @@ -102,19 +103,35 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine setSize(f.sizes.find(s => s.id === current?.model)?.id ?? f.sizes.find(s => have.has(s.id))?.id ?? f.sizes.find(s => s.model === rec.model)?.id ?? f.sizes[0]?.id ?? ''); setContext(('context' in rec ? rec.context : undefined) ?? 32768); } }, [native?.catalog]); - useEffect(() => { if (presetPending.current) { - presetPending.current = false; - return; - } if (installed) { - setContext(installed.context ?? 32768); - setVision(installed.visionEnabled === false || installed.images === 'off' ? 'no' : installed.visionDevice ?? installed.images ?? 'yes'); - setKv(installed.kv ?? 'int8'); - setLowRam(installed.lowRamMode ?? 'auto'); - // A model never tuned has no saved choice: keep the page's own (Leave 20%) rather than flipping to Full performance. - if (installed.resourceProfile && !loadedSelected?.resourceProfile) - setResourceProfile(installed.resourceProfile); - } }, [installed?.model, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); - useEffect(() => { if (jobId && job?.state === 'done' && (job.kind === 'load' || job.kind === 'install')) { + // The version that is selected: a model already on this PC shows the settings it was prepared with (so loading it never asks to download); + // a model that is not yet downloaded starts with Read pictures ON (owner rule: pictures on by default). This runs when the SELECTION or the + // installed settings change, not when the page opens again: coming back from another tab keeps what was chosen. + useEffect(() => { + if (presetPending.current) { + presetPending.current = false; + return; + } + if (!selectedSize) + return; + const sig = installed ? ['have', installed.model, installed.ready, installed.context, installed.kv, installed.images, installed.visionEnabled, installed.visionDevice, installed.lowRamMode, installed.resourceProfile].join('|') : `new|${selectedSize.id}`; + if (sig === appliedSig) + return; + setAppliedSig(sig); + if (installed) { + if (installed.context) + setContext(installed.context); + setVision(installed.visionEnabled === false || installed.images === 'off' ? 'no' : installed.visionDevice ?? installed.images ?? 'yes'); + setKv(installed.kv ?? 'int8'); + setLowRam(installed.lowRamMode ?? 'auto'); + // A model never tuned has no saved choice: keep the page's own (Leave 20%) rather than flipping to Full performance. + if (installed.resourceProfile && !loadedSelected?.resourceProfile) + setResourceProfile(installed.resourceProfile); + } + else + setVision('yes'); + }, [selectedSize?.id, installed?.model, installed?.ready, installed?.context, installed?.kv, installed?.images, installed?.visionEnabled, installed?.visionDevice, installed?.lowRamMode, installed?.resourceProfile]); + useEffect(() => { if (jobId && job?.state === 'done' && job.id !== toastedJob && (job.kind === 'load' || job.kind === 'install')) { + setToastedJob(job.id); selectRemoteModel(null); pushToast('success', 'Model ready', 'Start a new chat when you’re ready.'); } }, [job?.state]); @@ -153,7 +170,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(selectedSize ? <>
{tr("Version")} { const f = families.find(f => f.family === v.family || f.sizes.some(s => s.sourceFamily === v.family)); if (!f) return; presetPending.current = true; setFamily(f.family); setSize(f.sizes.find(s => s.model === v.model && (s.sourceFamily === v.family || f.family === v.family))?.id ?? ''); setContext(v.context ?? 32768); setVision(v.vision ?? 'no'); setKv(v.kv ?? 'int8'); setLowRam(v.low_ram ?? 'auto'); }}/> setManage(true)}>{tr("Manage models")}
-
{ const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/>
+
{ const f = families.find(f => f.sizes.some(s => s.id === id)); if (f) { setFamily(f.family); setSize(id); setError(''); } }} onOwnGguf={() => (onImport ?? onOtherModels)()}/>
{tr(noFit ?

{tr("May run slower \u00B7 Model data can be read from SSD.")}

: null)}
{tr("Conversation context")} setVision(e.target.checked ? 'yes' : 'no')}/>{tr("Read pictures ")}{tr("On by default")}{tr("Understand photos, screenshots and charts. The picture files download automatically. Turn it off to save memory.")}{tr(expert && vision !== 'no' ? ({ value: v.id, label: `${v.local ? v.name : v.family} · ${v.quant} · ${sizeGb(v.diskGb)}${v.local ? ' · Local' : ''}`, disabled: pickerVersionState(v, library?.loaded ?? null).busy })), - ]} onChange={id => { setError(''); setSelected(id); }}/> + + {tr(rows ?
    + {tr(nativeModels.map(m =>
  • {nativeShortName(m.model)}{tr(native?.instances.some(i => i.model === m.model) ? {tr('Loaded')} : null)}{tr(sizeGb(m.diskGb ?? 0))} j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}
  • ))} + {tr(versions.map(v =>
  • {`${v.local ? v.name : v.family} · ${v.quant}`}{tr(v.local ? {tr('Local')} : null)}{tr(v.id === library?.loaded ? {tr('Loaded')} : null)}{tr(sizeGb(v.diskGb))} { setError(''); setSelected(v.id); }}>{tr("Delete")}
  • ))} + {tr(sharedGb > 0 ?
  • {tr("Shared files")}{tr("Used by more than one model")}{tr(sizeGb(sharedGb))}
  • : null)} +
:

{tr("No downloaded models")}

)}
- {tr(native?.installed?.models.length ? n + (m.diskGb ?? 0), 0))])}> -
    {tr(native.installed.models.map(m =>
  • {nativeShortName(m.model)}{tr(native.instances.some(i => i.model === m.model) ? {tr('Loaded')} : null)}{tr(sizeGb(m.diskGb ?? 0))} j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}
  • ))}
-
: null)} setNativeDeleting(null)}/> {tr("Keep version")} void remove()}>{tr(pending ? 'Working…' : version?.local ? 'Remove model' : 'Delete version')}}>

{tr(version ? `${version.local ? version.name : version.family} · ${version.quant} · ${sizeGb(version.diskGb)}` : 'This version is no longer downloaded.')}

diff --git a/apps/host/src/components/SettingsUpdates.tsx b/apps/host/src/components/SettingsUpdates.tsx index 1f3e65c9..42cb142d 100644 --- a/apps/host/src/components/SettingsUpdates.tsx +++ b/apps/host/src/components/SettingsUpdates.tsx @@ -6,11 +6,12 @@ import { useStore } from '../lib/store'; import type { SoftwareUpdate, UpdateCheckResult } from '../lib/types'; import { nativeAction, useNative } from '../lib/native'; import { NativeProgress } from './NativeModels'; +import { appVersionLabel } from '../lib/app-version'; /** Installed versions are real host values. Installation needs a host updater. */ export function SettingsUpdates() { const native = useNative(); const [confirm, setConfirm] = useState(''); - const appVersion = useStore(s => s.setup?.app.version); + const appVersion = appVersionLabel(useStore(s => s.setup?.app.version), native?.version); const engineVersion = useStore(s => s.engine?.engine.version); const [rollback, setRollback] = useState(false); const [component, setComponent] = useState<'strata' | 'engine'>('strata'); @@ -19,7 +20,7 @@ export function SettingsUpdates() { const [error, setError] = useState(''); const request = useRef(null); useEffect(() => () => request.current?.abort(), []); - const installed = component === 'strata' ? native?.version ?? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion; + const installed = component === 'strata' ? appVersion : native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion; const active = native?.jobs.find(j => j.state === 'running'); async function operate(kind: string) { setError(''); @@ -68,7 +69,7 @@ export function SettingsUpdates() { } return <>
- {tr(versionRow('Strata', native?.version ?? appVersion, result?.strata))} + {tr(versionRow('Strata', appVersion, result?.strata))} {tr(versionRow('Engine', native?.available ? (native.installed?.engine?.version ?? 'Not installed') : engineVersion, result?.engine))}
void check()}>{tr(checking ? 'Checking…' : error || result?.strata.status === 'error' ? 'Try again' : result ? 'Check again' : 'Check for updates')} setRollback(true)}>{tr("Roll back\u2026")}
{tr(checking ? 'Checking for new versions…' : error ? {tr(error)} : result ? <>{tr(result.strata.message)} {tr(result.engine.message)} {tr("Checked at ")}{tr(new Date(result.checkedAt).toLocaleTimeString(localeTag(), { hour: '2-digit', minute: '2-digit' }))} : null)}
@@ -85,3 +86,12 @@ export function SettingsUpdates() { setConfirm('')} actions={<> setConfirm('')}>{tr("Cancel")} 0} onClick={() => void operate(confirm)}>{tr("Update")}}>

{tr("The native installer updates the installation. Model files and settings are kept. Unload native models before updating.")}

{tr((native?.instances.length ?? 0) > 0 ?

{tr("Open Models and unload the running native models first.")}

: null)}
; } + +/** "Strata 0.2.0-beta · Engine 0.1.45.3": the app's own version first, the engine's beside it (About). */ +export function AboutVersions() { + const native = useNative(); + const app = appVersionLabel(useStore(s => s.setup?.app.version), native?.version); + const engineVersion = useStore(s => s.engine?.engine.version); + const engine = native?.available ? native.installed?.engine?.version : engineVersion; + return

{tr("Strata")} {app ?? ''}{engine ? · {tr("Engine")} {engine} : null}

; +} diff --git a/apps/host/src/lib/app-version.ts b/apps/host/src/lib/app-version.ts new file mode 100644 index 00000000..258c97f8 --- /dev/null +++ b/apps/host/src/lib/app-version.ts @@ -0,0 +1,9 @@ +/** + * The version the person sees as "Strata". It is the DESKTOP APP's version (0.2.0-beta), not that of Strata Control, the tools the app runs + * (0.1.45, the version of the Terminal). Showing Control's number as "Strata" made a tester report "Strata 0.1.45" for the 0.2.0-beta app. + * Without a real app version (a source checkout reports 'dev') the other number is the best there is. + */ +export function appVersionLabel(app: string | null | undefined, control?: string | null): string | undefined { + const real = (v: string | null | undefined) => (typeof v === 'string' && v.trim() && v.trim().toLowerCase() !== 'dev' ? v.trim() : undefined); + return real(app) ?? real(control) ?? (typeof app === 'string' && app.trim() ? app.trim() : undefined); +} diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index e30f2985..6053f211 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -10,7 +10,7 @@ export interface NativeJob {id:string;kind:string;guided?:boolean;model?:string; export interface NativeInstance {id:string;apiModelId:string;model:string;label:string;aliases?:string[];vision?:boolean;resourceProfile?:'work'|'performance'|null;context?:number;port:number;gpus:number[];status:'loading'|'ready'|'unloading'|'error';phase:string;loadedAt:string;error:string|null;metrics:Record|null} export interface NativeState { /** The picture reader (strata-vision) is installed with the engine, so models marked for pictures can read them here. */ - visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;missing_files?:string[]}[];data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} + visionReader?: boolean;available:boolean;repo:string;downloadDirectory?:string;version?:string|null;summary:string;error:string|null;catalog:{families:NativeFamily[];contexts:number[];recommendation:{family:string|null;model:string|null;context?:number;why?:string};context_note:string}|null;installed:{models:{model:string;config:string;model_name:string;ready:boolean;/** The picture-reading files are on this computer (notes-split-agent8.md, item 8). */visionPrepared?:boolean;context?:number;kv?:string;images?:string;visionEnabled?:boolean;visionDevice?:string;lowRamMode?:string;resourceProfile?:'work'|'performance';dataFolder?:string;diskGb?:number;diskBytes?:number;/** Files this model shares with another (the picture reader, the draft layer): counted once, in `usage`. */sharedBytes?:number;/** What Delete frees: files in Strata's own folders that no other model uses. */removableGb?:number;missing_files?:string[]}[];/** What all models take on disk, from their real files, shared files counted once. */usage?:{total_bytes:number;total_gb:number;shared_bytes:number;shared_gb:number;models:Record}|null;data_folder:string;engine:{version:string|null}}|null;hardware:{ram_gb:number;gpus:{index:number;name:string;vram_gb:number;usable:boolean}[]}|null;fields:NativeField[];instances:NativeInstance[];defaultId:string|null;jobs:NativeJob[];capabilities:{responses?:boolean;updates:boolean;rollback:boolean;calibration:boolean;componentUpdates?:boolean}} let state:NativeState|null=null; const listeners=new Set<()=>void>(); function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());} diff --git a/apps/host/src/locales/de.json b/apps/host/src/locales/de.json index 918a1fad..832bc343 100644 --- a/apps/host/src/locales/de.json +++ b/apps/host/src/locales/de.json @@ -3235,5 +3235,10 @@ "s3239": "Die Engine für diesen PC wird heruntergeladen…", "s3240": "{0} wird vorbereitet", "s3241": "Teile des Downloads", - "s3242": "Bildleser" + "s3242": "Bildleser", + "s3243": "Gemeinsame Dateien", + "s3244": "Von mehr als einem Modell genutzt", + "s3245": "Diese Dateien liegen in deinem eigenen Ordner und bleiben dort. Nur der Eintrag in Strata wird entfernt.", + "s3246": "Das laufende Modell wird entladen.", + "s3247": "Lokal" } diff --git a/apps/host/src/locales/en.json b/apps/host/src/locales/en.json index 7502344c..cd8a27c5 100644 --- a/apps/host/src/locales/en.json +++ b/apps/host/src/locales/en.json @@ -3235,5 +3235,10 @@ "s3239": "Downloading the engine for this PC…", "s3240": "Preparing {0}", "s3241": "Download parts", - "s3242": "Picture reader" + "s3242": "Picture reader", + "s3243": "Shared files", + "s3244": "Used by more than one model", + "s3245": "These files are in your own folder, so they stay there. Only the entry in Strata is removed.", + "s3246": "The running model will be unloaded.", + "s3247": "Local" } diff --git a/apps/host/src/locales/es.json b/apps/host/src/locales/es.json index e9710a80..f1ca1558 100644 --- a/apps/host/src/locales/es.json +++ b/apps/host/src/locales/es.json @@ -3235,5 +3235,10 @@ "s3239": "Descargando el motor para este PC…", "s3240": "Preparando {0}", "s3241": "Partes de la descarga", - "s3242": "Lector de imágenes" + "s3242": "Lector de imágenes", + "s3243": "Archivos compartidos", + "s3244": "Los usa más de un modelo", + "s3245": "Estos archivos están en tu propia carpeta y se quedan allí. Solo se quita la entrada en Strata.", + "s3246": "El modelo en ejecución se descargará de la memoria.", + "s3247": "Local" } diff --git a/apps/host/src/locales/ja.json b/apps/host/src/locales/ja.json index 8b48a974..d971d529 100644 --- a/apps/host/src/locales/ja.json +++ b/apps/host/src/locales/ja.json @@ -3235,5 +3235,10 @@ "s3239": "このパソコン用のエンジンをダウンロード中…", "s3240": "{0} を準備中", "s3241": "ダウンロードの内訳", - "s3242": "画像読み取り" + "s3242": "画像読み取り", + "s3243": "共有ファイル", + "s3244": "複数のモデルで使われています", + "s3245": "これらのファイルはあなた自身のフォルダーにあるため、そのまま残ります。Strata 上の項目だけが削除されます。", + "s3246": "動作中のモデルの読み込みを解除します。", + "s3247": "ローカル" } diff --git a/apps/host/src/locales/ko.json b/apps/host/src/locales/ko.json index f1274ebc..3d548412 100644 --- a/apps/host/src/locales/ko.json +++ b/apps/host/src/locales/ko.json @@ -3235,5 +3235,10 @@ "s3239": "이 PC용 엔진 다운로드 중…", "s3240": "{0} 준비 중", "s3241": "다운로드 구성", - "s3242": "이미지 읽기" + "s3242": "이미지 읽기", + "s3243": "공유 파일", + "s3244": "여러 모델에서 함께 사용", + "s3245": "이 파일들은 내 폴더에 있으므로 그대로 남습니다. Strata의 항목만 삭제됩니다.", + "s3246": "실행 중인 모델을 해제합니다.", + "s3247": "로컬" } diff --git a/apps/host/src/locales/pt.json b/apps/host/src/locales/pt.json index a3c2748b..be22c5f9 100644 --- a/apps/host/src/locales/pt.json +++ b/apps/host/src/locales/pt.json @@ -3235,5 +3235,10 @@ "s3239": "Baixando o mecanismo para este PC…", "s3240": "Preparando {0}", "s3241": "Partes do download", - "s3242": "Leitor de imagens" + "s3242": "Leitor de imagens", + "s3243": "Arquivos compartilhados", + "s3244": "Usados por mais de um modelo", + "s3245": "Esses arquivos estão na sua própria pasta e continuam lá. Só a entrada no Strata é removida.", + "s3246": "O modelo em execução será descarregado.", + "s3247": "Local" } diff --git a/apps/host/src/locales/ru.json b/apps/host/src/locales/ru.json index 45303891..47c6551f 100644 --- a/apps/host/src/locales/ru.json +++ b/apps/host/src/locales/ru.json @@ -3235,5 +3235,10 @@ "s3239": "Скачивание движка для этого компьютера…", "s3240": "Подготовка: {0}", "s3241": "Части загрузки", - "s3242": "Чтение изображений" + "s3242": "Чтение изображений", + "s3243": "Общие файлы", + "s3244": "Используются несколькими моделями", + "s3245": "Эти файлы лежат в вашей папке и останутся там. Из Strata удаляется только запись.", + "s3246": "Работающая модель будет выгружена.", + "s3247": "Локальная" } diff --git a/apps/host/src/locales/zh.json b/apps/host/src/locales/zh.json index 5452b649..66b33556 100644 --- a/apps/host/src/locales/zh.json +++ b/apps/host/src/locales/zh.json @@ -3235,5 +3235,10 @@ "s3239": "正在下载适用于此电脑的引擎…", "s3240": "正在准备 {0}", "s3241": "下载分段", - "s3242": "图片读取组件" + "s3242": "图片读取组件", + "s3243": "共享文件", + "s3244": "被多个模型共用", + "s3245": "这些文件在你自己的文件夹中,会保留在原处,只会从 Strata 中移除该条目。", + "s3246": "将卸载运行中的模型。", + "s3247": "本地" } diff --git a/apps/host/src/screens/Settings.tsx b/apps/host/src/screens/Settings.tsx index d608f2d9..a14854f2 100644 --- a/apps/host/src/screens/Settings.tsx +++ b/apps/host/src/screens/Settings.tsx @@ -7,7 +7,7 @@ import { SettingsModels } from '../components/SettingsModels'; import { SettingsTools } from '../components/SettingsTools'; import { SettingsStorage } from '../components/SettingsStorage'; import { PrivacyNotes } from '../components/PrivacyNotes'; -import { SettingsUpdates } from '../components/SettingsUpdates'; +import { AboutVersions, SettingsUpdates } from '../components/SettingsUpdates'; import { NativeOperations } from '../components/NativeOperations'; import { FontChoice } from '../components/FontChoice'; import { LANGUAGES } from '../lib/i18n'; @@ -58,7 +58,7 @@ export function SettingsScreen() { {tr(panel.sections.map(section =>

{tr(section)}

- {tr(section === 'About' ?
: null)} + {tr(section === 'About' ?
: null)} {tr(section === 'Storage' ? : null)} {tr(section === 'Privacy' ? : null)} {tr(section === 'Update' ? : null)} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index 842f5f01..d3b34218 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -5653,7 +5653,8 @@ textarea.config-editor.st-input { .key-input .st-input { min-width: 0; flex: 1; } .dialog-feature-icon { display: grid; place-items: center; width: 52px; height: 52px; border: 1px solid var(--st-line); border-radius: 16px; background: var(--st-surface-2); color: var(--st-accent); } .key-url { overflow-wrap: anywhere; padding: 14px; background: var(--st-surface-2); border-radius: 10px; } -.settings-about-brand { display: flex; padding: 22px 20px 0; } +.settings-about-brand { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 18px; padding: 22px 20px 0; } +.settings-about-version { margin: 0; font-size: var(--st-fs-base); } .prompt-progress { display: flex; align-items: center; gap: 16px; } .prompt-progress > .st-bar { flex: 1; } .hardware-section { display: flex; flex-direction: column; gap: 20px; } @@ -7493,3 +7494,5 @@ textarea { .st-btn.btn-neutral { background: var(--st-surface); color: var(--st-ink); border: 1px solid var(--st-line); box-shadow: none; } .st-btn.btn-neutral:hover:not(:disabled) { background: var(--st-surface-2); } .native-vision-missing { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-top: 8px; font-size: var(--st-fs-sm); color: var(--st-ink-soft); } +.storage-model--shared { background: var(--st-surface-2); } +.storage-model--shared small { font-size: var(--st-fs-xs); } diff --git a/apps/host/tests/qa1-storage.test.mjs b/apps/host/tests/qa1-storage.test.mjs new file mode 100644 index 00000000..af23db09 --- /dev/null +++ b/apps/host/tests/qa1-storage.test.mjs @@ -0,0 +1,61 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { nativeUnloadPlan } from '../server/storage-check.mjs'; + +const loaded = [{ id: 'a', model: 'gyro-gyro-s' }, { id: 'b', model: 'iq3_s' }]; + +test('O01: checking the same folder unloads nothing', () => { + assert.deepEqual(nativeUnloadPlan({ changed: false, unload: true, instances: loaded }), { refuse: null, ids: [] }); + assert.deepEqual(nativeUnloadPlan({ changed: false, unload: undefined, instances: loaded }), { refuse: null, ids: [] }); +}); + +test('O01: changing the folder unloads the loaded models only when the person agreed', () => { + assert.match(nativeUnloadPlan({ changed: true, unload: false, instances: loaded }).refuse, /Unload native models/); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: true, instances: loaded }), { refuse: null, ids: ['a', 'b'] }); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: false, instances: [] }), { refuse: null, ids: [] }); + assert.deepEqual(nativeUnloadPlan({ changed: true, unload: true, instances: undefined }), { refuse: null, ids: [] }); +}); + +test('O01: the route uses that plan and the screen asks for an unload only when the folder differs', async () => { + const route = await readFile(new URL('../server/index.mjs', import.meta.url), 'utf8'); + assert.match(route, /nativeUnloadPlan\(\{changed,unload:body\.unload,instances:native\.state\(\)\.instances\}\)/); + assert.doesNotMatch(route, /for\(const instance of native\.state\(\)\.instances\)await native\.unload\(instance\.id\);\}\s*\n\s*storageChanging = true/); + const screen = await readFile(new URL('../src/components/SettingsStorage.tsx', import.meta.url), 'utf8'); + assert.match(screen, /changeModelDirectory\(path, path\.trim\(\) !== currentDirectory\)/); +}); + +test('F02: Settings -> Storage has ONE Downloaded models list and one total, with the shared files as a line of their own', async () => { + const screen = await readFile(new URL('../src/components/SettingsStorage.tsx', import.meta.url), 'utf8'); + assert.equal((screen.match(/ { + const { appVersionToShow } = await import('../server/app-version.mjs'); + assert.equal(appVersionToShow('0.2.0-beta', '0.1.45'), '0.2.0-beta'); + assert.equal(appVersionToShow('dev', '0.1.45'), '0.1.45', 'a source checkout has no app version: the next best number'); + assert.equal(appVersionToShow(undefined, null), null); + assert.equal(appVersionToShow('dev', null), 'dev'); + const { build } = await import('esbuild'); + const out = await build({ stdin: { contents: "export * from './src/lib/app-version';", resolveDir: process.cwd() }, bundle: true, write: false, platform: 'node', format: 'esm' }); + const { appVersionLabel } = await import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`); + assert.equal(appVersionLabel('0.2.0-beta', '0.1.45'), '0.2.0-beta'); + assert.equal(appVersionLabel('dev', '0.1.45'), '0.1.45'); + assert.equal(appVersionLabel(undefined, undefined), undefined); + const route = await readFile(new URL('../server/index.mjs', import.meta.url), 'utf8'); + assert.match(route, /appVersion:appVersionToShow\(setupState\(\)\.app\.version,native\.state\(\)\.version\)/); + const updates = await readFile(new URL('../src/components/SettingsUpdates.tsx', import.meta.url), 'utf8'); + assert.doesNotMatch(updates, /native\?\.version \?\? appVersion/, 'the Strata row no longer prefers Control\'s version'); + assert.match(updates, /AboutVersions/); +}); + +test('Cargo.toml, tauri.conf.json and the desktop package agree on the app version the host reports', async () => { + const root = new URL('../../desktop/', import.meta.url); + const cargo = /^version\s*=\s*"([^"]+)"/m.exec(await readFile(new URL('src-tauri/Cargo.toml', root), 'utf8'))[1]; + const pkg = JSON.parse(await readFile(new URL('package.json', root), 'utf8')).version; + assert.equal(cargo, pkg); + assert.equal(cargo, '0.2.0-beta'); +}); diff --git a/tools/strata_mcp.py b/tools/strata_mcp.py index 5184aaaf..ae2dcdc2 100644 --- a/tools/strata_mcp.py +++ b/tools/strata_mcp.py @@ -571,7 +571,7 @@ class Strata: except (OSError, ValueError): return {} - def describe_config(self, path: Path) -> dict: + def describe_config(self, path: Path, usage: dict | None = None) -> dict: cfg = self.read_config(path) a = cfg.get("args") if isinstance(cfg.get("args"), list) else [] @@ -580,9 +580,12 @@ class Strata: tag = path.stem[len("strata-"):] missing = [p for p in [cfg.get("exe"), *[x for x in a if isinstance(x, str) and x.endswith(".gguf")]] if not p or not Path(p).exists()] - missing += shard_gaps([x for x in a if isinstance(x, str) and x.endswith(".gguf")]) # a model in parts is whole only with every part + gaps = shard_gaps([x for x in a if isinstance(x, str) and x.endswith(".gguf")]) # a model in parts is whole only with every part + missing += gaps script = self.root / f"run-{tag}.{'bat' if WIN else 'sh'}" vis = cfg.get("vision") + own_usage = (usage or self.disk_usage())["models"].get(tag) or {"gb": 0.0, "bytes": 0, "shared_bytes": 0} + plan = self.removal_plan(path) return {"model": tag, "config": path.name, "model_name": cfg.get("model_name"), "context": int(val("--max-context")) if str(val("--max-context") or "").isdigit() else None, "kv": val("--kv"), "images": ("gpu" if vis.get("gpu") else "cpu") if isinstance(vis, dict) else "off", @@ -590,8 +593,11 @@ class Strata: "gpu": cfg.get("gpu"), "api_key_set": bool(cfg.get("api_key")), "low_ram": "--resident-experts" in a or "--mmap-experts" in a, "start_script": script.name if script.exists() else None, - "ready": not missing and bool(cfg), "missing_files": missing[:3], - "disk_gb": self.removal_plan(path)["gb"], "disk_bytes": self.removal_plan(path)["bytes"], + "ready": not missing and bool(cfg), "missing_files": missing[:3], "parts_missing": len(gaps), + "disk_gb": own_usage["gb"], "disk_bytes": own_usage["bytes"], + "shared_bytes": own_usage["shared_bytes"], + # what Delete would remove (files in Strata's own folders that no other model uses); the person's own GGUF folders stay + "removable_gb": plan["gb"], "kept_files": len(plan["keep"]), "last_used": time.strftime("%Y-%m-%d %H:%M", time.localtime(path.stat().st_mtime))} # ---- what a model owns on disk (Delete, and the per-model disk usage in Storage) @@ -602,9 +608,19 @@ class Strata: """(the GGUF files, the folders) a run config names: --native/--ple-gguf/... and --pack/--mtp, plus any other .gguf.""" a = [x for x in (cfg.get("args") or []) if isinstance(x, str)] files = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.FILE_FLAGS] - files += [Path(x) for x in a if x.lower().endswith(".gguf") and Path(x) not in files] + files += [Path(x) for x in a if x.lower().endswith(".gguf")] dirs = [Path(a[i + 1]) for i, x in enumerate(a[:-1]) if x in self.DIR_FLAGS] - return files, dirs + seen, once = set(), [] + for f in files: # one file named by several flags is still one file + if norm(f) not in seen: + seen.add(norm(f)) + once.append(f) + seen_d, once_d = set(), [] + for d in dirs: + if norm(d) not in seen_d: + seen_d.add(norm(d)) + once_d.append(d) + return once, once_d @staticmethod def tree_bytes(path: Path) -> int: @@ -622,6 +638,61 @@ class Strata: pass return total + @staticmethod + def file_key(path: Path): + """What makes two names the same file on disk: device + inode (hard links), else the resolved path.""" + try: + st = os.stat(path) + if st.st_ino: + return ("ino", st.st_dev, st.st_ino), st.st_size + return ("path", str(norm(path))), st.st_size + except OSError: + return None, 0 + + def used_files(self, cfg: dict) -> dict: + """Every file a model really uses, from its run config: all parts of a multi-part GGUF (the config names the first), the + picture reader, the packs and the draft layer folders. {file identity: bytes}, wherever they live (the Strata folders or the + person's own).""" + files, dirs = self.model_paths(cfg) + paths = list(files) + vis = cfg.get("vision") + if isinstance(vis, dict) and isinstance(vis.get("mmproj"), str): + paths.append(Path(vis["mmproj"])) + for f in list(paths): # the other parts of a multi-part file + m = SHARD_NAME.match(str(f)) + if m: + paths += [Path(f"{m.group(1)}-{i:05d}-of-{m.group(3)}.gguf") for i in range(1, int(m.group(3)) + 1)] + for d in dirs: + for base, _sub, names in os.walk(d): + paths += [Path(base) / n for n in names] + out = {} + for p in paths: + if p.is_file(): + key, size = self.file_key(p) + if key is not None: + out[key] = size + return out + + def disk_usage(self) -> dict: + """What the installed models take on disk, from the real files: each model's own files, the files shared between models + (the picture reader, the draft layer) counted ONCE, and the total. A model's own figure leaves out the shared files and + every other model's; rows plus 'shared' add up to the total.""" + per = {c.stem[len("strata-"):]: self.used_files(self.read_config(c)) for c in self.configs()} + owners: dict = {} + for files in per.values(): + for k in files: + owners[k] = owners.get(k, 0) + 1 + models, shared = {}, {} + for tag, files in per.items(): + own = sum(b for k, b in files.items() if owners[k] == 1) + models[tag] = {"bytes": own, "gb": round(own / 1e9, 2), "files": len(files), + "shared_bytes": sum(b for k, b in files.items() if owners[k] > 1)} + shared.update({k: b for k, b in files.items() if owners[k] > 1}) + shared_bytes = sum(shared.values()) + total = sum(m["bytes"] for m in models.values()) + shared_bytes + return {"models": models, "shared_bytes": shared_bytes, "shared_gb": round(shared_bytes / 1e9, 2), + "total_bytes": total, "total_gb": round(total / 1e9, 2)} + def removal_plan(self, config: Path) -> dict: """What deleting this model removes and what it keeps. A file or folder another installed model's config still names (the shared MTP draft, a shared PLE shard) is kept; so is anything outside Strata's own folders.""" @@ -709,9 +780,11 @@ class Strata: entry["downloading"] = bool(list(c.glob("*.part"))) items.setdefault(sub, []).append(entry) mtp = data / "mtp" / "rt" / "experts.bin" + usage = self.disk_usage() return {"strata_folder": str(self.root), "data_folder": str(data), "data_folder_exists": data.is_dir(), "python_env": self.venv_python().exists(), "engine": self.engine_info(), - "models": [self.describe_config(c) for c in self.configs()], + "models": [self.describe_config(c, usage) for c in self.configs()], + "usage": usage, "downloads": items.get("models", []), "prepared": items.get("packs", []), "draft_layer": mtp.exists()} diff --git a/tools/test_strata_mcp.py b/tools/test_strata_mcp.py index b8cc4ed4..923c5745 100644 --- a/tools/test_strata_mcp.py +++ b/tools/test_strata_mcp.py @@ -799,3 +799,85 @@ class RemoveMissingFilesTest(unittest.TestCase): self.assertFalse(folder.exists()); self.assertFalse(cfg.exists()) again = mod.Tools(S()).strata_remove(model="gyro-m", confirm=True) self.assertEqual(again["failed"], [], "a second delete of the same model finds nothing left and still succeeds") + + +class DiskUsageTest(unittest.TestCase): + """QA 2026-10-18 (F02): Storage showed IQ3_S as 0.0 GB while it uses 84 GB, and Gyro-S as 119 GB while it is 59 GB. The sizes come from the real + files: every part of a model in parts, the picture reader, the packs; a file one config names through several flags counts once; a + file two models share counts once in the total; a model's own figure leaves out another model's files.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + d = Path(self.tmp.name) + self.root, self.data, self.own = d / "install", d / "data", d / "owner-folder" + for p in (self.root, self.data / "models" / "gyro-Gyro-S", self.data / "packs" / "swift-iq2_xs", self.data / "mtp" / "rt", self.own): + p.mkdir(parents=True) + (d / "settings.json").write_text(json.dumps({"data_dir": str(self.data)}), encoding="utf-8") + env = mock.patch.dict(os.environ, {"STRATA_SETTINGS_FILE": str(d / "settings.json")}) + env.start() + self.addCleanup(env.stop) + + def blob(self, path: Path, size: int) -> str: + path.write_bytes(b"x" * size) + return str(path) + + def write_config(self, name: str, args: list, vision=None): + cfg = {"exe": sys.executable, "args": args, "port": 8080} + if vision: + cfg["vision"] = {"mmproj": vision} + (self.root / f"strata-{name}.json").write_text(json.dumps(cfg), encoding="utf-8") + + def test_sizes_come_from_the_files_not_from_what_may_be_deleted(self): + gyro = self.blob(self.data / "models" / "gyro-Gyro-S" / "Gyro-S.gguf", 59_000) + reader = self.blob(self.data / "models" / "mmproj.gguf", 900) + part1 = self.blob(self.own / "Model-IQ3_S-00001-of-00002.gguf", 30_000) + self.blob(self.own / "Model-IQ3_S-00002-of-00002.gguf", 54_000) + # Gyro: the one file is --native, --ple-gguf, --embd-gguf and --native-dense-gguf at once + self.write_config("gyro-gyro-s", ["--native", gyro, "--ple-gguf", gyro, "--embd-gguf", gyro, "--native-dense-gguf", gyro], reader) + # IQ3_S: adopted from the person's own folder, the config names the first part only + self.write_config("iq3_s", ["--native", part1], reader) + s = M.Strata(self.root) + use = s.disk_usage() + self.assertEqual(use["models"]["gyro-gyro-s"]["bytes"], 59_000, "the Gyro file is counted once, not four times") + self.assertEqual(use["models"]["iq3_s"]["bytes"], 84_000, "both parts of IQ3_S, although the config names the first") + self.assertEqual(use["shared_bytes"], 900, "the picture reader both use is one file") + self.assertEqual(use["total_bytes"], 59_000 + 84_000 + 900, "rows plus the shared files add up to the total") + self.assertEqual(use["models"]["iq3_s"]["shared_bytes"], 900) + # deleting IQ3_S would remove nothing: its files are the person's own + by = {d["model"]: d for d in (s.describe_config(c, use) for c in s.configs())} + self.assertEqual(by["iq3_s"]["disk_bytes"], 84_000) + self.assertEqual(by["iq3_s"]["removable_gb"], 0.0) + self.assertEqual(by["gyro-gyro-s"]["disk_bytes"], 59_000) + + def test_a_pack_folder_and_the_shared_draft_layer_count_once(self): + gguf = self.blob(self.data / "models" / "gyro-Gyro-S" / "m.gguf", 10_000) + pack = self.data / "packs" / "swift-iq2_xs" + self.blob(pack / "experts.bin", 40_000) + self.blob(pack / "index.txt", 100) + mtp = self.data / "mtp" / "rt" + self.blob(mtp / "experts.bin", 5_000) + self.write_config("swift-iq2_xs", ["--native", gguf, "--pack", str(pack), "--mtp", str(mtp)]) + link_target = self.data / "models" / "gyro-Gyro-S" / "m2.gguf" + try: + os.link(gguf, link_target) # a hard link: the same bytes under another name + except OSError: + self.skipTest("no hard links here") + self.write_config("other", ["--native", str(link_target), "--mtp", str(mtp)]) + use = M.Strata(self.root).disk_usage() + self.assertEqual(use["models"]["swift-iq2_xs"]["bytes"], 40_100) + self.assertEqual(use["models"]["other"]["bytes"], 0) + self.assertEqual(use["shared_bytes"], 10_000 + 5_000, "the hard-linked GGUF and the draft layer are shared") + self.assertEqual(use["total_bytes"], 55_100) + + def test_a_model_with_a_part_missing_is_not_ready(self): + part1 = self.blob(self.own / "Model-00001-of-00003.gguf", 10) + self.blob(self.own / "Model-00002-of-00003.gguf", 10) + self.write_config("three-parts", ["--native", part1]) + s = M.Strata(self.root) + desc = s.describe_config(s.configs()[0]) + self.assertFalse(desc["ready"], "one part of three is on disk: not downloaded") + self.assertTrue(any(m.endswith("Model-00003-of-00003.gguf") for m in desc["missing_files"]), desc["missing_files"]) + self.blob(self.own / "Model-00003-of-00003.gguf", 10) + desc = s.describe_config(s.configs()[0]) + self.assertEqual([m for m in desc["missing_files"] if m.endswith(".gguf")], []) From fef5dfec030fc924b4608fc475de0e7ff82a4837 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:08:41 +0200 Subject: [PATCH 04/26] Storage list full width; version list title keeps its spaces --- apps/host/src/components/SettingsStorage.tsx | 2 +- apps/host/src/styles/app.css | 2 +- apps/host/tests/qa1-storage.test.mjs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/host/src/components/SettingsStorage.tsx b/apps/host/src/components/SettingsStorage.tsx index 10700d6a..ba0dab55 100644 --- a/apps/host/src/components/SettingsStorage.tsx +++ b/apps/host/src/components/SettingsStorage.tsx @@ -98,7 +98,7 @@ export function SettingsStorage() { {tr(notice ?

{tr(notice)}

: null)} {tr(directoryError ? : null)}
- + {tr(rows ?
    {tr(nativeModels.map(m =>
  • {nativeShortName(m.model)}{tr(native?.instances.some(i => i.model === m.model) ? {tr('Loaded')} : null)}{tr(sizeGb(m.diskGb ?? 0))} j.state === 'running')} onClick={() => setNativeDeleting(m.model)}>{tr("Delete")}
  • ))} {tr(versions.map(v =>
  • {`${v.local ? v.name : v.family} · ${v.quant}`}{tr(v.local ? {tr('Local')} : null)}{tr(v.id === library?.loaded ? {tr('Loaded')} : null)}{tr(sizeGb(v.diskGb))} { setError(''); setSelected(v.id); }}>{tr("Delete")}
  • ))} diff --git a/apps/host/src/styles/app.css b/apps/host/src/styles/app.css index d3b34218..09667ef3 100644 --- a/apps/host/src/styles/app.css +++ b/apps/host/src/styles/app.css @@ -7027,7 +7027,7 @@ textarea { .version-row.is-on { background: var(--st-surface-2); } .version-row__name { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .version-row__name svg { color: var(--st-accent-text); margin-right: 6px; vertical-align: -2px; } -.version-row__title { display: inline-flex; align-items: baseline; gap: 0; max-width: 100%; } +.version-row__title { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; } .version-row__note { display: block; margin-top: 1px; font-size: var(--st-fs-xs); white-space: normal; line-height: 1.35; } .version-row__have, .version-trigger .version-row__have { margin-left: 8px; padding: 1px 8px; border-radius: var(--st-r-pill); background: var(--st-accent-tint); color: var(--st-accent-text); font-size: var(--st-fs-xs); font-weight: 700; white-space: nowrap; } .version-row__ssd { margin-left: 10px; font-size: var(--st-fs-xs); color: var(--st-warn-text); } diff --git a/apps/host/tests/qa1-storage.test.mjs b/apps/host/tests/qa1-storage.test.mjs index af23db09..62884816 100644 --- a/apps/host/tests/qa1-storage.test.mjs +++ b/apps/host/tests/qa1-storage.test.mjs @@ -27,7 +27,7 @@ test('O01: the route uses that plan and the screen asks for an unload only when test('F02: Settings -> Storage has ONE Downloaded models list and one total, with the shared files as a line of their own', async () => { const screen = await readFile(new URL('../src/components/SettingsStorage.tsx', import.meta.url), 'utf8'); - assert.equal((screen.match(/ Date: Sun, 18 Oct 2026 21:30:17 +0200 Subject: [PATCH 05/26] Read pictures is on unless the person turned it off: an installed model with no saved choice starts checked --- apps/host/server/native-control.mjs | 2 +- apps/host/src/components/NativeModels.tsx | 3 ++- apps/host/tests/qa1-downloads.test.mjs | 24 +++++++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index 19fc1bb3..ebfb9bd6 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -67,7 +67,7 @@ export function createNativeControl({directory,requests=()=>[],changed=()=>{},sp for(const name of names){const path=join(dir,name),config=readJson(path,null);if(!config||typeof config!=='object')continue; const next={...config,...(config.cwd!==undefined?{cwd:fix(config.cwd)}:{}),...(Array.isArray(config.args)?{args:config.args.map(fix)}:{})}; if(JSON.stringify(next)!==JSON.stringify(config)){try{writeModelConfig(path,next);}catch{/* read-only folder: the load reports it */}}}} - function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,visionPrepared:!!cfg.vision,visionEnabled:cfg.ui_vision_enabled??[...instances.values()].some(i=>i.model===entry.model&&i.status==='ready'&&i.vision),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} + function installedInfo(info){if(!info)return info;return {...info,models:(info.models??[]).map(entry=>{const cfg=/^strata-[a-z0-9_-]+\.json$/i.test(entry.config??'')?readJson(entry.configPath??join(repo(),entry.config)):{};const at=cfg.args?.indexOf('--native')??-1,nativeFile=at>=0?cfg.args[at+1]:null;const dataFolder=typeof nativeFile==='string'&&basename(dirname(dirname(nativeFile)))==='models'?dirname(dirname(dirname(nativeFile))):info.data_folder;return {...entry,diskGb:entry.diskGb??entry.disk_gb,diskBytes:entry.diskBytes??entry.disk_bytes,sharedBytes:entry.sharedBytes??entry.shared_bytes,removableGb:entry.removableGb??entry.removable_gb,dataFolder,visionPrepared:!!cfg.vision,/* Picture reading is ON unless the person turned it off: no saved choice and not loaded is undefined, not false (owner rule: pictures on by default). */visionEnabled:cfg.ui_vision_enabled??(()=>{const running=[...instances.values()].find(i=>i.model===entry.model&&i.status==='ready');return running?!!running.vision:undefined;})(),visionDevice:cfg.ui_vision_device,resourceProfile:cfg.ui_resource_profile,lowRamMode:cfg.args?.includes('--resident-experts')?'resident':cfg.args?.includes('--mmap-experts')?'mmap':'auto'};})};} function installRoot(){const found=[preferences.installDir].find(d=>d&&existsSync(d));if(found)return realpathSync(found);mkdirSync(defaultInstall(),{recursive:true});return realpathSync(defaultInstall());} function repo(){if(packaged)return installRoot();const path=realpathSync(preferences.repo);if(!existsSync(join(path,'setup.py'))||!existsSync(join(path,'tools/strata_mcp.py'))||!existsSync(join(path,'serve/server.py')))throw new Error('Choose the Strata repository folder containing setup.py and tools/strata_mcp.py.');return path;} function python(){return resolvePython({repo:preferences.repo});} diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 42ef8c09..255393e1 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -120,7 +120,8 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine if (installed) { if (installed.context) setContext(installed.context); - setVision(installed.visionEnabled === false || installed.images === 'off' ? 'no' : installed.visionDevice ?? installed.images ?? 'yes'); + // Off only when the person turned it off (a saved choice); a model prepared without the picture files (images 'off') still starts with it ON. + setVision(installed.visionEnabled === false ? 'no' : installed.visionDevice ?? (installed.images && installed.images !== 'off' ? installed.images : 'yes')); setKv(installed.kv ?? 'int8'); setLowRam(installed.lowRamMode ?? 'auto'); // A model never tuned has no saved choice: keep the page's own (Leave 20%) rather than flipping to Full performance. diff --git a/apps/host/tests/qa1-downloads.test.mjs b/apps/host/tests/qa1-downloads.test.mjs index 9938d615..3e03ed1e 100644 --- a/apps/host/tests/qa1-downloads.test.mjs +++ b/apps/host/tests/qa1-downloads.test.mjs @@ -1,4 +1,5 @@ import test from 'node:test'; +import { readFileSync as readSource } from 'node:fs'; import assert from 'node:assert/strict'; import { build } from 'esbuild'; import { createEngineStep } from '../server/engine-step.mjs'; @@ -123,3 +124,26 @@ test('the three NVFP4 versions have clear names and one line that tells them apa } lib.setTranslationLanguage('en'); }); + +test('4d: picture reading is on unless the person turned it off (no saved choice is not "off")', async () => { + const { nativeFixture } = await import('./helpers/native-fixture.mjs'); + const { readFileSync, writeFileSync } = await import('node:fs'); + const { join } = await import('node:path'); + const f = nativeFixture(); + try { + await f.control.refresh(true); + const first = () => f.control.state().installed.models.find(m => m.model === 'iq2_xs'); + assert.equal(first().visionEnabled, undefined, 'a model never loaded and never turned off'); + const path = join(f.repo, 'strata-iq2_xs.json'); + const cfg = JSON.parse(readFileSync(path, 'utf8')); + writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: false })); + await f.control.refresh(true); + assert.equal(first().visionEnabled, false, 'turned off by the person: stays off'); + writeFileSync(path, JSON.stringify({ ...cfg, ui_vision_enabled: true, ui_vision_device: 'cpu' })); + await f.control.refresh(true); + assert.equal(first().visionEnabled, true); + } finally { await f.cleanup(); } + const screen = readSource(new URL('../src/components/NativeModels.tsx', import.meta.url), 'utf8'); + assert.match(screen, /setVision\(installed\.visionEnabled === false \? 'no'/); + assert.match(screen, /else\s+setVision\('yes'\)/, 'a version that is not downloaded starts with Read pictures on'); +}); From 43ea31544be8d211b609498508775be825bb3a69 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:31:21 +0200 Subject: [PATCH 06/26] native poll: a read that never answers is dropped after 60 s --- apps/host/src/lib/native.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/host/src/lib/native.ts b/apps/host/src/lib/native.ts index 6053f211..49a1d1c1 100644 --- a/apps/host/src/lib/native.ts +++ b/apps/host/src/lib/native.ts @@ -16,7 +16,7 @@ const listeners=new Set<()=>void>(); function put(value:NativeState){if(state&&JSON.stringify(state)===JSON.stringify(value))return;state=value;listeners.forEach(fn=>fn());} /** The host pushes its whole native state (jobs included) at every progress step: the page shows it at once, without waiting for the next poll. */ export function applyNativeEvent(value:unknown){if(value&&typeof value==='object'&&'available' in value&&'jobs' in value)put(value as NativeState);} -const READ_LIMIT_MS=20000; +const READ_LIMIT_MS=60000; function read(force:boolean):Promise{ const request=api.get(`/api/native${force?'?refresh=1':''}`); // A read that never answers must not freeze the page: after the limit the next poll starts a fresh one. From fb14c354b4146a571226f3d78e0a71094bb07160 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:31:30 +0200 Subject: [PATCH 07/26] strata-vision: HIP build (strata-vision-hip) for AMD GPUs; the reader refuses a GPU that is not in its build; RUNPATH $ORIGIN --- tools/vision/CMakeLists.txt | 33 +++++++++++++++++++++ tools/vision/gpu_arch.h | 33 +++++++++++++++++++++ tools/vision/gpu_arch_test.cpp | 24 +++++++++++++++ tools/vision/strata_vision.cpp | 54 ++++++++++++++++++++++++++++++++++ 4 files changed, 144 insertions(+) create mode 100644 tools/vision/gpu_arch.h create mode 100644 tools/vision/gpu_arch_test.cpp diff --git a/tools/vision/CMakeLists.txt b/tools/vision/CMakeLists.txt index ed42e625..5b09e2d6 100644 --- a/tools/vision/CMakeLists.txt +++ b/tools/vision/CMakeLists.txt @@ -3,6 +3,7 @@ # # cmake -S tools/vision -B build-vision -G Ninja -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR=third_party/llama.cpp # [-DSTRATA_VISION_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=native] [-DSTRATA_PORTABLE=OFF] +# [-DSTRATA_VISION_HIP=ON -DSTRATA_VISION_HIP_ARCHS="gfx1200;gfx1201" + the HIP compiler the engine build uses] # cmake --build build-vision --target strata-vision # # Portable (AVX2 baseline) is the default, so an encoder built without extra flags runs on any AVX2 PC: the 0.1.32 @@ -14,6 +15,14 @@ project(strata_vision C CXX) set(LLAMA_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../third_party/llama.cpp" CACHE PATH "llama.cpp checkout") option(STRATA_VISION_CUDA "run the vision encoder on the GPU (builds ggml-cuda)" OFF) +option(STRATA_VISION_HIP "run the vision encoder on an AMD GPU (builds ggml-hip); the program is named strata-vision-hip" OFF) +set(STRATA_VISION_HIP_ARCHS "" CACHE STRING "the gfx architectures strata-vision-hip is compiled for (';'-separated)") +if(STRATA_VISION_HIP AND STRATA_VISION_CUDA) + message(FATAL_ERROR "strata-vision: STRATA_VISION_CUDA and STRATA_VISION_HIP are two different programs") +endif() +if(STRATA_VISION_HIP AND NOT STRATA_VISION_HIP_ARCHS) + message(FATAL_ERROR "strata-vision: STRATA_VISION_HIP needs STRATA_VISION_HIP_ARCHS, for example \"gfx1200;gfx1201\"") +endif() option(STRATA_PORTABLE "build for other PCs: AVX2 baseline, static MSVC runtime" ON) if(STRATA_PORTABLE AND MSVC) set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded") @@ -52,6 +61,13 @@ else() endif() set(GGML_BACKEND_DL OFF CACHE BOOL "" FORCE) set(GGML_CUDA ${STRATA_VISION_CUDA} CACHE BOOL "" FORCE) +set(GGML_HIP ${STRATA_VISION_HIP} CACHE BOOL "" FORCE) +if(STRATA_VISION_HIP) + # the engine's HIP build says the same (cmake/hip_backend.cmake); ggml-hip reads AMDGPU_TARGETS / CMAKE_HIP_ARCHITECTURES + set(AMDGPU_TARGETS "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) + set(GPU_TARGETS "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) + set(CMAKE_HIP_ARCHITECTURES "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) +endif() add_subdirectory(${LLAMA_DIR} llama EXCLUDE_FROM_ALL) @@ -59,9 +75,26 @@ add_executable(strata-vision strata_vision.cpp) target_link_libraries(strata-vision PRIVATE mtmd llama) target_compile_features(strata-vision PRIVATE cxx_std_17) set_target_properties(strata-vision PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +if(STRATA_VISION_HIP) + # beside strata (and, in a component, the CPU reader "strata-vision"): the GPU reader is its own program, so a PC where + # the HIP runtime does not load still has the CPU one to fall back on + set_target_properties(strata-vision PROPERTIES OUTPUT_NAME strata-vision-hip) + string(REPLACE ";" "," _hip_archs "${STRATA_VISION_HIP_ARCHS}") + target_compile_definitions(strata-vision PRIVATE STRATA_VISION_HIP STRATA_VISION_HIP_ARCHS="${_hip_archs}") +endif() +if(UNIX AND NOT APPLE) + # the libraries it needs are the ones in its own folder (a component folder is relocatable): RUNPATH $ORIGIN + set_target_properties(strata-vision PROPERTIES BUILD_WITH_INSTALL_RPATH ON INSTALL_RPATH "$ORIGIN") + target_link_options(strata-vision PRIVATE -Wl,--enable-new-dtags) +endif() # opens a GGUF that has tensor types llama.cpp does not know (a Gyro quantization's TQK6 / TQK7) for its vocabulary only add_executable(strata-vision-gguf-test EXCLUDE_FROM_ALL gguf_meta_test.cpp) target_link_libraries(strata-vision-gguf-test PRIVATE llama) target_compile_features(strata-vision-gguf-test PRIVATE cxx_std_17) set_target_properties(strata-vision-gguf-test PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) + +# the HIP reader's architecture check (gpu_arch.h), without a GPU +add_executable(strata-vision-arch-test EXCLUDE_FROM_ALL gpu_arch_test.cpp) +target_compile_features(strata-vision-arch-test PRIVATE cxx_std_17) +set_target_properties(strata-vision-arch-test PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) diff --git a/tools/vision/gpu_arch.h b/tools/vision/gpu_arch.h new file mode 100644 index 00000000..411f5201 --- /dev/null +++ b/tools/vision/gpu_arch.h @@ -0,0 +1,33 @@ +// tools/vision/gpu_arch.h - which GPU the HIP picture reader (strata-vision-hip) was compiled for, and whether the GPU it +// found is one of them. ggml-hip prints " Device 0: AMD Radeon RX 9070 XT, gfx1201:sramecc-:xnack- (0x1201), ..." when it +// starts; a card whose architecture is not in the build would fail at its first kernel ("no kernel image", an abort), so +// the reader reads that line and refuses before any kernel runs. The server then starts the CPU reader (see +// serve/server.py, Vision._start). Header only, so gpu_arch_test.cpp can check it without a GPU. +#pragma once + +#include +#include +#include + +// "gfx1201" out of ggml's device line (or a gcnArchName: "gfx1201:sramecc-:xnack-"); "" when there is none +inline std::string strata_gfx_in(const std::string& text) { + for (size_t at = text.find("gfx"); at != std::string::npos; at = text.find("gfx", at + 1)) { + size_t end = at + 3; + while (end < text.size() && std::isxdigit((unsigned char) text[end])) ++end; + if (end > at + 3) return text.substr(at, end - at); + } + return ""; +} + +// "gfx1200,gfx1201" (the build's list; ',' or ';' between) holds `arch` +inline bool strata_arch_listed(const std::string& list, const std::string& arch) { + if (arch.empty()) return false; + size_t start = 0; + while (start <= list.size()) { + size_t end = list.find_first_of(",; ", start); + if (end == std::string::npos) end = list.size(); + if (list.compare(start, end - start, arch) == 0 && end - start == arch.size()) return true; + start = end + 1; + } + return false; +} diff --git a/tools/vision/gpu_arch_test.cpp b/tools/vision/gpu_arch_test.cpp new file mode 100644 index 00000000..7cced432 --- /dev/null +++ b/tools/vision/gpu_arch_test.cpp @@ -0,0 +1,24 @@ +// tools/vision/gpu_arch_test.cpp - the HIP picture reader's architecture check (gpu_arch.h) without a GPU. Exit 0 = passed. +#include "gpu_arch.h" + +#include + +static int bad = 0; +#define CHECK(c) do { if (!(c)) { std::printf("FAIL line %d: %s\n", __LINE__, #c); ++bad; } } while (0) + +int main() { + CHECK(strata_gfx_in(" Device 0: AMD Radeon RX 9070 XT, gfx1201:sramecc-:xnack- (0x1201), VMM: no, Wave Size: 32") == "gfx1201"); + CHECK(strata_gfx_in(" Device 0: AMD Radeon Graphics, gfx1151 (0x1151)") == "gfx1151"); + CHECK(strata_gfx_in(" Device 0: gfx, nothing after it") == ""); + CHECK(strata_gfx_in("no architecture here") == ""); + CHECK(strata_arch_listed("gfx1200,gfx1201", "gfx1201")); + CHECK(strata_arch_listed("gfx1200;gfx1201", "gfx1200")); + CHECK(strata_arch_listed("gfx1100", "gfx1100")); + CHECK(!strata_arch_listed("gfx1200,gfx1201", "gfx1100")); + CHECK(!strata_arch_listed("gfx1100", "gfx110")); // a prefix is not an architecture + CHECK(!strata_arch_listed("gfx1100", "gfx11000")); + CHECK(!strata_arch_listed("", "gfx1100")); + CHECK(!strata_arch_listed("gfx1100", "")); + std::printf(bad ? "gpu_arch_test: %d FAILED\n" : "gpu_arch_test: ok\n", bad); + return bad ? 1 : 0; +} diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 410d9302..b4f4582e 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -13,9 +13,11 @@ // QUIT // The output file is int32 {0x31455653 'SVE1', n_tokens, nx, ny, n_embd} then float32 [n_tokens][n_embd], // row i at grid position (x = i % nx, y = i / nx). The text model is opened vocab-only (no weights). +#include "ggml-backend.h" #include "ggml-cpu.h" #include "gguf.h" #include "gguf_meta.h" +#include "gpu_arch.h" #include "llama.h" #include "mtmd.h" #include "mtmd-helper.h" @@ -37,7 +39,14 @@ namespace { +// the GPU architectures ggml-hip printed while it started (" Device 0: ..., gfx1201:sramecc-:xnack- (0x1201), ...") +std::vector g_gfx; + void quiet_log(ggml_log_level level, const char* text, void*) { + if (level == GGML_LOG_LEVEL_INFO && std::strstr(text, "Device ") != nullptr) { + const std::string gfx = strata_gfx_in(text); + if (!gfx.empty()) g_gfx.push_back(gfx); + } if (level >= GGML_LOG_LEVEL_WARN) std::fputs(text, stderr); } @@ -70,6 +79,16 @@ int main(int argc, char** argv) { if (a == "--mmproj") mmproj = next(); else if (a == "--model") model = next(); else if (a == "--gpu") gpu = true; + else if (a == "--version") { +#ifdef STRATA_VISION_HIP + std::printf("strata-vision hip (GPU architectures: %s) +", STRATA_VISION_HIP_ARCHS); +#else + std::printf("strata-vision +"); +#endif + return 0; + } else if (a == "--threads") threads = std::atoi(next().c_str()); else if (a == "--max-tokens") max_tokens = std::atoi(next().c_str()); else if (a == "--min-tokens") min_tokens = std::atoi(next().c_str()); // mtmd image_min_tokens (#767) @@ -91,13 +110,48 @@ int main(int argc, char** argv) { if (!gpu) { #ifdef _WIN32 _putenv_s("CUDA_VISIBLE_DEVICES", "-1"); + _putenv_s("HIP_VISIBLE_DEVICES", "-1"); #else setenv("CUDA_VISIBLE_DEVICES", "-1", 1); + setenv("HIP_VISIBLE_DEVICES", "-1", 1); #endif } llama_log_set(quiet_log, nullptr); mtmd_helper_log_set(quiet_log, nullptr); llama_backend_init(); + if (gpu) { + // Starting the backends prints the GPU line; with --gpu and no GPU, mtmd would quietly use the CPU, and a card + // the HIP build has no code for would abort at its first kernel. Both end here with a line the server reads + // (it then starts the CPU reader). + bool have_gpu = false; + for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { + const auto type = ggml_backend_dev_type(ggml_backend_dev_get(i)); + have_gpu = have_gpu || type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; + } + if (!have_gpu) { + std::printf("ERR this picture reader found no GPU (it was built for: %s) +", +#ifdef STRATA_VISION_HIP + STRATA_VISION_HIP_ARCHS +#else + "none" +#endif + ); + std::fflush(stdout); + return 3; + } +#ifdef STRATA_VISION_HIP + const char* check = std::getenv("STRATA_VISION_ARCH_CHECK"); + if (!g_gfx.empty() && (check == nullptr || std::atoi(check) != 0) && + !strata_arch_listed(STRATA_VISION_HIP_ARCHS, g_gfx.front())) { + std::printf("ERR this GPU (%s) is not in the picture reader's build (%s) +", g_gfx.front().c_str(), + STRATA_VISION_HIP_ARCHS); + std::fflush(stdout); + return 3; + } +#endif + } const auto load_t0 = std::chrono::steady_clock::now(); #if !defined(_WIN32) && !defined(__APPLE__) // macOS has no posix_fadvise From 96658aebaeb8975848b241eb954e91b61717743e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:32:58 +0200 Subject: [PATCH 08/26] packaging: build_hip_linux.sh builds the HIP engine package with both picture readers --- packaging/build_hip_linux.sh | 94 ++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 packaging/build_hip_linux.sh diff --git a/packaging/build_hip_linux.sh b/packaging/build_hip_linux.sh new file mode 100644 index 00000000..e833bc69 --- /dev/null +++ b/packaging/build_hip_linux.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Linux AMD (HIP) engine package: strata + the CPU picture reader (strata-vision) + the GPU picture reader (strata-vision-hip), +# the ROCm libraries both load, and the rocBLAS / hipBLASLt kernel data for the listed archs, packaged as an engine component. +# Run on a Linux box that has ROCm (TheRock Python wheels are enough); the tester packages were built in an Ubuntu 22.04 chroot +# (glibc 2.35) so they run on every distribution since. All settings are environment variables: +# +# VARIANT=rx9070 rx9070 (gfx1200 gfx1201) | rx7900 (gfx1100 gfx1101 gfx1102) | halo (gfx1151) | igpu (gfx1103 gfx1150) | a name + ARCHS= +# ARCHS="gfx1200;gfx1201" the code objects (default: the variant's) +# SRC= the Strata source (default: the checkout this script is in) +# LLAMA= at the pinned commit (setup.py LLAMA_CPP_COMMIT); mtmd and ggml come from it +# HP= CORE= LIBW= (TheRock: _rocm_sdk_devel, _rocm_sdk_core, _rocm_sdk_libraries_*) +# OUT= PKGVER=0.1.45.3 COMMIT= JOBS=16 +# VISION_ONLY=1 build only the two readers (no engine, no package) +# NO_PACKAGE=1 stop after the stage folder +# +# Both readers get RUNPATH $ORIGIN (tools/vision/CMakeLists.txt), and every bundled library is patched to $ORIGIN, so the +# component folder runs from anywhere with nothing from the environment (packaging/binary_deps.py checks it). +set -u +V=${VARIANT:?VARIANT=rx9070|rx7900|halo|igpu| with ARCHS=} +SRC=${SRC:-$(cd "$(dirname "$0")/.." && pwd)} +LLAMA=${LLAMA:?LLAMA=} +HP=${HP:?HP=} +CORE=${CORE:-$HP} +LIBW=${LIBW:-$HP} +OUT=${OUT:-$PWD/work-$V} +PKGVER=${PKGVER:-0.1.45.3} +COMMIT=${COMMIT:-unknown} +JOBS=${JOBS:-16} +case "$V" in + rx9070) ARCHS=${ARCHS:-gfx1200;gfx1201} ;; + rx7900) ARCHS=${ARCHS:-gfx1100;gfx1101;gfx1102} ;; + halo) ARCHS=${ARCHS:-gfx1151} ;; + igpu) ARCHS=${ARCHS:-gfx1103;gfx1150} ;; + *) ARCHS=${ARCHS:?ARCHS=gfx...} ;; +esac +ARCHLIST=${ARCHS//;/ } +DATAARCH=${ARCHS//;/,} +mkdir -p "$OUT"; S=$OUT/build.status +st() { echo "$* $(date +%T)" >> "$S"; } +: > "$S" +export HIP_PLATFORM=amd HIP_COMPILER=clang HIP_RUNTIME=rocclr ROCM_PATH=$HP HIP_PATH=$HP +HIPDEFS=(-DCMAKE_HIP_COMPILER=$HP/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=$HP "-DCMAKE_PREFIX_PATH=$HP;$LIBW" + "-DCMAKE_HIP_FLAGS=--rocm-path=$HP --rocm-device-lib-path=$HP/lib/llvm/amdgcn/bitcode") +st "start $V ($ARCHS) commit $COMMIT" +cd "$SRC" || exit 1 +if [ -z "${VISION_ONLY:-}" ]; then + cmake -G Ninja -S . -B "$OUT/b" -DCMAKE_BUILD_TYPE=Release -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_BUILD_TESTS=OFF \ + -DSTRATA_PREFILL_MMQ=ON "-DCMAKE_HIP_ARCHITECTURES=$ARCHS" "${HIPDEFS[@]}" -DSTRATA_GGML_DIR="$LLAMA" -DSTRATA_PORTABLE=ON \ + "-DCMAKE_EXE_LINKER_FLAGS=-Wl,-rpath,'\$ORIGIN' -Wl,--enable-new-dtags" > "$OUT/cfg.log" 2>&1 + st "engine configured rc=$?" + nice -n 10 cmake --build "$OUT/b" --target strata -j "$JOBS" > "$OUT/build.log" 2>&1 + st "engine built rc=$?" + [ -x "$OUT/b/strata" ] || { st "ABORT no strata"; exit 1; } +fi +# the CPU reader: portable (AVX2), the fallback that runs on any PC +cmake -G Ninja -S tools/vision -B "$OUT/bv" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="$LLAMA" -DSTRATA_VISION_CUDA=OFF \ + -DSTRATA_PORTABLE=ON > "$OUT/cfg-vision.log" 2>&1 +nice -n 10 cmake --build "$OUT/bv" --target strata-vision -j "$JOBS" > "$OUT/build-vision.log" 2>&1 +st "cpu reader built rc=$?" +[ -x "$OUT/bv/bin/strata-vision" ] || { st "ABORT no strata-vision"; exit 1; } +# the GPU reader: ggml-hip for the same archs; the CPU kernels in it are portable too +cmake -G Ninja -S tools/vision -B "$OUT/bh" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="$LLAMA" -DSTRATA_VISION_HIP=ON \ + "-DSTRATA_VISION_HIP_ARCHS=$ARCHS" -DSTRATA_PORTABLE=ON "${HIPDEFS[@]}" > "$OUT/cfg-vision-hip.log" 2>&1 +st "gpu reader configured rc=$?" +nice -n 10 cmake --build "$OUT/bh" --target strata-vision -j "$JOBS" > "$OUT/build-vision-hip.log" 2>&1 +st "gpu reader built rc=$?" +[ -x "$OUT/bh/bin/strata-vision-hip" ] || { st "ABORT no strata-vision-hip"; tail -20 "$OUT/build-vision-hip.log" >> "$S"; exit 1; } +[ -n "${VISION_ONLY:-}" ] && { st "VISION-DONE"; exit 0; } +STAGE=$OUT/stage; rm -rf "$STAGE"; mkdir -p "$STAGE" +cp "$OUT/b/strata" "$OUT/bv/bin/strata-vision" "$OUT/bh/bin/strata-vision-hip" "$STAGE/" +ARCHJSON=$(for a in $ARCHLIST; do printf '"%s", ' "$a"; done | sed 's/, $//') +cat > "$STAGE/BUILD.json" <> "$OUT/collect.log" 2>&1 + st "collected for $b rc=$?" +done +for f in "$STAGE"/*.so "$STAGE"/*.so.*; do [ -f "$f" ] && [ ! -L "$f" ] && patchelf --set-rpath '$ORIGIN' "$f"; done +for f in "$STAGE/strata" "$STAGE/strata-vision" "$STAGE/strata-vision-hip"; do + st "RUNPATH $(basename "$f"): $(readelf -d "$f" | grep -E 'RPATH|RUNPATH' | cut -d'[' -f2 | tr -d ']' | paste -sd' ')" +done +[ -n "${NO_PACKAGE:-}" ] && { st "STAGE-DONE"; exit 0; } +rm -rf "$OUT/components"; mkdir -p "$OUT/components/engine" +ARCHARGS=""; for a in $ARCHLIST; do ARCHARGS="$ARCHARGS --arch $a"; done +python3 packaging/package_engine.py --src "$STAGE" --backend hip --version "$PKGVER" --out "$OUT/components/engine" $ARCHARGS \ + --variant "$V" --build-id "$COMMIT+rocm" --tree --notes "AMD $V build: engine, CPU picture reader, GPU picture reader" > "$OUT/package.log" 2>&1 +st "packaged rc=$?" +cat "$OUT/package.log" >> "$S" +st "BUILD-DONE" From 75127c794e64ddc9e7ad4ff32d92e7d31b2e5c73 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:34:28 +0200 Subject: [PATCH 09/26] strata-vision: fix the escaped newlines --- tools/vision/strata_vision.cpp | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index b4f4582e..293e0198 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -81,11 +81,9 @@ int main(int argc, char** argv) { else if (a == "--gpu") gpu = true; else if (a == "--version") { #ifdef STRATA_VISION_HIP - std::printf("strata-vision hip (GPU architectures: %s) -", STRATA_VISION_HIP_ARCHS); + std::printf("strata-vision hip (GPU architectures: %s)\n", STRATA_VISION_HIP_ARCHS); #else - std::printf("strata-vision -"); + std::printf("strata-vision\n"); #endif return 0; } @@ -129,8 +127,7 @@ int main(int argc, char** argv) { have_gpu = have_gpu || type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; } if (!have_gpu) { - std::printf("ERR this picture reader found no GPU (it was built for: %s) -", + std::printf("ERR this picture reader found no GPU (it was built for: %s)\n", #ifdef STRATA_VISION_HIP STRATA_VISION_HIP_ARCHS #else @@ -144,8 +141,7 @@ int main(int argc, char** argv) { const char* check = std::getenv("STRATA_VISION_ARCH_CHECK"); if (!g_gfx.empty() && (check == nullptr || std::atoi(check) != 0) && !strata_arch_listed(STRATA_VISION_HIP_ARCHS, g_gfx.front())) { - std::printf("ERR this GPU (%s) is not in the picture reader's build (%s) -", g_gfx.front().c_str(), + std::printf("ERR this GPU (%s) is not in the picture reader's build (%s)\n", g_gfx.front().c_str(), STRATA_VISION_HIP_ARCHS); std::fflush(stdout); return 3; From f82fffbe25be01999de0ae76d4594ce9f2318a4c Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:39:13 +0200 Subject: [PATCH 10/26] picture reader choice for AMD engine folders and the server's fallback from the GPU reader to the CPU reader (one log line) --- serve/server.py | 45 +++++-- strata_control/vision_reader.py | 101 ++++++++++++++++ tools/test_vision_reader.py | 202 ++++++++++++++++++++++++++++++++ 3 files changed, 338 insertions(+), 10 deletions(-) create mode 100644 strata_control/vision_reader.py create mode 100644 tools/test_vision_reader.py diff --git a/serve/server.py b/serve/server.py index 1b82c102..bce59b6f 100644 --- a/serve/server.py +++ b/serve/server.py @@ -66,6 +66,7 @@ from serve.frontend import (THINK_END, ChatTemplate, Event, OutputParser, anthro from serve.mcp import McpCancelled, hub_from_config # noqa: E402 from serve import runconfig # noqa: E402 from strata_control import engine_component # noqa: E402 +from strata_control import vision_reader # noqa: E402 from serve import ready as ready_file # noqa: E402 from serve import owner_guard # noqa: E402 from serve import launch_identity # noqa: E402 @@ -2487,18 +2488,13 @@ class Vision: return Path(tempfile.mkdtemp(prefix="strata-vision-")) def __init__(self, cfg: dict, log=None, env: dict | None = None, lazy: bool = False): - absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p # the encoder runs in its own dir (#480) # noqa: E731 - args = [absolute(cfg["exe"]), "--mmproj", absolute(cfg["mmproj"]), "--model", absolute(cfg["model"])] - if cfg.get("gpu"): - args.append("--gpu") - if cfg.get("threads"): - args += ["--threads", str(cfg["threads"])] - if cfg.get("max_tokens"): - args += ["--max-tokens", str(cfg["max_tokens"])] - if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) - args += ["--min-tokens", str(cfg["min_tokens"])] + args = self.reader_args(cfg) self.dir = self.work_dir() self.spawn = (args, log, env) # to start it again after an unload + # AMD: the GPU reader (strata-vision-hip) has the CPU reader (strata-vision, same program, no GPU runtime) to + # fall back on when it does not start; _start switches to it by itself + cpu = vision_reader.cpu_fallback(cfg) + self.fallback = (self.reader_args(cpu), log, env) if cpu else None self.proc = None self.stopped = True self.lock = threading.Lock() @@ -2512,7 +2508,36 @@ class Vision: if not lazy and not self.elastic: self._start() + @staticmethod + def reader_args(cfg: dict) -> list: + absolute = lambda p: os.path.abspath(p) if os.path.dirname(str(p)) else p # the encoder runs in its own dir (#480) # noqa: E731 + args = [absolute(cfg["exe"]), "--mmproj", absolute(cfg["mmproj"]), "--model", absolute(cfg["model"])] + if cfg.get("gpu"): + args.append("--gpu") + if cfg.get("threads"): + args += ["--threads", str(cfg["threads"])] + if cfg.get("max_tokens"): + args += ["--max-tokens", str(cfg["max_tokens"])] + if cfg.get("min_tokens"): # #767: mtmd's image_min_tokens (a hand-edited key) + args += ["--min-tokens", str(cfg["min_tokens"])] + return args + def _start(self): + """Start the reader. When a GPU reader that has a CPU reader to fall back on does not start (the GPU runtime does not + load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line + and no question.""" + try: + self._start_reader() + except (RuntimeError, OSError) as e: + fallback = getattr(self, "fallback", None) + if fallback is None: + raise + why = " ".join(str(e).split())[:240] + print(f"[strata] the GPU picture reader did not start ({why}); pictures are read on the CPU", flush=True) + self.spawn, self.fallback = fallback, None + self._start_reader() + + def _start_reader(self): args, log, env = self.spawn # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) self.proc = popen("the image encoder", args, role="vision", stdin=subprocess.PIPE, stdout=subprocess.PIPE, diff --git a/strata_control/vision_reader.py b/strata_control/vision_reader.py new file mode 100644 index 00000000..cd000194 --- /dev/null +++ b/strata_control/vision_reader.py @@ -0,0 +1,101 @@ +"""Which picture reader an engine folder gets: the GPU one (`strata-vision-hip`, AMD) or the CPU one (`strata-vision`). + +An AMD engine package carries two programs for pictures. `strata-vision` is the CPU reader: it needs nothing from the GPU +runtime, so it starts on every PC. `strata-vision-hip` is the same reader on the card (llama.cpp's HIP backend), a +fraction of a second per picture instead of seconds. Setup writes the run config with the GPU reader first and the CPU +reader as its fallback (`vision.cpu_exe`); the server (serve/server.py, Vision) starts the CPU reader by itself, with one +log line, when the GPU reader does not start: the HIP runtime does not load, the card is not one the build has code for +(the reader says so before it runs a kernel), or the card is busy. Nothing is asked of the user. + +`choose` is the whole decision; setup.py calls it, and tools/test_vision_reader.py checks every branch. +""" +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +CPU_READER = "strata-vision" +GPU_READER = "strata-vision-hip" + +GFX = re.compile(r"gfx[0-9a-f]+", re.IGNORECASE) + + +def reader_name(base: str, windows: bool) -> str: + return base + (".exe" if windows else "") + + +def find(folder: Path | str, windows: bool) -> dict: + """The readers in an engine folder: {"cpu": Path | None, "gpu": Path | None}.""" + folder = Path(folder) + found = {} + for key, base in (("cpu", CPU_READER), ("gpu", GPU_READER)): + path = folder / reader_name(base, windows) + found[key] = path if path.is_file() else None + return found + + +def gfx_of(text: object) -> str: + """"gfx1201" out of a gcnArchName ("gfx1201:sramecc-:xnack-"), a device line or a plain arch; "" when there is none.""" + m = GFX.search(str(text or "")) + return m.group(0).lower() if m else "" + + +@dataclass +class Reader: + mode: str # "gpu" | "cpu" | "none" + exe: Path | None = None # the program the run config starts + cpu_exe: Path | None = None # the CPU reader to fall back on when a GPU reader does not start (mode "gpu" only) + note: str = "" # one plain sentence for the setup output when it is not what was asked for + + +def choose(folder: Path | str, asked: str, *, windows: bool, gpu_arch: str = "", archs: list | None = None) -> Reader: + """The reader for `asked` ("yes"/"on"/"gpu" = the best the folder has, "cpu", "no"/"none"/"off"). + + gpu_arch: the card's architecture when setup knows it ("gfx1201"); archs: what the GPU reader was built for + (BUILD.json `vision_archs`, else the package's `archs`). A card the build does not list gets the CPU reader here; + when the card is unknown the GPU reader is tried and falls back by itself (see the module doc).""" + asked = (asked or "").lower() + if asked in ("no", "none", "off", ""): + return Reader("none") + have = find(folder, windows) + if asked == "cpu": + if have["cpu"]: + return Reader("cpu", have["cpu"]) + return Reader("none", note="this engine has no picture reader: pictures off") + # yes / on / gpu + gfx = gfx_of(gpu_arch) + built = [gfx_of(a) for a in (archs or []) if gfx_of(a)] + if have["gpu"] is None: + if have["cpu"]: + return Reader("cpu", have["cpu"], note="this engine has no GPU picture reader: pictures are read on the CPU " + "(a few seconds each)" if asked == "gpu" else "") + return Reader("none", note="this engine has no picture reader: pictures off") + if gfx and built and gfx not in built: + if have["cpu"]: + return Reader("cpu", have["cpu"], note=f"the GPU picture reader has no code for your card ({gfx}): pictures " + "are read on the CPU (a few seconds each)") + return Reader("none", note=f"the GPU picture reader has no code for your card ({gfx}): pictures off") + return Reader("gpu", have["gpu"], have["cpu"]) + + +def vision_section(reader: Reader, base: dict) -> dict: + """The run config's "vision" section for `reader` on top of `base` (mmproj, model, max_tokens ...): exe, gpu, and for the + GPU reader the CPU reader to fall back on.""" + out = dict(base) + out["exe"] = str(reader.exe) + out["gpu"] = reader.mode == "gpu" + if reader.mode == "gpu" and reader.cpu_exe: + out["cpu_exe"] = str(reader.cpu_exe) + else: + out.pop("cpu_exe", None) + return out + + +def cpu_fallback(vision_cfg: dict) -> dict | None: + """The same section for the CPU reader, when the GPU reader has one to fall back on; None otherwise.""" + if not vision_cfg.get("gpu") or not vision_cfg.get("cpu_exe"): + return None + out = {k: v for k, v in vision_cfg.items() if k not in ("cpu_exe", "elastic", "elastic_mib", "elastic_idle_s")} + out["exe"], out["gpu"] = vision_cfg["cpu_exe"], False + return out diff --git a/tools/test_vision_reader.py b/tools/test_vision_reader.py new file mode 100644 index 00000000..1f77b0c9 --- /dev/null +++ b/tools/test_vision_reader.py @@ -0,0 +1,202 @@ +"""The picture reader choice for an AMD engine folder (strata_control/vision_reader.py) and the server's fallback from the GPU +reader to the CPU reader (serve/server.py, Vision._start): hip present, hip missing, hip start failure, then cpu. + + python -m unittest tools.test_vision_reader +""" +from __future__ import annotations + +import io +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +from strata_control import vision_reader as VR +import serve.server as server + + +def folder(*names: str) -> Path: + d = Path(tempfile.mkdtemp(prefix="vr-")) + for n in names: + (d / n).write_bytes(b"x") + return d + + +class Choose(unittest.TestCase): + def test_hip_present_gives_the_gpu_reader_with_the_cpu_one_to_fall_back_on(self): + d = folder("strata-vision", "strata-vision-hip") + for ask in ("yes", "on", "gpu"): + r = VR.choose(d, ask, windows=False, gpu_arch="gfx1201", archs=["gfx1200", "gfx1201"]) + self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name), ("gpu", "strata-vision-hip", "strata-vision"), ask) + self.assertEqual(r.note, "") + + def test_hip_missing_gives_the_cpu_reader(self): + d = folder("strata-vision") + r = VR.choose(d, "yes", windows=False, gpu_arch="gfx1201") + self.assertEqual((r.mode, r.exe.name, r.cpu_exe), ("cpu", "strata-vision", None)) + self.assertEqual(r.note, "") # "yes" never asked for the GPU in particular + self.assertIn("no GPU picture reader", VR.choose(d, "gpu", windows=False).note) # --vision gpu: said once + + def test_card_not_in_the_build_gives_the_cpu_reader(self): + d = folder("strata-vision", "strata-vision-hip") + r = VR.choose(d, "yes", windows=False, gpu_arch="gfx1100", archs=["gfx1200", "gfx1201"]) + self.assertEqual((r.mode, r.exe.name), ("cpu", "strata-vision")) + self.assertIn("gfx1100", r.note) + + def test_unknown_card_tries_the_gpu_reader(self): + d = folder("strata-vision", "strata-vision-hip") + self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="", archs=["gfx1201"]).mode, "gpu") + self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="gfx1100", archs=None).mode, "gpu") + + def test_gcn_arch_names_with_features_match(self): + self.assertEqual(VR.gfx_of("gfx1201:sramecc-:xnack-"), "gfx1201") + d = folder("strata-vision", "strata-vision-hip") + self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="gfx1151:sramecc+:xnack-", archs=["gfx1151"]).mode, "gpu") + + def test_cpu_asked_and_off(self): + d = folder("strata-vision", "strata-vision-hip") + self.assertEqual(VR.choose(d, "cpu", windows=False).exe.name, "strata-vision") + for ask in ("no", "none", "off", None): + self.assertEqual(VR.choose(d, ask, windows=False).mode, "none") + + def test_no_reader_at_all(self): + d = folder("strata") + for ask in ("yes", "cpu", "gpu"): + r = VR.choose(d, ask, windows=False) + self.assertEqual(r.mode, "none", ask) + self.assertIn("no picture reader", r.note) + + def test_windows_names(self): + d = folder("strata-vision.exe", "strata-vision-hip.exe") + r = VR.choose(d, "yes", windows=True, gpu_arch="gfx1201", archs=["gfx1201"]) + self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name), ("gpu", "strata-vision-hip.exe", "strata-vision.exe")) + self.assertEqual(VR.choose(folder("strata-vision-hip"), "yes", windows=True).mode, "none") # a Linux name on Windows + + def test_run_config_section(self): + d = folder("strata-vision", "strata-vision-hip") + base = {"mmproj": "m.gguf", "model": "t.gguf", "max_tokens": 1024} + sec = VR.vision_section(VR.choose(d, "yes", windows=False), base) + self.assertTrue(sec["gpu"]) + self.assertEqual(Path(sec["exe"]).name, "strata-vision-hip") + self.assertEqual(Path(sec["cpu_exe"]).name, "strata-vision") + cpu = VR.cpu_fallback(sec) + self.assertFalse(cpu["gpu"]) + self.assertEqual(Path(cpu["exe"]).name, "strata-vision") + self.assertNotIn("cpu_exe", cpu) + self.assertEqual(cpu["mmproj"], "m.gguf") + cpu_only = VR.vision_section(VR.choose(folder("strata-vision"), "yes", windows=False), base) + self.assertFalse(cpu_only["gpu"]) + self.assertNotIn("cpu_exe", cpu_only) + self.assertIsNone(VR.cpu_fallback(cpu_only)) + self.assertIsNone(VR.cpu_fallback({**sec, "cpu_exe": ""})) + self.assertIsNone(VR.cpu_fallback({"exe": "strata-vision", "gpu": True})) # an NVIDIA config has no fallback + + +class FakeProc: + def __init__(self, first_line: str): + self.stdin, self.stdout = io.StringIO(), io.StringIO(first_line) + self.killed = False + + def kill(self): + self.killed = True + + def wait(self, timeout=None): + return 0 + + def poll(self): + return None + + +def make_vision(cfg: dict) -> "server.Vision": + with mock.patch.object(server.Vision, "work_dir", staticmethod(lambda: Path(tempfile.gettempdir()))): + return server.Vision(cfg, lazy=True) + + +class Fallback(unittest.TestCase): + CFG = {"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision", "gpu": True, "mmproj": "/m/mm.gguf", + "model": "/m/t.gguf", "max_tokens": 1024, "threads": 6} + + def run_start(self, answers: dict, cfg: dict | None = None): + """answers: exe name -> its first stdout line, or an exception to raise from popen.""" + started = [] + + def popen(what, args, **kw): + name = Path(args[0]).name + started.append(args) + a = answers[name] + if isinstance(a, Exception): + raise a + return FakeProc(a) + + v = make_vision(cfg or self.CFG) + out = io.StringIO() + with mock.patch.object(server, "popen", popen), mock.patch("builtins.print", lambda *a, **k: out.write(" ".join(map(str, a)) + "\n")): + err = None + try: + v._start() + except RuntimeError as e: + err = e + return v, started, out.getvalue(), err + + def test_hip_present_and_starts(self): + v, started, log, err = self.run_start({"strata-vision-hip": "READY 2048\n"}) + self.assertIsNone(err) + self.assertEqual([Path(a[0]).name for a in started], ["strata-vision-hip"]) + self.assertIn("--gpu", started[0]) + self.assertEqual(log, "") + self.assertFalse(v.stopped) + + def test_hip_start_failure_falls_back_to_cpu_with_one_line(self): + v, started, log, err = self.run_start({"strata-vision-hip": "ERR this GPU (gfx1100) is not in the picture reader's build (gfx1200,gfx1201)\n", + "strata-vision": "READY 2048\n"}) + self.assertIsNone(err) + self.assertEqual([Path(a[0]).name for a in started], ["strata-vision-hip", "strata-vision"]) + self.assertNotIn("--gpu", started[1]) + self.assertIn("--threads", started[1]) + self.assertEqual(log.count("\n"), 1) + self.assertIn("gfx1100", log) + self.assertIn("CPU", log) + self.assertFalse(v.stopped) + self.assertIsNone(v.fallback) + + def test_hip_process_that_dies_silently_falls_back(self): # a GPU runtime that aborts: stdout closes empty + v, started, log, err = self.run_start({"strata-vision-hip": "", "strata-vision": "READY 2048\n"}) + self.assertIsNone(err) + self.assertEqual(len(started), 2) + self.assertEqual(log.count("\n"), 1) + + def test_hip_missing_file_falls_back(self): # popen raises (exe gone, not executable) + v, started, log, err = self.run_start({"strata-vision-hip": FileNotFoundError("strata-vision-hip"), + "strata-vision": "READY 2048\n"}) + self.assertIsNone(err) + self.assertEqual(len(started), 2) + + def test_restart_after_a_fallback_stays_on_the_cpu_reader(self): + v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n", "strata-vision": "READY 2048\n"}) + started.clear() + with mock.patch.object(server, "popen", lambda what, args, **kw: started.append(args) or FakeProc("READY 2048\n")): + v.restart() + self.assertEqual([Path(a[0]).name for a in started], ["strata-vision"]) + + def test_cpu_failure_after_the_fallback_is_an_error(self): + v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n", "strata-vision": "ERR cannot load the vision encoder\n"}) + self.assertIsNotNone(err) + self.assertIn("cannot load", str(err)) + + def test_a_config_without_cpu_exe_has_no_fallback(self): # NVIDIA: the error is shown as before + cfg = {k: v for k, v in self.CFG.items() if k != "cpu_exe"} + v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n"}, cfg) + self.assertIsNotNone(err) + self.assertEqual(len(started), 1) + self.assertEqual(log, "") + + def test_cpu_config_is_unchanged(self): + cfg = {"exe": "/e/strata-vision", "gpu": False, "mmproj": "/m/mm.gguf", "model": "/m/t.gguf"} + v, started, log, err = self.run_start({"strata-vision": "READY 2048\n"}, cfg) + self.assertIsNone(err) + self.assertNotIn("--gpu", started[0]) + + +if __name__ == "__main__": + unittest.main() From de9101935d3b1cfd186854325178f82faadbdc53 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:43:23 +0200 Subject: [PATCH 11/26] setup: AMD pictures on by default (the HIP reader with the CPU reader behind it, else the CPU reader), on Windows too; source build compiles the HIP reader; package_engine carries strata-vision-hip --- packaging/package_engine.py | 2 +- setup.py | 113 ++++++++++++++++++++++++++++-------- tools/test_setup_amd.py | 38 +++++++++--- tools/test_setup_choices.py | 10 ++-- tools/test_setup_qwen36.py | 35 +++++++++-- 5 files changed, 154 insertions(+), 44 deletions(-) diff --git a/packaging/package_engine.py b/packaging/package_engine.py index 15820294..319f3cab 100644 --- a/packaging/package_engine.py +++ b/packaging/package_engine.py @@ -53,7 +53,7 @@ def sha256(path: Path) -> str: def wanted(path: Path) -> bool: name = path.name.lower() return (name.endswith((".dll", ".so", ".dylib", ".metallib")) or ".so." in name or name == "build.json" - or name.startswith("license") or name in ("strata-vision", "strata-vision.exe")) # the picture reader beside the engine (pictures need it) + or name.startswith("license") or name in ("strata-vision", "strata-vision.exe", "strata-vision-hip", "strata-vision-hip.exe")) # the picture readers (CPU, AMD GPU) beside the engine def git_build_id(repo: Path = ROOT) -> str: diff --git a/setup.py b/setup.py index 0c7ab554..cdb4fb15 100644 --- a/setup.py +++ b/setup.py @@ -574,6 +574,7 @@ VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700}, "cpu": {"max_tokens": 300, "reserve_mib": 700}} EXE = "strata.exe" if WIN else "strata" VEXE = "strata-vision.exe" if WIN else "strata-vision" +HVEXE = "strata-vision-hip.exe" if WIN else "strata-vision-hip" # AMD: the picture reader on the GPU (tools/vision, STRATA_VISION_HIP) # MODEL-UPDATE Phase 1: the K-quant prompt kernels (Unsloth's UD-Q4/Q5/Q6_K_XL experts) are a library next to the CUDA # engine, opened only for those models; an engine without it runs them on the FP16 prompt path KQ_LIB = "strata_kq.dll" if WIN else "libstrata_kq.so" @@ -3340,12 +3341,13 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: floor = cpu_floor(cpu_info()[1]) # "" on an AVX2 CPU: the normal engine engine_ok = meta.get("backend") == "hip" and (eng / EXE).exists() and meta.get("src") == src and has_archs and \ (meta.get("isa_floor") or "") == floor and not stale_binary(eng / EXE) - vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc) + vision_ok = vision == "none" or ((eng / VEXE).exists() and meta.get("vision_src") == vsrc and + (vision != "gpu" or ((eng / HVEXE).exists() and set(archs) <= set(meta.get("vision_archs", []))))) if engine_ok and vision_ok: ok("engine already built for this PC") return eng if engine_ok: - return build_vision_cpu(eng, stamp, meta, llama, vsrc) + return build_vision_hip(eng, stamp, meta, llama, vsrc, archs, vision) if not (shutil.which("c++") or shutil.which("g++")) or not shutil.which("git"): fail("a C++ compiler and git are needed to compile the AMD engine", "Ubuntu/Debian: sudo apt install build-essential git Fedora: sudo dnf install gcc-c++ git") @@ -3376,23 +3378,80 @@ def build_engine_hip(gpu, llama, vision="none") -> Path: meta = {"source": "local-hip", "backend": "hip", "version": source_version(), "archs": archs, "vision": "none", "lib_dirs": dirs, "src": src, **({"isa_floor": floor} if floor else {})} if vision != "none": - return build_vision_cpu(eng, stamp, meta, llama, vsrc) + return build_vision_hip(eng, stamp, meta, llama, vsrc, archs, vision) stamp.write_text(json.dumps(meta, indent=1)) ok(f"engine compiled: {eng / EXE}") return eng def hip_vision(asked) -> str: - """The image encoder with the AMD backend (--vision): the CPU one when asked for (#304); a HIP (GPU) encoder build - is a later step, so `yes`/`gpu` leave images off, as before, and say how to get them.""" - if asked in ("yes", "gpu"): - warn("the AMD backend has no GPU image encoder yet: images off" - + ("" if WIN else " (--vision cpu reads them on the CPU)")) - if asked == "cpu" and WIN: - warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " - "image encoder): images off") + """The picture reader wanted with the AMD backend (--vision): "gpu" for yes/gpu and when nothing was asked (pictures are on + by default), "cpu" when asked for (#304), "none" for no. "gpu" is a wish: hip_reader() settles it against what the + engine folder carries (the HIP reader, else the CPU one) once the engine is known.""" + if asked in ("no", "none"): return "none" - return "cpu" if asked == "cpu" else "none" + return "cpu" if asked == "cpu" else "gpu" + + +def reader_archs(eng: Path) -> list: + """The GPU architectures the engine folder's HIP picture reader was built for: its BUILD.json (vision_archs, else archs), + else the component manifest's archs; [] when neither says (the reader then checks the card itself when it starts).""" + for name, keys in (("BUILD.json", ("vision_archs", "archs")), ("engine-component.json", ("archs",))): + try: + data = json.loads((eng / name).read_text(encoding="utf-8-sig")) + except (OSError, ValueError): + continue + for key in keys: + if isinstance(data, dict) and isinstance(data.get(key), list) and data[key]: + return [str(x) for x in data[key]] + return [] + + +def hip_reader(eng: Path, vision: str, gpu: dict): + """AMD: the picture reader this engine folder gets for `vision` ("gpu" or "cpu"; strata_control/vision_reader.py): the HIP + reader with the CPU reader to fall back on, else the CPU reader. Returns (vision, Reader); a Reader of mode "none" means + the folder has no reader. The one plain note (a card the HIP reader has no code for, no HIP reader in this engine) is said.""" + from strata_control import vision_reader as VR + r = VR.choose(eng, vision, windows=WIN, gpu_arch=str(gpu.get("arch") or ""), archs=reader_archs(eng)) + if r.note: + warn(r.note) + return r.mode, r + + +def build_vision_hip(eng: Path, stamp: Path, meta: dict, llama, vsrc, archs: list, vision: str) -> Path: + """The picture readers beside the HIP engine: the CPU reader always (the fallback), and for "gpu" the HIP reader + (tools/vision, STRATA_VISION_HIP) for the same architectures. The HIP reader needs the ROCm environment the engine build + sets; a build that fails leaves the CPU reader and says so (pictures still work, on the CPU).""" + if vision == "gpu" and not (shutil.which("hipconfig") or os.environ.get("ROCM_PATH")): + root, dirs = rocm_root(archs) # the engine was built earlier: set the same environment again + os.environ.update({"HIP_PLATFORM": "amd", "HIP_COMPILER": "clang", "HIP_RUNTIME": "rocclr", "ROCM_PATH": str(root), + "HIP_PATH": str(root)}) + os.environ["LD_LIBRARY_PATH"] = os.pathsep.join(dirs + [os.environ.get("LD_LIBRARY_PATH", "")]).rstrip(os.pathsep) + os.environ["PATH"] = os.pathsep.join([str(root / "bin"), str(root / "llvm" / "bin"), os.environ.get("PATH", "")]) + build_vision_cpu(eng, stamp, meta, llama, vsrc) + meta = json.loads(stamp.read_text(encoding="utf-8")) + if vision != "gpu": + return eng + root, dirs = rocm_root(archs) + libs = [str(Path(d).parent) for d in dirs[1:]] + bitcode = next((p for p in (root / "lib" / "llvm" / "amdgcn" / "bitcode", root / "amdgcn" / "bitcode") if p.is_dir()), + root / "amdgcn" / "bitcode") + say(" Compiling the picture reader for your AMD GPU (a few minutes, once) ...") + try: + cmake_build(ROOT / "tools" / "vision", ROOT / "build-vision-hip", "strata-vision", + [f"-DLLAMA_DIR={llama}", "-DSTRATA_VISION_HIP=ON", "-DSTRATA_VISION_HIP_ARCHS=" + ";".join(archs), + "-DSTRATA_PORTABLE=OFF", f"-DCMAKE_HIP_COMPILER={root / 'llvm' / 'bin' / 'clang++'}", + f"-DCMAKE_HIP_COMPILER_ROCM_ROOT={root}", "-DCMAKE_PREFIX_PATH=" + ";".join([str(root), *libs]), + f"-DCMAKE_HIP_FLAGS=--rocm-path={root} --rocm-device-lib-path={bitcode}"], None, "") + shutil.copy2(ROOT / "build-vision-hip" / "bin" / HVEXE, eng / HVEXE) + except SystemExit: + raise + except Exception as e: # noqa: BLE001 - the CPU reader is there; pictures work without the GPU one + warn(f"the GPU picture reader did not compile ({e}): pictures are read on the CPU") + return eng + stamp.write_text(json.dumps({**meta, "vision": "gpu", "vision_archs": archs, "vision_gpu": HVEXE, "vision_cpu": VEXE}, indent=1)) + ok(f"picture reader (GPU): {eng / HVEXE}, (CPU fallback): {eng / VEXE}") + return eng def build_vision_cpu(eng: Path, stamp: Path, meta: dict, llama, vsrc) -> Path: @@ -4841,7 +4900,7 @@ SETUP_ENV = frozenset({"STRATA_HIPBLASLT_TUNING", "STRATA_ROCBLAS_TUNING", "STRA # user's own (STRATA_ROUTE_TAIL_SKIP=0 to turn the tail skip off, STRATA_MMQ_KQ=1 ...): a setup run again keeps them there # (0.1.44 dropped them with the rest of SETUP_ENV). SETUP_ENV_UNSLOTH = frozenset({"STRATA_MMQ_KQ", "STRATA_HC_Q8", "STRATA_ROUTE_TAIL_SKIP"}) -SETUP_VISION = frozenset({"exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) +SETUP_VISION = frozenset({"exe", "cpu_exe", "mmproj", "model", "gpu", "max_tokens", "threads"}) def carry_over(old: dict, cfg: dict) -> list[str]: @@ -6029,22 +6088,16 @@ def own_path_vision(a, fam: dict, gpu: dict, hip: bool) -> str: say() say(f" Images: {fam['title']} can also read pictures (screenshots, photos, scanned pages). This adds a " f"{fam['sha256'][fam['mmproj']][0] / 1e9:.1f} GB download" + ( - "; the encoder runs on the CPU (no VRAM), a few seconds per picture." if hip else + "; the encoder runs on the GPU when the engine has the AMD one (about 1 GB of VRAM), else on the CPU." if hip else " and the image encoder runs on the GPU (~1.4 GB of VRAM kept free, 0.1-0.5 s per picture)." if big else "; the encoder runs on the CPU (a few seconds per picture), because the GPU encoder would take ~1.4 GB " "of VRAM from the experts on this card.")) - default = "n" if (hip and WIN) else "y" if (big or hip) else "n" + default = "y" if (big or hip) else "n" if ask("Do you want images?", ["y", "n"], default, a.yes) != "y": return "none" - asked = "cpu" if (hip or not big) else "gpu" + asked = "gpu" if hip else "cpu" if not big else "gpu" if hip: - if asked == "gpu": - say(" The AMD backend has no GPU image encoder yet: the encoder runs on the CPU.") - if WIN: - warn("images on the CPU with an AMD card are Linux-only for now (the ready-made Windows AMD engine has no " - "image encoder): images off") - return "none" - return "cpu" + return hip_vision(asked) # settled against the engine's readers in hip_reader() (GPU reader, else CPU) if asked == "yes": asked = "gpu" if big else "cpu" if asked == "gpu" and not big and vram > 0: @@ -6207,7 +6260,10 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte step(4, "the Strata engine") llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) - if vision != "none" and not (eng / VEXE).exists(): + reader = None + if hip and vision != "none": + vision, reader = hip_reader(eng, vision, gpu) + elif vision != "none" and not (eng / VEXE).exists(): warn("this engine has no image encoder: images off (run setup again with --build to compile it)") vision = "none" if fam["arch"] not in engine_families(eng): @@ -6276,6 +6332,9 @@ def install_own_path(a, family, gpu, hip, amd, cuda_tk, multi, port, ram, adopte cfg["args"].append("--vision") cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), "model": str(gguf), "gpu": vision == "gpu", "max_tokens": vt} # the text model, opened vocab-only + if reader is not None: # AMD: the HIP reader with the CPU reader behind it, or the CPU reader + from strata_control import vision_reader as VR + cfg["vision"] = VR.vision_section(reader, cfg["vision"]) if vision == "cpu": cfg["vision"]["threads"] = vision_threads() elif getattr(a, "vision_tokens", None) is not None: @@ -7261,6 +7320,9 @@ def main() -> int: # ---- 4. the engine step(4, "the Strata engine") llama, eng, meta, lib_dirs, gpu, vision = engine_step(a, gpu, hip, amd, cuda_tk, vision) + reader = None + if hip and vision != "none": # AMD: the engine folder's reader (GPU, else CPU), settled now the engine is known + vision, reader = hip_reader(eng, vision, gpu) if (ready or family == "gyro") and meta.get("source") != "local" and \ tuple(int(x) for x in str(meta.get("version", "0")).split(".")[:4] if x.isdigit()) < MODELS[model]["engine"]: # a ready-made engine from before NVFP4 / Gyro cannot read these experts: one compiled from this source can @@ -7668,6 +7730,9 @@ def main() -> int: cfg["vision"] = {"exe": str(eng / VEXE), "mmproj": str(mmproj), # the text model, opened vocab-only: "model": str(ready_paths(model, models_dir)["dense"] if ready else shards[0]), "gpu": vision == "gpu", "max_tokens": vt} + if reader is not None: # AMD: the HIP reader with the CPU reader behind it, or the CPU reader + from strata_control import vision_reader as VR + cfg["vision"] = VR.vision_section(reader, cfg["vision"]) if vision == "cpu": cfg["vision"]["threads"] = vision_threads() elif a.vision_tokens is not None: diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 6c0253e4..e8a75ecd 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -429,13 +429,37 @@ class CalibrationKey(unittest.TestCase): self.assertIsNone(setup.setup_calibration(cfg, hip=True)) # Windows HIP: defaults for now -class WindowsHipVision(unittest.TestCase): - def test_no_cpu_encoder_on_windows(self): - with mock.patch.object(setup, "WIN", True), mock.patch.object(setup, "warn", lambda *a: None): - self.assertEqual(setup.hip_vision("cpu"), "none") - self.assertEqual(setup.hip_vision("yes"), "none") - with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "warn", lambda *a: None): - self.assertEqual(setup.hip_vision("cpu"), "cpu") +class HipVisionWish(unittest.TestCase): + """AMD pictures are on by default, on Linux and Windows: the wish is "gpu" (hip_reader() settles it against the readers the + engine folder carries: the HIP one, else the CPU one), "cpu" when asked for, "none" for no.""" + + def test_wish(self): + for win in (True, False): + with mock.patch.object(setup, "WIN", win): + self.assertEqual(setup.hip_vision(None), "gpu") + self.assertEqual(setup.hip_vision("yes"), "gpu") + self.assertEqual(setup.hip_vision("gpu"), "gpu") + self.assertEqual(setup.hip_vision("cpu"), "cpu") + self.assertEqual(setup.hip_vision("no"), "none") + self.assertEqual(setup.hip_vision("none"), "none") + + def test_reader_settled_against_the_engine_folder(self): + for win, suffix in ((False, ""), (True, ".exe")): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "WIN", win), mock.patch.object(setup, "warn", lambda *a: None): + eng = Path(d) + (eng / ("strata-vision" + suffix)).write_bytes(b"x") + self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1201"})[0], "cpu") # no HIP reader: the CPU one + (eng / ("strata-vision-hip" + suffix)).write_bytes(b"x") + mode, r = setup.hip_reader(eng, "gpu", {"arch": "gfx1201"}) + self.assertEqual((mode, r.exe.name, r.cpu_exe.name), + ("gpu", "strata-vision-hip" + suffix, "strata-vision" + suffix)) + (eng / "BUILD.json").write_text('{"vision_archs": ["gfx1100"]}') + self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1201"})[0], "cpu") # the card is not in its build + self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1100"})[0], "gpu") + self.assertEqual(setup.hip_reader(eng, "cpu", {"arch": "gfx1100"})[0], "cpu") + (eng / ("strata-vision" + suffix)).unlink() + (eng / ("strata-vision-hip" + suffix)).unlink() + self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1100"})[0], "none") class HipRuntimeBesideExe(unittest.TestCase): diff --git a/tools/test_setup_choices.py b/tools/test_setup_choices.py index 2e7540cf..d2d43159 100644 --- a/tools/test_setup_choices.py +++ b/tools/test_setup_choices.py @@ -318,15 +318,13 @@ class ExperimentalSm60(unittest.TestCase): class HipVision(unittest.TestCase): """#304: --vision cpu with --backend hip builds the CPU image encoder beside the HIP engine.""" - @mock.patch.object(setup, "WIN", False) # Linux: compiled here (Windows has no AMD image encoder yet) + @mock.patch.object(setup, "WIN", False) def test_the_choice(self): self.assertEqual(quiet(setup.hip_vision, "cpu"), ("cpu", "")) - for asked in (None, "no", "none"): + for asked in ("no", "none"): self.assertEqual(quiet(setup.hip_vision, asked), ("none", "")) - for asked in ("yes", "gpu"): - got, out = quiet(setup.hip_vision, asked) - self.assertEqual(got, "none") - self.assertIn("--vision cpu", out) + for asked in (None, "yes", "gpu"): # pictures are on by default; the engine folder's readers settle gpu vs cpu + self.assertEqual(quiet(setup.hip_vision, asked), ("gpu", "")) def build(self, meta, vision, vexe=False): """build_engine_hip with an engine that is already built: only the encoder can be missing.""" diff --git a/tools/test_setup_qwen36.py b/tools/test_setup_qwen36.py index 3106e616..69bdd726 100644 --- a/tools/test_setup_qwen36.py +++ b/tools/test_setup_qwen36.py @@ -88,6 +88,7 @@ class InstallOwnPath(unittest.TestCase): self.root = Path(self.tmp.name) self.calls = [] self.families = {"qwen4exp", "qwen35moe"} + self.hip_reader = True eng = self.root / "engine" self.cfg = {} @@ -96,6 +97,8 @@ class InstallOwnPath(unittest.TestCase): if vision != "none": # the image encoder beside the engine eng.mkdir(parents=True, exist_ok=True) (eng / setup.VEXE).write_text("x") + if hip and self.hip_reader: # an AMD engine package carries the GPU reader too + (eng / setup.HVEXE).write_text("x") return self.root / "llama", eng, {"version": "0.1.44"}, ["/libs"], gpu, vision def write_cfg(path, cfg, source=None): @@ -219,16 +222,36 @@ class InstallOwnPath(unittest.TestCase): self.assertTrue(self.cfg["vision"]["gpu"]) self.assertIn("kept as you chose", out) - def test_amd_reads_pictures_on_the_cpu(self): - with mock.patch.object(setup, "WIN", False): + def test_amd_reads_pictures_on_the_gpu_with_the_cpu_reader_behind_it(self): + for win, suffix in ((False, ""), (True, ".exe")): + with mock.patch.object(setup, "WIN", win), mock.patch.object(setup, "VEXE", "strata-vision" + suffix), mock.patch.object(setup, "HVEXE", "strata-vision-hip" + suffix): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="yes") + self.assertEqual(rc, 0, out) + v = self.cfg["vision"] + self.assertTrue(v["gpu"]) + self.assertEqual(Path(v["exe"]).name, "strata-vision-hip" + suffix) + self.assertEqual(Path(v["cpu_exe"]).name, "strata-vision" + suffix) + self.assertIn("--vision", self.cfg["args"]) + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="cpu") + v = self.cfg["vision"] + self.assertFalse(v["gpu"]) + self.assertEqual(Path(v["exe"]).name, "strata-vision" + suffix) + self.assertNotIn("cpu_exe", v) + + def test_amd_engine_without_the_gpu_reader_reads_pictures_on_the_cpu(self): + self.hip_reader = False + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "VEXE", "strata-vision"): rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="yes") self.assertEqual(rc, 0, out) self.assertFalse(self.cfg["vision"]["gpu"]) + self.assertNotIn("cpu_exe", self.cfg["vision"]) self.assertIn("--vision", self.cfg["args"]) - with mock.patch.object(setup, "WIN", True): - rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True, vision="cpu") - self.assertNotIn("vision", self.cfg) - self.assertIn("Linux-only", out) + + def test_amd_pictures_are_on_when_nothing_is_asked(self): + with mock.patch.object(setup, "WIN", False), mock.patch.object(setup, "VEXE", "strata-vision"), mock.patch.object(setup, "HVEXE", "strata-vision-hip"): + rc, out = self.install(model="UD-Q4_K_XL", vram=32.0, hip=True) + self.assertEqual(rc, 0, out) + self.assertTrue(self.cfg["vision"]["gpu"]) def test_parallel_is_opt_in_and_recommended_where_the_experts_fit(self): fam = setup.OWN_PATH_FAMILIES["qwen36"] From 536c7f019e5de0571baad9f9a1032bc82e20ccf6 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:44:45 +0200 Subject: [PATCH 12/26] Windows HIP zip: build_windows.bat builds the two picture readers and package_windows.py ships them --- tools/hip/build_windows.bat | 29 +++++++++++++++++++++++++++-- tools/hip/package_windows.py | 14 +++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/tools/hip/build_windows.bat b/tools/hip/build_windows.bat index 08eb06c2..d0eed669 100644 --- a/tools/hip/build_windows.bat +++ b/tools/hip/build_windows.bat @@ -16,6 +16,7 @@ rem gfx1031 = RX 6700 XT / 6800M, #915 #1078; drop it fro rem STRATA_ROCM_VERSION 10.2.0a20260930 STRATA_ROCM_INDEX https://nightly.repo.amd.com/rocm/whl-next/ rem ROCM_VENV \.rocm-win BUILD_DIR \build-hip-win DIST_DIR \dist rem STRATA_GGML_DIR a llama.cpp checkout at the pinned commit (default: CMake fetches it) +rem STRATA_NO_VISION 1 = skip the two picture readers (strata-vision.exe for the CPU, strata-vision-hip.exe for the GPU) setlocal EnableDelayedExpansion for %%I in ("%~dp0..\..") do set "SRC=%%~fI" if not defined STRATA_HIP_ARCHS set "STRATA_HIP_ARCHS=gfx1100;gfx1101;gfx1102;gfx1200;gfx1201;gfx1030;gfx1031;gfx1151" @@ -79,9 +80,33 @@ if "%TESTS%"=="ON" ( cmake --build "%BUILD_DIR%" --target strata strata-device || exit /b 1 ) -rem ---- 4. the zip: the two programs, the ROCm DLLs they load (+ rocBLAS/hipBLASLt kernels for these archs), licenses +rem ---- 3b. the picture readers (tools/vision, the same llama.cpp as the engine): strata-vision.exe on the CPU (MSVC, portable: the +rem fallback that starts on any PC) and strata-vision-hip.exe on the GPU (ROCm's clang, ggml-hip, the archs above) +set "VISION_ARGS=" +if not "%STRATA_NO_VISION%"=="1" ( + set "LLAMA=%STRATA_GGML_DIR%" + if not defined LLAMA set "LLAMA=%BUILD_DIR%\_deps\strata_llamacpp-src" + set "LLAMA=!LLAMA:\=/!" + if not exist "!LLAMA!/tools/mtmd" (echo llama.cpp with tools/mtmd not found in !LLAMA! - set STRATA_GGML_DIR & exit /b 1) + if not exist "%SRC%\build-vision-cpu-win\build.ninja" ( + cmake -G Ninja -S "%SRC%\tools\vision" -B "%SRC%\build-vision-cpu-win" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="!LLAMA!" ^ + -DSTRATA_VISION_CUDA=OFF -DSTRATA_PORTABLE=ON -DCMAKE_C_COMPILER=cl -DCMAKE_CXX_COMPILER=cl || exit /b 1 + ) + cmake --build "%SRC%\build-vision-cpu-win" --target strata-vision || exit /b 1 + if not exist "%SRC%\build-vision-hip-win\build.ninja" ( + cmake -G Ninja -S "%SRC%\tools\vision" -B "%SRC%\build-vision-hip-win" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="!LLAMA!" ^ + -DSTRATA_VISION_HIP=ON "-DSTRATA_VISION_HIP_ARCHS=%STRATA_HIP_ARCHS%" -DSTRATA_PORTABLE=ON ^ + "-DCMAKE_C_COMPILER=%ROCM_F%/lib/llvm/bin/clang.exe" "-DCMAKE_CXX_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" ^ + "-DCMAKE_HIP_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" "-DCMAKE_HIP_COMPILER_ROCM_ROOT=%ROCM_F%" ^ + "-DCMAKE_PREFIX_PATH=%ROCM_F%" "-DCMAKE_HIP_FLAGS=--rocm-path=%ROCM_F% --rocm-device-lib-path=%BITCODE%" || exit /b 1 + ) + cmake --build "%SRC%\build-vision-hip-win" --target strata-vision || exit /b 1 + set "VISION_ARGS=--vision-cpu %SRC%\build-vision-cpu-win\bin\strata-vision.exe --vision-hip %SRC%\build-vision-hip-win\bin\strata-vision-hip.exe" +) + +rem ---- 4. the zip: the programs, the ROCm DLLs they load (+ rocBLAS/hipBLASLt kernels for these archs), licenses "%ROCM_VENV%\Scripts\python.exe" "%SRC%\tools\hip\package_windows.py" --build "%BUILD_DIR%" --rocm "%ROCM%" ^ - --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" || exit /b 1 + --archs "%STRATA_HIP_ARCHS%" --rocm-version "%STRATA_ROCM_VERSION%" --out "%DIST_DIR%" !VISION_ARGS! || exit /b 1 echo. echo Done: %DIST_DIR%\strata-windows-x64-hip.zip endlocal diff --git a/tools/hip/package_windows.py b/tools/hip/package_windows.py index 4db84d7f..82dc26cc 100644 --- a/tools/hip/package_windows.py +++ b/tools/hip/package_windows.py @@ -7,6 +7,9 @@ tools/hip/build_windows.bat runs it after the build. The zip holds: strata.exe, strata-device.exe, BUILD.json (backend "hip", the archs, the ROCm and hipBLASLt versions) + strata-vision.exe, strata-vision-hip.exe the picture readers when --vision-cpu / --vision-hip are given: the CPU reader + (the fallback; starts on any PC) and the GPU reader (tools/vision, + STRATA_VISION_HIP; imports the same ROCm DLLs as strata.exe) amdhip64_7.dll, amd_comgr.dll + what they import the HIP runtime beside the exes too (#468 #461: before System32) rocm/bin/*.dll the ROCm DLLs the two programs load (their import tables, followed through the ROCm DLLs, + amd_comgr.dll, which the HIP runtime loads @@ -73,6 +76,8 @@ def main() -> int: ap.add_argument("--archs", required=True, help="the archs the engine was compiled for, ';'-separated") ap.add_argument("--rocm-version", required=True) ap.add_argument("--out", required=True, type=Path) + ap.add_argument("--vision-cpu", type=Path, help="strata-vision.exe built for the CPU (tools/vision, STRATA_PORTABLE=ON)") + ap.add_argument("--vision-hip", type=Path, help="strata-vision-hip.exe built for the same archs (STRATA_VISION_HIP=ON)") a = ap.parse_args() archs = [x for x in re.split(r"[;, ]+", a.archs) if x] rbin = a.rocm / "bin" @@ -83,10 +88,13 @@ def main() -> int: for p in PROGRAMS: shutil.copy2(a.build / p, stage / p) + readers = [(src, src.name) for src in (a.vision_cpu, a.vision_hip) if src is not None] + for src, name in readers: + shutil.copy2(src, stage / name) # the ROCm DLLs: the programs' imports, followed through the ROCm DLLs themselves rocm_dlls = {p.name.lower(): p for p in rbin.glob("*.dll")} - need, todo, crt = [], [stage / p for p in PROGRAMS] + [rbin / d for d in DYNAMIC], set() + need, todo, crt = [], [stage / p for p in PROGRAMS] + [stage / n for _, n in readers] + [rbin / d for d in DYNAMIC], set() while todo: f = todo.pop() for name in imports(objdump, f): @@ -157,6 +165,10 @@ def main() -> int: meta = {"source": "prebuilt", "backend": "hip", "platform": "windows-x64", "version": version, "archs": archs, "rocm": a.rocm_version, "hipblaslt_version": hlv[0] * 100000 + hlv[1] * 100 + hlv[2], "vision": "none", "lib_dirs": ["rocm/bin"]} + if a.vision_cpu is not None: + meta.update({"vision": "cpu", "vision_cpu": a.vision_cpu.name}) + if a.vision_hip is not None: + meta.update({"vision": "gpu", "vision_gpu": a.vision_hip.name, "vision_archs": archs}) (stage / "BUILD.json").write_text(json.dumps(meta, indent=1), encoding="utf-8") z = a.out / ASSET From 979da9d2bca48ba801ecab95361e8ff6d99fe002 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:44:49 +0200 Subject: [PATCH 13/26] Terminal launch list: Qwen3.6 (own engine path) stays out of Flash-Next's rows --- strata_cli/launch/catalog.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/strata_cli/launch/catalog.py b/strata_cli/launch/catalog.py index ebfe0fcb..2402edc9 100644 --- a/strata_cli/launch/catalog.py +++ b/strata_cli/launch/catalog.py @@ -272,7 +272,10 @@ class Catalog: vram = comp.main_vram_gb rec = self.recommendation(hw) out: list[ModelRow] = [] + own = self.strata.own_families() # Qwen3.6 is listed for the app; the Terminal's launch list is Flash-Next's for fam in self.strata.model_table(hw): + if fam["family"] in own: + continue for size in fam["sizes"]: f = fit_on(size, hw.get("ram_gb"), vram) cat, words = verdict(size.get("on_this_pc")) From 55ca7b955a37167b77a38bea3840be62bb6a4783 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:51:10 +0200 Subject: [PATCH 14/26] launch: the Pictures screen says the AMD picture reader runs on the graphics card; build_hip_linux.sh collects libraries from the build outputs --- packaging/build_hip_linux.sh | 10 +++++----- strata_cli/launch/screens.py | 5 ++++- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packaging/build_hip_linux.sh b/packaging/build_hip_linux.sh index e833bc69..c78626ca 100644 --- a/packaging/build_hip_linux.sh +++ b/packaging/build_hip_linux.sh @@ -67,19 +67,19 @@ st "gpu reader built rc=$?" [ -x "$OUT/bh/bin/strata-vision-hip" ] || { st "ABORT no strata-vision-hip"; tail -20 "$OUT/build-vision-hip.log" >> "$S"; exit 1; } [ -n "${VISION_ONLY:-}" ] && { st "VISION-DONE"; exit 0; } STAGE=$OUT/stage; rm -rf "$STAGE"; mkdir -p "$STAGE" -cp "$OUT/b/strata" "$OUT/bv/bin/strata-vision" "$OUT/bh/bin/strata-vision-hip" "$STAGE/" ARCHJSON=$(for a in $ARCHLIST; do printf '"%s", ' "$a"; done | sed 's/, $//') cat > "$STAGE/BUILD.json" <> "$OUT/collect.log" 2>&1 - st "collected for $b rc=$?" + st "collected for $(basename "$b") rc=$?" done +cp "$OUT/b/strata" "$OUT/bv/bin/strata-vision" "$OUT/bh/bin/strata-vision-hip" "$STAGE/" for f in "$STAGE"/*.so "$STAGE"/*.so.*; do [ -f "$f" ] && [ ! -L "$f" ] && patchelf --set-rpath '$ORIGIN' "$f"; done for f in "$STAGE/strata" "$STAGE/strata-vision" "$STAGE/strata-vision-hip"; do st "RUNPATH $(basename "$f"): $(readelf -d "$f" | grep -E 'RPATH|RUNPATH' | cut -d'[' -f2 | tr -d ']' | paste -sd' ')" diff --git a/strata_cli/launch/screens.py b/strata_cli/launch/screens.py index f090b684..7b76dba7 100644 --- a/strata_cli/launch/screens.py +++ b/strata_cli/launch/screens.py @@ -820,7 +820,10 @@ class PicturesScreen(Base): def explain(self) -> Text: vram = self.ctx.computer.main_vram_gb - extra = ("a 0.9 GB download. On a card under 24 GB the picture reader runs on the CPU (a few seconds per picture, nothing " + amd = any(str(g.get("vendor")) == "amd" for g in self.ctx.computer.usable_gpus) + extra = ("a 0.9 GB download. On your AMD card the picture reader runs on the graphics card (about 1 GB of its memory, under a second " + "per picture) and starts on the processor by itself if it cannot." if amd and self.reader() != "missing" else + "a 0.9 GB download. On a card under 24 GB the picture reader runs on the CPU (a few seconds per picture, nothing " "taken from the graphics card). On a bigger card it runs on the GPU and keeps about 1.4 GB free, costing a few % of text speed." if vram < 24 else "a 0.9 GB download, and about 1.4 GB of graphics memory kept free for the picture reader (text is a few % slower).") if not self.supported: From b2e3008bfb4b64165ec18eeb5f99f7a4d3073d0a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:51:33 +0200 Subject: [PATCH 15/26] build_hip_linux.sh: kernel data collected once --- packaging/build_hip_linux.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packaging/build_hip_linux.sh b/packaging/build_hip_linux.sh index c78626ca..b0c244b2 100644 --- a/packaging/build_hip_linux.sh +++ b/packaging/build_hip_linux.sh @@ -72,12 +72,13 @@ cat > "$STAGE/BUILD.json" <> "$OUT/collect.log" 2>&1 + "${DATA[@]}" >> "$OUT/collect.log" 2>&1 st "collected for $(basename "$b") rc=$?" + DATA=() # the kernel data once done cp "$OUT/b/strata" "$OUT/bv/bin/strata-vision" "$OUT/bh/bin/strata-vision-hip" "$STAGE/" for f in "$STAGE"/*.so "$STAGE"/*.so.*; do [ -f "$f" ] && [ ! -L "$f" ] && patchelf --set-rpath '$ORIGIN' "$f"; done From b31c13875e3492c47cd7fe6f2018c46303b438ba Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 21:55:51 +0200 Subject: [PATCH 16/26] AMD picture reader: the no-GPU/arch refusal only in the HIP program; the app's CPU choice starts the CPU reader program --- apps/host/server/native-vision.mjs | 1 + apps/host/tests/native-onboarding.test.mjs | 4 ++++ tools/vision/strata_vision.cpp | 18 ++++++------------ 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/apps/host/server/native-vision.mjs b/apps/host/server/native-vision.mjs index 922ddfd2..0394ea02 100644 --- a/apps/host/server/native-vision.mjs +++ b/apps/host/server/native-vision.mjs @@ -5,5 +5,6 @@ export function runtimeVision(config,requested){ if(mode==='no')return undefined; if(mode===undefined)return config.vision; if(!config.vision)throw new Error('Prepare this model’s vision files before enabling picture reading.'); + if(mode==='cpu'&&config.vision.cpu_exe){const {cpu_exe,...rest}=config.vision;return {...rest,exe:cpu_exe,gpu:false};} // AMD: the CPU reader program, not the HIP one with the GPU hidden return {...config.vision,...(mode==='cpu'?{gpu:false}:mode==='gpu'?{gpu:true}:{})}; } diff --git a/apps/host/tests/native-onboarding.test.mjs b/apps/host/tests/native-onboarding.test.mjs index 1357756a..5db0a676 100644 --- a/apps/host/tests/native-onboarding.test.mjs +++ b/apps/host/tests/native-onboarding.test.mjs @@ -145,6 +145,10 @@ test('runtime vision checks prepared files, validates mode, and leaves the sourc assert.equal(runtimeVision(config,'cpu').gpu,false); assert.equal(runtimeVision(config,'yes').mmproj,config.vision.mmproj); assert.deepEqual(config,before); + const amd={vision:{exe:'/e/strata-vision-hip',cpu_exe:'/e/strata-vision',mmproj:'/m.gguf',gpu:true}}; + assert.deepEqual(runtimeVision(amd,'cpu'),{exe:'/e/strata-vision',mmproj:'/m.gguf',gpu:false}); + assert.equal(runtimeVision(amd,'gpu').exe,'/e/strata-vision-hip');assert.equal(runtimeVision(amd,'gpu').cpu_exe,'/e/strata-vision'); + assert.equal(runtimeVision(amd,'yes').gpu,true); assert.throws(()=>runtimeVision({},'yes'),/Prepare/); assert.throws(()=>runtimeVision(config,'invalid'),/picture reading/); }); diff --git a/tools/vision/strata_vision.cpp b/tools/vision/strata_vision.cpp index 293e0198..85979b66 100644 --- a/tools/vision/strata_vision.cpp +++ b/tools/vision/strata_vision.cpp @@ -117,27 +117,21 @@ int main(int argc, char** argv) { llama_log_set(quiet_log, nullptr); mtmd_helper_log_set(quiet_log, nullptr); llama_backend_init(); +#ifdef STRATA_VISION_HIP if (gpu) { - // Starting the backends prints the GPU line; with --gpu and no GPU, mtmd would quietly use the CPU, and a card - // the HIP build has no code for would abort at its first kernel. Both end here with a line the server reads - // (it then starts the CPU reader). + // The AMD GPU reader: starting the backends prints the GPU line. With --gpu and no GPU, mtmd would quietly use the CPU + // (a second, slower CPU reader inside the HIP program), and a card the build has no code for would abort at its first + // kernel. Both end here with a line the server reads: it then starts the CPU reader (serve/server.py, Vision._start). bool have_gpu = false; for (size_t i = 0; i < ggml_backend_dev_count(); ++i) { const auto type = ggml_backend_dev_type(ggml_backend_dev_get(i)); have_gpu = have_gpu || type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU; } if (!have_gpu) { - std::printf("ERR this picture reader found no GPU (it was built for: %s)\n", -#ifdef STRATA_VISION_HIP - STRATA_VISION_HIP_ARCHS -#else - "none" -#endif - ); + std::printf("ERR this picture reader found no GPU (it was built for: %s)\n", STRATA_VISION_HIP_ARCHS); std::fflush(stdout); return 3; } -#ifdef STRATA_VISION_HIP const char* check = std::getenv("STRATA_VISION_ARCH_CHECK"); if (!g_gfx.empty() && (check == nullptr || std::atoi(check) != 0) && !strata_arch_listed(STRATA_VISION_HIP_ARCHS, g_gfx.front())) { @@ -146,8 +140,8 @@ int main(int argc, char** argv) { std::fflush(stdout); return 3; } -#endif } +#endif const auto load_t0 = std::chrono::steady_clock::now(); #if !defined(_WIN32) && !defined(__APPLE__) // macOS has no posix_fadvise From c59505e6389105f21dcf62a2bab300c9a88a679b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:02:17 +0200 Subject: [PATCH 17/26] build_windows.bat: STRATA_ROCM_KEEP uses the ROCm venv as it is --- tools/hip/build_windows.bat | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/hip/build_windows.bat b/tools/hip/build_windows.bat index d0eed669..0d166031 100644 --- a/tools/hip/build_windows.bat +++ b/tools/hip/build_windows.bat @@ -16,6 +16,7 @@ rem gfx1031 = RX 6700 XT / 6800M, #915 #1078; drop it fro rem STRATA_ROCM_VERSION 10.2.0a20260930 STRATA_ROCM_INDEX https://nightly.repo.amd.com/rocm/whl-next/ rem ROCM_VENV \.rocm-win BUILD_DIR \build-hip-win DIST_DIR \dist rem STRATA_GGML_DIR a llama.cpp checkout at the pinned commit (default: CMake fetches it) +rem STRATA_ROCM_KEEP 1 = use the ROCM_VENV as it is (no pip install, even when its archs differ from STRATA_HIP_ARCHS) rem STRATA_NO_VISION 1 = skip the two picture readers (strata-vision.exe for the CPU, strata-vision-hip.exe for the GPU) setlocal EnableDelayedExpansion for %%I in ("%~dp0..\..") do set "SRC=%%~fI" @@ -40,7 +41,7 @@ set "STAMP=%ROCM_VENV%\strata-rocm.txt" set "WANT=%STRATA_ROCM_VERSION% %EXTRAS%" set "HAVE=" if exist "%STAMP%" set /p HAVE=<"%STAMP%" -if not "!HAVE!"=="!WANT!" ( +if not "!HAVE!"=="!WANT!" if not "%STRATA_ROCM_KEEP%"=="1" ( echo Installing ROCm %STRATA_ROCM_VERSION% [%EXTRAS%] into %ROCM_VENV% ... "%ROCM_VENV%\Scripts\python.exe" -m pip install --disable-pip-version-check --index-url "%STRATA_ROCM_INDEX%" "rocm[%EXTRAS%]==%STRATA_ROCM_VERSION%" || exit /b 1 "%ROCM_VENV%\Scripts\rocm-sdk.exe" init || exit /b 1 From 97cb031bf7a53fbd57a6f748c7ca19feb136f948 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:04:25 +0200 Subject: [PATCH 18/26] docs: AMD pictures run on the card by default, with the CPU reader as the automatic fallback --- docs/AMD_HIP.md | 12 ++++++++---- docs/INSTALL.md | 3 +-- docs/TROUBLESHOOTING.md | 3 ++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md index c4fb1943..9402ff22 100644 --- a/docs/AMD_HIP.md +++ b/docs/AMD_HIP.md @@ -51,7 +51,12 @@ the kernel's amdgpu driver (no ROCm install needed): architectures above; the engine is compiled for each of them (cards of two families, e.g. gfx1100 + gfx1201, need a system ROCm 7: AMD's wheels hold one family). A split pays only when no single card holds the model's experts (see RDNA4 below). -- **Limits for now:** images only through the CPU encoder (`--vision cpu`, 0.1.32). Setup does not offer the tuning +- **Pictures:** on by default. The engine package carries two picture readers: `strata-vision-hip`, which reads a picture on the + card (llama.cpp's HIP backend; about 1.4 GiB of VRAM, measured on an R9700: 0.06 s for a 260-token picture and 0.4 s for 972 + tokens, against 3.1 s and 14 s on the CPU), and `strata-vision`, the CPU reader. If the GPU reader cannot start (the card is + not one it was built for, the HIP runtime does not load, the card is busy) the server starts the CPU reader by itself and + prints one line; nothing is asked. `--vision cpu` picks the CPU reader on purpose. +- **Limits for now:** Setup does not offer the tuning (calibration) on AMD yet: its controls are being checked on HIP one at a time (#566). Since 0.1.39 a tuning run by hand (`./setup.sh --calibrate`) is saved for the AMD card it ran on and reused when setup runs again. The Monitor shows the card's load, VRAM, temperature and power from Linux sysfs (0.1.32). @@ -84,8 +89,7 @@ On a PC with no NVIDIA card Strata can use, the AMD card is chosen by itself; wi the PATH): if the HIP runtime does not see the card, setup stops there and points to the driver. It also gives the card's HIP number: with an integrated Radeon that is device 1, not 0 (#325). From then on setup lists the AMD cards as HIP numbers them, so `--gpu N` and the config's `"gpu"` are HIP numbers. -- **Differences from Windows-on-NVIDIA and Linux-on-AMD:** no images yet (the CPU image encoder is Linux-only for - now), one card per model (`--gpus` is Linux-only for now), no calibration. +- **Differences from Windows-on-NVIDIA and Linux-on-AMD:** one card per model (`--gpus` is Linux-only for now), no calibration. - Two Windows-only engine details (#247, #325): hipBLAS can return success and still leave `hipErrorInvalidValue` set after some BF16/FP16 GEMMs (seen on gfx1201); the engine clears that one stale error after a GEMM that succeeded, on Windows only. `hipHostGetDevicePointer` returns the host pointer itself on Windows: kernels read @@ -260,7 +264,7 @@ sizes itself automatically and leaves 1 GiB of VRAM headroom. GPU memory to system RAM (GTT), the OOM killer then ends KWin/plasmashell or `systemd-oomd` ends apps, or the compositor fails with "Failed to pin framebuffer with error -12". -The installer supports this backend (see "Install with setup" above). Images run through the CPU encoder for now (`--vision cpu`). +The installer supports this backend (see "Install with setup" above). Pictures are read on the card (`strata-vision-hip`) when the engine has it, else on the CPU (`strata-vision`). Setup installs one AMD card, or several with `--gpus` (the engine's layer split; see RDNA4 below). **Opt-in switches for RDNA2 prompts and hangs (0.1.40, off by default):** `STRATA_DENSE_MMQ=1` (#820, HIP) runs the diff --git a/docs/INSTALL.md b/docs/INSTALL.md index eb8a1ee5..c9c6c888 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -80,8 +80,7 @@ On Linux setup uses a system ROCm 7 when there is one, or installs ROCm into `.v sudo), and compiles the engine on your PC for the card (10-20 minutes, once; it needs a C++ compiler and git: `sudo apt install build-essential git`). Several AMD cards share the model with `--gpus`, as on NVIDIA. -What differs from NVIDIA for now: pictures are read by the image encoder on the CPU (`--vision cpu`, about 3 s per -picture at the default 300 image tokens on 8 cores), `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the +What differs from NVIDIA for now: `--calibrate` is NVIDIA-only, and Unsloth's 4-bit model needs an NVIDIA card. Measurements per card, the build by hand and the tuning tables: [AMD_HIP.md](AMD_HIP.md). ## Two or three cards diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 706f355d..799ad8e5 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -133,7 +133,8 @@ setup warns when it finds 13.2.0 or 13.2.1 for such a card, and takes an older 1 **Pictures are refused, or slow.** "this server was started without the vision encoder": the model was set up for text only - run setup again with `--vision gpu` (or `--vision cpu`). Pictures that take several seconds (about 3 s at 300 image tokens on 8 cores, more with more tokens) are read by the encoder on the CPU; `--vision gpu` -(NVIDIA, ~1.4 GB of VRAM) makes it 0.1-0.5 s. +(NVIDIA and AMD, ~1.4 GB of VRAM) makes it 0.1-0.5 s. On AMD the GPU reader is the default; if it cannot start, the server +prints "the GPU picture reader did not start (...); pictures are read on the CPU" and goes on with the CPU reader. ## AMD cards From b0b8860d13e4fd3bc433c6b544224efeafe7ed5e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:19:18 +0200 Subject: [PATCH 19/26] build_windows.bat: the HIP reader's host compiler gets the ROCm device-library path --- tools/hip/build_windows.bat | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/hip/build_windows.bat b/tools/hip/build_windows.bat index 0d166031..33acd936 100644 --- a/tools/hip/build_windows.bat +++ b/tools/hip/build_windows.bat @@ -97,6 +97,7 @@ if not "%STRATA_NO_VISION%"=="1" ( if not exist "%SRC%\build-vision-hip-win\build.ninja" ( cmake -G Ninja -S "%SRC%\tools\vision" -B "%SRC%\build-vision-hip-win" -DCMAKE_BUILD_TYPE=Release -DLLAMA_DIR="!LLAMA!" ^ -DSTRATA_VISION_HIP=ON "-DSTRATA_VISION_HIP_ARCHS=%STRATA_HIP_ARCHS%" -DSTRATA_PORTABLE=ON ^ + "-DCMAKE_CXX_FLAGS=--rocm-path=%ROCM_F% --rocm-device-lib-path=%BITCODE%" ^ "-DCMAKE_C_COMPILER=%ROCM_F%/lib/llvm/bin/clang.exe" "-DCMAKE_CXX_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" ^ "-DCMAKE_HIP_COMPILER=%ROCM_F%/lib/llvm/bin/clang++.exe" "-DCMAKE_HIP_COMPILER_ROCM_ROOT=%ROCM_F%" ^ "-DCMAKE_PREFIX_PATH=%ROCM_F%" "-DCMAKE_HIP_FLAGS=--rocm-path=%ROCM_F% --rocm-device-lib-path=%BITCODE%" || exit /b 1 From e23a56f2f8d774b76f9f1c5132040e9b3f3a275b Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:19:49 +0200 Subject: [PATCH 20/26] ENGINE-COMPONENT.md: the picture readers in an AMD package --- packaging/ENGINE-COMPONENT.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/packaging/ENGINE-COMPONENT.md b/packaging/ENGINE-COMPONENT.md index 903dec4f..217ccad0 100644 --- a/packaging/ENGINE-COMPONENT.md +++ b/packaging/ENGINE-COMPONENT.md @@ -95,9 +95,9 @@ the manifest file (which holds every file's hash), used as the package's digest |---|---|---|---| | `windows-x86_64` cuda, variant `cuda13` | the owner PC, the same cmake line as the release zips (CUDA 13.0, `75;86;89;120` real + `120` PTX, `STRATA_PORTABLE=ON`) | `strata.exe`, `strata_kq.dll`, `strata-vision.exe` (reused, unchanged since 0.1.44), `BUILD.json` | `min_driver` nvidia 580.65 | | `windows-x86_64` cuda, variant `cuda12` | the owner PC (CUDA 12.9, `60;61;70;75;80;86;89` real + `89` PTX, `STRATA_EXPERIMENTAL_SM60=ON`) | the same four files | experimental, `min_driver` nvidia 575.51; the CUDA 13 build wins when both fit | -| `windows-x86_64` hip | the owner PC, `tools/hip/build_windows.bat` (ROCm 10.2 nightly wheels) then `tools/hip/package_windows.py` | `strata.exe`, `strata-device.exe`, the ROCm DLLs and the rocBLAS/hipBLASLt kernels of the zip (`--tree`) | no Windows AMD test machine yet | +| `windows-x86_64` hip | the owner PC, `tools/hip/build_windows.bat` (ROCm 10.2 nightly wheels) then `tools/hip/package_windows.py` | `strata.exe`, `strata-device.exe`, the ROCm DLLs and the rocBLAS/hipBLASLt kernels of the zip (`--tree`) | no Windows AMD test machine yet; with `STRATA_NO_VISION` unset it also builds the two picture readers (`strata-vision.exe` on the CPU, `strata-vision-hip.exe` on the GPU) | | `linux-x86_64` cuda | a Linux box with the CUDA toolkit | `strata`, `libstrata_kq.so`, `libcudart/libcublas/libcublasLt` (13.x) | the GPU driver's `libcuda` stays the PC's | -| `linux-x86_64` hip | a box with ROCm (the Python wheels are enough) | `strata`, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, comgr + libLLVM, `rocblas/library` and `hipblaslt/library` for the listed gfx archs | | +| `linux-x86_64` hip | a box with ROCm (the Python wheels are enough) | `strata`, the HIP runtime, hipBLAS/hipBLASLt/rocBLAS, comgr + libLLVM, `rocblas/library` and `hipblaslt/library` for the listed gfx archs; `packaging/build_hip_linux.sh` builds it with both picture readers | | `linux-x86_64` hip, gfx1103 (Radeon 780M / Phoenix iGPU) | `packaging/build_hip_gfx1103.sh` on the mini PC (TheRock gfx110X-all SDK) | the same set as the gfx1200/1201 package, with `rocblas/library` and `hipblaslt/library` for gfx1103 (600 MiB) | experimental, unvalidated: the iGPU resets now and then (MES REMOVE_QUEUE, notes-minipc.md); never kill the engine mid-request; run configs set `STRATA_NO_ARENA_THP=1`. `engine_component.resolve` picks a HIP package only when its `archs` list a gfx target the Linux kfd topology reports | | `linux-x86_64` sycl | a box with oneAPI DPC++ | `strata` (JIT from SPIR-V), libsycl, the Unified Runtime adapters, MKL SYCL libraries | the Level Zero loader and compute runtime are the PC's driver | | `macos-arm64` metal | an Apple Silicon Mac | `strata`, `metal/kernels/*.metal`, `metal/engine-msl/*.metal`, `metal/ggml-common.h`, `metal/data/*.bin` | the Metal engine compiles its kernel sources when it starts; since S1 it finds them beside the executable (`metal/src/resource_path.h`: environment variable, then `/metal/`, then the compiled-in source path) | @@ -105,3 +105,13 @@ the manifest file (which holds every file's hash), used as the package's digest `packaging/collect_libs.py` gathers the Linux libraries (an `ldd` closure with the dlopen'd extras named, kernel data filtered by GPU architecture) into the folder `package_engine.py` packages; libraries the distribution provides are listed in `SYSTEM-LIBS.txt` inside the package so a missing one can be named on a target PC. + +## Picture readers in an AMD package + +A HIP package carries two programs for pictures next to `strata` (`vision` in its BUILD.json): `strata-vision` is the CPU reader, which +needs nothing of the GPU runtime and starts on every PC, and `strata-vision-hip` is the same reader on the card (llama.cpp's HIP +backend, built for the package's `archs`; BUILD.json `vision_archs`). Setup writes the run config with the GPU reader first and the CPU +reader as `vision.cpu_exe`; when the GPU reader does not start (the card is not in its build, the HIP runtime does not load, the card is +busy) the server starts the CPU reader by itself and prints one line. Both programs have RUNPATH `$ORIGIN` on Linux; on Windows the +ROCm DLLs they import sit beside the programs or in `rocm/bin` (the engine's PATH entry, `lib_dirs`). `strata_control/vision_reader.py` +holds the choice; `tools/test_vision_reader.py` the tests. From e6ab4c024d6dfc5e8070fc44465151df7d6a181a Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sun, 18 Oct 2026 22:28:15 +0200 Subject: [PATCH 21/26] No recognised engine: the app still downloads the model and warns in its card; loading names the next step setup.py control_engine_step stops only for strata launch (STRATA_NEED_ENGINE=1); the app warns and continues. The Models card and the first-run download card show the owner's plain warning before and during the download; the load refusal says the same with Settings > Engine. --- apps/host/server/native-control.mjs | 6 ++++-- apps/host/src/components/EngineWarning.tsx | 12 ++++++++++++ apps/host/src/components/GuidedSetup.tsx | 3 ++- apps/host/src/components/NativeModels.tsx | 2 ++ apps/host/src/lib/native.ts | 2 ++ apps/host/src/locales/de.json | 4 +++- apps/host/src/locales/en.json | 4 +++- apps/host/src/locales/es.json | 4 +++- apps/host/src/locales/ja.json | 4 +++- apps/host/src/locales/ko.json | 4 +++- apps/host/src/locales/pt.json | 4 +++- apps/host/src/locales/ru.json | 4 +++- apps/host/src/locales/zh.json | 4 +++- apps/host/src/styles/onboarding.css | 4 ++++ apps/host/tests/qa1-downloads.test.mjs | 16 ++++++++++++++++ setup.py | 10 +++++----- tests/terminal/test_launch_engine_first.py | 14 ++++++++++++-- 17 files changed, 83 insertions(+), 18 deletions(-) create mode 100644 apps/host/src/components/EngineWarning.tsx diff --git a/apps/host/server/native-control.mjs b/apps/host/server/native-control.mjs index ebfb9bd6..147ff225 100644 --- a/apps/host/server/native-control.mjs +++ b/apps/host/server/native-control.mjs @@ -25,6 +25,8 @@ const safeId=value=>typeof value==='string'&&/^[a-z0-9_-]{1,80}$/i.test(value); const busy=requests=>requests.some(r=>['queued','generating'].includes(r.state)); function readJson(path,fallback={}){try{return JSON.parse(readFileSync(path,'utf8').replace(/^\uFEFF/,''));}catch{return fallback;}} +/** The plain words for "no usable engine": the model still downloads, but loading needs the engine (owner decision 2026-10-18). */ +export const ENGINE_NOT_RECOGNISED='Strata didn’t recognise an engine for this computer. The model is downloaded, but it can’t run until the right engine is installed. Open Settings → Engine.'; export function createNativeControl({directory,requests=()=>[],changed=()=>{},spawnProcess=spawn,fetcher=fetch,modelsDirectory,nativeDataDirectory=value=>value,beforeLoad=async()=>{},hardwareProbe=()=>[],control=null,ready=null,appUpdater=null,defaultRepo=process.env.STRATA_NATIVE_REPO??resolve(ROOT,'../../Strata')}={}){ mkdirSync(directory,{recursive:true}); const settingsPath=join(directory,'native-host.json'); @@ -204,7 +206,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} return {cfg,resources,visionPreferences,parallelChoice,parallelNote}; } async function loadEngine(job,args){ - await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); + await refresh(true);if(job.state!=='running')return;const {config,entry,path:configFile}=record(args.model);assertSettingsFile(configFile);if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));}if(!entry.ready)throw new Error('Some model files are missing. Use Download / repair to restore them.'); if(externalRunning().length)throw new Error('A Strata server is already running outside this UI. Stop it before loading here, or connect its API in Settings → Models.'); if(args.multiple&&instances.size>=8)throw new Error('Unload an instance before adding another. Up to eight native instances can run here.'); const {cfg,resources,visionPreferences,parallelChoice,parallelNote:chosenNote}=buildConfig(args,config); @@ -345,7 +347,7 @@ return {summary:result.summary??'Deleted',removed:result.plan?.gb??null};} async function tuneOff(args){await refresh();const {path}=tuneConfig(args);return autotuner.off(path);} async function autotune(job,args){ await refresh(true);if(job.state!=='running')return; - if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(engine.notice??'No engine for this PC was found.');} + if(packaged){const engine=await control.engine();if(!engine.usable)throw new Error(ENGINE_NOT_RECOGNISED+(engine.notice?` ${engine.notice}`:''));} const {path}=tuneConfig(args); if(externalRunning().length)throw new Error('Stop the native server running outside this UI before tuning.'); if(busy(requests().filter(r=>instances.has(r.instanceId))))throw new Error('Finish requests before tuning.'); diff --git a/apps/host/src/components/EngineWarning.tsx b/apps/host/src/components/EngineWarning.tsx new file mode 100644 index 00000000..cbaa13c9 --- /dev/null +++ b/apps/host/src/components/EngineWarning.tsx @@ -0,0 +1,12 @@ +import { tr } from '../lib/i18n'; +import { Icon } from './ui'; +import type { NativeState } from '../lib/native'; + +/** The app could not find or recognise an engine for this computer (none installed and none in the feed, another card family, a driver that is too old). It still downloads the model + * (owner decision 2026-10-18) and says so before and during the download; loading says the same with the next step. */ +export const engineMissing = (native: NativeState | null | undefined) => !!native?.engine && native.engine.usable === false; + +export function EngineWarning({ native }: { native: NativeState | null | undefined }) { + if (!engineMissing(native)) return null; + return

    {tr("Strata didn’t recognise an engine for this computer. The model will download, but it may not run until the right engine is installed (Settings → Engine).")}

    {native?.engine?.notice ? {native.engine.notice} : null}
    ; +} diff --git a/apps/host/src/components/GuidedSetup.tsx b/apps/host/src/components/GuidedSetup.tsx index a8586cee..3697fdb7 100644 --- a/apps/host/src/components/GuidedSetup.tsx +++ b/apps/host/src/components/GuidedSetup.tsx @@ -15,6 +15,7 @@ import { downloadCounter, modelFolderLabel, onboardingError } from '../lib/onboa import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; import { VersionPicker } from './VersionPicker'; import { DownloadParts } from './DownloadParts'; +import { EngineWarning } from './EngineWarning'; import { recommendedVersions } from '../lib/native-fit'; import { nativeCatalogModels, catalogVersionLabel } from '../lib/native-catalog'; type Choices = NonNullable['onboarding']>; @@ -194,7 +195,7 @@ export function GuidedSetup() { {tr(folderOpen ? void perform(async () => { await nativeAction('directory', { directory: path }); setDirectory(path); setFolderOpen(false); setPlan(null); })}/> : null)} :
    {tr("Connect your Strata installation")} void skip(false, 'Engine')}>{tr("Connect engine")}
    )}
: step === 3 ?
-
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
+
{tr(selectedFamily?.title)}{tr(version ? catalogVersionLabel(version) : '')}{tr(version?.model)}
{tr(preparing ?
{tr(progress ? stageText(installStage(installJob?.result?.install)) : 'Preparing your model…')}
{tr(progress ? : )}
{tr(progress ? `${progress.percent ?? 0}%${Number.isFinite(progress.done_gb) && Number.isFinite(progress.total_gb) ? ` · ${progress.done_gb!.toFixed(1)} / ${progress.total_gb!.toFixed(1)} GB` : ''}` : 'Getting files ready…')}
{tr(eta ? {eta} : null)}
: <>{tr(stopped ? : null)}{tr(plan?.plan?.disk_short ? : null)})} {tr("Save to")}{tr(modelFolderLabel(folder))}{tr(!preparing ? : null)}
diff --git a/apps/host/src/components/NativeModels.tsx b/apps/host/src/components/NativeModels.tsx index 255393e1..05827343 100644 --- a/apps/host/src/components/NativeModels.tsx +++ b/apps/host/src/components/NativeModels.tsx @@ -9,6 +9,7 @@ import { Btn, Dialog, ErrorNotice, Icon, Select } from './ui'; import { installProgress, installStage, stageText, useDownloadEta } from '../lib/download-eta'; import { useKept } from '../lib/kept-state'; import { DownloadParts } from './DownloadParts'; +import { EngineWarning } from './EngineWarning'; import { sizeGb } from '../lib/format'; import { NativeDeleteDialog } from './NativeDelete'; import { plainFailureText } from '../lib/plain-errors'; @@ -181,6 +182,7 @@ export function NativeModels({ onOtherModels, onReady, onImport, onConnectEngine {tr(selectedSize?.imagesCapable && !selectedSize.images ?

{tr("This model can read pictures, but the engine installed here does not include the picture reader yet, so Read pictures is off. Update the engine in Settings → About to turn it on.")}

: null)} {tr(selectedSize?.images ? <>
{tr(expert && vision !== 'no' ?