From c3dc9820fd926668d42956dd84eda05dffd12f4b Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:46:07 -0700 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20move=20withdrawn=20unsloth=20presets?= =?UTF-8?q?=20to=20public=20repos;=20chore:=20bump=20start-sdk=20to=204.1.?= =?UTF-8?q?0;=2012110:0=20=E2=86=92=2012110:1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit unsloth made its Qwen2.5 7B/14B/32B and Meta-Llama-3.1-8B GGUF repos non-public (the HF API returns 401), so llama-server can't resolve a file for those presets and exits. The presets now point at Qwen's own GGUF repos and bartowski's Llama 3.1 8B (Meta publishes no GGUF). The migration rewrites a saved -hf selection of a withdrawn repo only when none of its weights are cached: llama-server falls back to hf_cache::get_cached_files when the repo lookup fails (common_download_get_hf_plan at b12110), so a cached copy still loads and moving it would force a needless re-download. UPDATING.md gains a per-bump check that every preset repo is public and carries its quant; README documents the failure for support. Closes #46 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 1 + UPDATING.md | 11 ++ instructions.md | 2 +- package-lock.json | 156 +--------------------- package.json | 2 +- startos/actions/presets.ts | 8 +- startos/actions/setModel.ts | 2 +- startos/i18n/dictionaries/default.ts | 2 +- startos/i18n/dictionaries/translations.ts | 8 +- startos/versions/current.ts | 85 ++++++------ 11 files changed, 67 insertions(+), 212 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 34d1bf3..28f9e52 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,5 +37,5 @@ verified, tried, and decided belongs in the commit message and the PR body. - **One repo, four builds.** `VARIANT` (the `Makefile` targets) selects the image, architectures and `hardwareRequirements` for `generic`, `nvidia`, `rocm` and `vulkan`. Bump `upstreamBuild` in `startos/manifest/index.ts` once; every variant follows. - **Don't widen the AMD matcher to a bare `amdgpu` match.** ROCm fails on integrated Radeon, and StartOS's regex engine has no lookahead to exclude them, so it stays a positive allowlist of discrete product names. - **Don't shorten the health check's one-hour grace period.** It covers the model download on first start. -- **New presets go in `startos/actions/presets.ts`**, with `minMemoryGB` set to the weights plus roughly 25% for the KV cache. +- **New presets go in `startos/actions/presets.ts`**, with `minMemoryGB` set to the weights plus roughly 25% for the KV cache, and must pass `UPDATING.md`'s preset check: a public, ungated repo, the publisher's own where one exists. - **Keep the Web UI host on Basic auth and the API host on Bearer.** One binding takes one `ProxyAuth`, and StartOS enforces it on the bridge address too, so moving siblings to `api-multi` or merging the hosts locks out browsers or other services. diff --git a/README.md b/README.md index 0968a7b..daf8370 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,7 @@ The `main` and `public` volumes are backed up — `sdk.Backups.ofVolumes('main', 8. **Models are excluded from backups.** After a restore, the selected model downloads again on first start. 9. **Downloaded models are listed by repo and file.** A cached file matching a curated preset's quant is not duplicated; other quants from the same repo remain separate entries. Settings are remembered per model, so deleting a model with Delete Model Cache and downloading it again keeps them. 10. **Saved inference states are upstream-version-specific.** Custom `--slot-save-path` caches may need to be recreated after an update; the package does not convert them. This does not affect downloaded GGUF weights or `store.json`. +11. **A model's HuggingFace repo must stay public.** If its publisher withdraws or gates it, `llama-server` logs `get_repo_commit: error: GET failed (401)` and fails to start unless that model's weights are already cached. Choose another preset or a public repo in Set Model. --- diff --git a/UPDATING.md b/UPDATING.md index a1b03b8..bb8cfe9 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -65,3 +65,14 @@ Map the build tag `bNNNN` to the version `NNNN:`, keeping the complete 1. Update `const upstreamBuild` in `startos/manifest/index.ts` to the stable release's build tag (e.g. `'b11429'` for `v0.6.0`) — the one you confirmed all four variants and their architectures for above. 2. Set `version` in `startos/versions/current.ts` to `:0`. 3. In the release notes, summarize changes since the actual pinned build, not features already present from the previous stable release's range. Link both the stable release (`https://github.com/ggml-org/llama.cpp/releases/tag/vX.Y.Z`) and the build comparison. +4. Confirm every Set Model preset still downloads. A HuggingFace publisher can withdraw a repo at any time, and llama-server then fails to start for anyone who picks that preset without its weights cached. Run from the repo root; every line must read `OK`: + + ```sh + grep -o "hfRepo: '[^']*'" startos/actions/presets.ts | cut -d"'" -f2 | while IFS=: read -r repo quant; do + json=$(curl -sf "https://huggingface.co/api/models/$repo") || { echo "UNAVAILABLE $repo"; continue; } + jq -r '.siblings[].rfilename' <<<"$json" | grep -qi -- "$quant" \ + && echo "OK $repo:$quant" || echo "NO $quant FILE $repo" + done + ``` + + For a failing preset, point `hfRepo` at a public, ungated repo carrying the same model at the same quant, preferring the model publisher's own GGUF repo, and migrate a saved selection of the old repo that has no cached weights onto the new one, as version `12110:1` does. diff --git a/instructions.md b/instructions.md index 38fc4e3..19a67e3 100644 --- a/instructions.md +++ b/instructions.md @@ -17,7 +17,7 @@ Requires StartOS 0.4.1 or later. Two tasks appear on the dashboard on a fresh install: 1. **Set UI Password** — generates your web UI login password. The username is always `admin`; copy the password it returns (you'll need it the first time you open the UI or connect a client). Run it again any time to rotate the password. -2. **Set Model** — choose what llama.cpp serves. The form shows curated presets, lists the memory each one needs, and disables ones too large for the detected memory. Models you have already downloaded are listed too, so you can switch back to one without re-entering or re-downloading it. Every entry has its own context size, GPU layers and extra arguments, and remembers what you last used with that model. If none of the presets fit, pick **Custom** and paste a HuggingFace repo such as `unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M`. On a GPU variant, leave `GPU layers` at 999 to offload everything; on the CPU-only `generic` variant the field is ignored. +2. **Set Model** — choose what llama.cpp serves. The form shows curated presets, lists the memory each one needs, and disables ones too large for the detected memory. Models you have already downloaded are listed too, so you can switch back to one without re-entering or re-downloading it. Every entry has its own context size, GPU layers and extra arguments, and remembers what you last used with that model. If none of the presets fit, pick **Custom** and paste a HuggingFace repo such as `Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M`. On a GPU variant, leave `GPU layers` at 999 to offload everything; on the CPU-only `generic` variant the field is ignored. Complete both tasks, then start the service from the dashboard. The first launch downloads weights — expect several gigabytes and a few minutes (or longer over a slow link) before the API answers. The API health check stays pending until the model finishes loading, even if the chat UI opens earlier. Subsequent restarts are fast. diff --git a/package-lock.json b/package-lock.json index 492b05d..d408948 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,7 +6,7 @@ "": { "name": "llama-cpp-startos", "dependencies": { - "@start9labs/start-sdk": "4.0.0" + "@start9labs/start-sdk": "4.1.0" } }, "node_modules/@eslint-community/eslint-utils": { @@ -250,9 +250,9 @@ "license": "MIT" }, "node_modules/@start9labs/start-sdk": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/@start9labs/start-sdk/-/start-sdk-4.0.0.tgz", - "integrity": "sha512-DIlIveWLqgPHYgvTttTXTeKEO4u6B4aab0+nRng3xSMJX15o3E+AL5vlijsggLPFsoDztFlcm4C7txPEcQOWXg==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@start9labs/start-sdk/-/start-sdk-4.1.0.tgz", + "integrity": "sha512-/VRlD66r4BkZJPe/CWnRMzHwNgjyj92DWCbu7xnPatHX6wY7KKVg+TrOibGaYVy/AXcmkIPaLFcSDV+OXAMU2w==", "bundleDependencies": [ "@start9labs/start-core" ], @@ -278,154 +278,6 @@ "zod": "4.6.7" } }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core": { - "inBundle": true, - "license": "MIT", - "dependencies": { - "@iarna/toml": "^3.0.0", - "@noble/curves": "^1.9.7", - "@noble/hashes": "^1.8.0", - "deep-equality-data-structures": "^2.0.0", - "isomorphic-fetch": "^3.0.0", - "mime": "^4.1.0", - "yaml": "^2.8.3", - "zod": "4.6.7" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/@iarna/toml": { - "version": "3.0.0", - "inBundle": true, - "license": "ISC" - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/@noble/curves": { - "version": "1.9.7", - "inBundle": true, - "license": "MIT", - "dependencies": { - "@noble/hashes": "1.8.0" - }, - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/@noble/hashes": { - "version": "1.8.0", - "inBundle": true, - "license": "MIT", - "engines": { - "node": "^14.21.3 || >=16" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/deep-equality-data-structures": { - "version": "2.0.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "object-hash": "^3.0.0" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/isomorphic-fetch": { - "version": "3.0.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "node-fetch": "^2.6.1", - "whatwg-fetch": "^3.4.1" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/mime": { - "version": "4.1.1", - "funding": [ - "https://github.com/sponsors/broofa" - ], - "inBundle": true, - "license": "MIT", - "bin": { - "mime": "bin/cli.js" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/node-fetch": { - "version": "2.7.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/object-hash": { - "version": "3.0.0", - "inBundle": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/tr46": { - "version": "0.0.3", - "inBundle": true, - "license": "MIT" - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/webidl-conversions": { - "version": "3.0.1", - "inBundle": true, - "license": "BSD-2-Clause" - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/whatwg-fetch": { - "version": "3.6.20", - "inBundle": true, - "license": "MIT" - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/whatwg-url": { - "version": "5.0.0", - "inBundle": true, - "license": "MIT", - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/yaml": { - "version": "2.9.1", - "inBundle": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, - "node_modules/@start9labs/start-sdk/node_modules/@start9labs/start-core/node_modules/zod": { - "version": "4.6.7", - "inBundle": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/colinhacks" - } - }, "node_modules/@types/estree": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", diff --git a/package.json b/package.json index 2666dfb..275c64c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "llama-cpp-startos", "dependencies": { - "@start9labs/start-sdk": "4.0.0" + "@start9labs/start-sdk": "4.1.0" }, "overrides": { "@start9labs/start-sdk": "$@start9labs/start-sdk" diff --git a/startos/actions/presets.ts b/startos/actions/presets.ts index f35ab9c..2056720 100644 --- a/startos/actions/presets.ts +++ b/startos/actions/presets.ts @@ -35,21 +35,21 @@ export const models: ModelPreset[] = [ { id: 'qwen25-7b', displayName: 'Qwen2.5 7B Instruct', - hfRepo: 'unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M', + hfRepo: 'Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M', minMemoryGB: 6, defaultCtx: 8192, }, { id: 'llama-31-8b', displayName: 'Llama 3.1 8B Instruct', - hfRepo: 'unsloth/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M', + hfRepo: 'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M', minMemoryGB: 8, defaultCtx: 8192, }, { id: 'qwen25-14b', displayName: 'Qwen2.5 14B Instruct', - hfRepo: 'unsloth/Qwen2.5-14B-Instruct-GGUF:Q4_K_M', + hfRepo: 'Qwen/Qwen2.5-14B-Instruct-GGUF:Q4_K_M', minMemoryGB: 12, defaultCtx: 8192, }, @@ -70,7 +70,7 @@ export const models: ModelPreset[] = [ { id: 'qwen25-32b', displayName: 'Qwen2.5 32B Instruct', - hfRepo: 'unsloth/Qwen2.5-32B-Instruct-GGUF:Q4_K_M', + hfRepo: 'Qwen/Qwen2.5-32B-Instruct-GGUF:Q4_K_M', minMemoryGB: 24, defaultCtx: 8192, }, diff --git a/startos/actions/setModel.ts b/startos/actions/setModel.ts index 7805ad1..848e5cf 100644 --- a/startos/actions/setModel.ts +++ b/startos/actions/setModel.ts @@ -167,7 +167,7 @@ const customVariant = { hfRepo: Value.text({ name: i18n('HuggingFace repo'), description: i18n( - 'A HuggingFace GGUF repo, optionally with a quant tag (e.g. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', + 'A HuggingFace GGUF repo, optionally with a quant tag (e.g. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', ), required: true, default: null, diff --git a/startos/i18n/dictionaries/default.ts b/startos/i18n/dictionaries/default.ts index 377c0bc..0c1f624 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -20,7 +20,7 @@ const dict = { 'Changing the model will restart the service and may require downloading a new model.': 9, Configuration: 10, 'HuggingFace repo': 11, - 'A HuggingFace GGUF repo, optionally with a quant tag (e.g. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).': 12, + 'A HuggingFace GGUF repo, optionally with a quant tag (e.g. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).': 12, 'HuggingFace file (optional)': 13, 'Specific GGUF filename inside the repo. Leave empty to let llama-server pick.': 14, 'Context size': 15, diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index f8d8a9e..3eb79d2 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -14,7 +14,7 @@ export default { 9: 'Cambiar el modelo reiniciará el servicio y puede requerir descargar un nuevo modelo.', 10: 'Configuración', 11: 'Repositorio HuggingFace', - 12: 'Un repositorio GGUF de HuggingFace, opcionalmente con una etiqueta de cuantización (ej. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', + 12: 'Un repositorio GGUF de HuggingFace, opcionalmente con una etiqueta de cuantización (ej. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', 13: 'Archivo HuggingFace (opcional)', 14: 'Nombre del archivo GGUF dentro del repositorio. Dejar vacío para que llama-server lo elija.', 15: 'Tamaño de contexto', @@ -77,7 +77,7 @@ export default { 9: 'Das Ändern des Modells startet den Dienst neu und erfordert möglicherweise den Download eines neuen Modells.', 10: 'Konfiguration', 11: 'HuggingFace-Repository', - 12: 'Ein HuggingFace-GGUF-Repository, optional mit einem Quantisierungs-Tag (z. B. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', + 12: 'Ein HuggingFace-GGUF-Repository, optional mit einem Quantisierungs-Tag (z. B. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', 13: 'HuggingFace-Datei (optional)', 14: 'Spezifischer GGUF-Dateiname im Repository. Leer lassen, damit llama-server wählt.', 15: 'Kontextgröße', @@ -140,7 +140,7 @@ export default { 9: 'Zmiana modelu zrestartuje usługę i może wymagać pobrania nowego modelu.', 10: 'Konfiguracja', 11: 'Repozytorium HuggingFace', - 12: 'Repozytorium GGUF z HuggingFace, opcjonalnie z tagiem kwantyzacji (np. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', + 12: 'Repozytorium GGUF z HuggingFace, opcjonalnie z tagiem kwantyzacji (np. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', 13: 'Plik HuggingFace (opcjonalnie)', 14: 'Konkretna nazwa pliku GGUF w repozytorium. Pozostaw puste, aby llama-server sam wybrał.', 15: 'Rozmiar kontekstu', @@ -203,7 +203,7 @@ export default { 9: 'Changer de modèle redémarre le service et peut nécessiter le téléchargement d’un nouveau modèle.', 10: 'Configuration', 11: 'Dépôt HuggingFace', - 12: 'Un dépôt GGUF HuggingFace, éventuellement avec une étiquette de quantification (ex. unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', + 12: 'Un dépôt GGUF HuggingFace, éventuellement avec une étiquette de quantification (ex. Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M).', 13: 'Fichier HuggingFace (optionnel)', 14: 'Nom de fichier GGUF spécifique dans le dépôt. Laissez vide pour laisser llama-server choisir.', 15: 'Taille du contexte', diff --git a/startos/versions/current.ts b/startos/versions/current.ts index af4d37b..4cb1692 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,56 +1,47 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' +import { storeJson } from '../fileModels/store.json' +import { listCachedModels } from '../modelCache' +import { hfRepoFlags, lastOptionValue } from '../utils' + +const withdrawnRepos: Record = { + 'unsloth/Qwen2.5-7B-Instruct-GGUF': 'Qwen/Qwen2.5-7B-Instruct-GGUF', + 'unsloth/Qwen2.5-14B-Instruct-GGUF': 'Qwen/Qwen2.5-14B-Instruct-GGUF', + 'unsloth/Qwen2.5-32B-Instruct-GGUF': 'Qwen/Qwen2.5-32B-Instruct-GGUF', + 'unsloth/Meta-Llama-3.1-8B-Instruct-GGUF': + 'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF', +} export const current = VersionInfo.of({ - version: '12110:0', + version: '12110:1', releaseNotes: { - en_US: `Updated llama.cpp to build b12110 at the stable v0.9.0 release. Requires StartOS 0.4.1 or later. - -- Adds Clover, Limite, Metis-1.6 and Mistral Large 4 model support, FP8 E4M3 quantization, Chatterbox speech synthesis, Nemotron 3.5 transcription and predefined Pocket TTS voices. -- Speeds up Gemma 4 E2B/E4B prompt processing and concurrent inference with a unified KV cache. Improves GPU performance, model loading and tool-call handling. -- Fixes ignored extra parameters in the Responses API and improves chat scrolling, queued messages and interrupted tool-call display. -- Set Model no longer confuses cached F16 and BF16 weights. Existing model settings and downloaded GGUF weights need no conversion; custom saved slot caches may need to be recreated after updating. - -[Full upstream release notes](https://github.com/ggml-org/llama.cpp/releases/tag/v0.9.0) -[Changes since the previous build](https://github.com/ggml-org/llama.cpp/compare/b11960...b12110)`, - es_ES: `Actualiza llama.cpp a la compilación b12110 de la versión estable v0.9.0. Requiere StartOS 0.4.1 o posterior. - -- Añade compatibilidad con los modelos Clover, Limite, Metis-1.6 y Mistral Large 4, cuantización FP8 E4M3, síntesis de voz Chatterbox, transcripción Nemotron 3.5 y voces predefinidas de Pocket TTS. -- Acelera el procesamiento de prompts en Gemma 4 E2B/E4B y la inferencia simultánea con una caché KV unificada. Mejora el rendimiento de GPU, la carga de modelos y las llamadas a herramientas. -- Corrige los parámetros adicionales ignorados en la API Responses y mejora el desplazamiento del chat, los mensajes en cola y la visualización de llamadas a herramientas interrumpidas. -- Establecer modelo ya no confunde los pesos F16 y BF16 en caché. La configuración del modelo y los pesos GGUF descargados no necesitan conversión; puede ser necesario recrear las cachés de ranuras guardadas mediante opciones personalizadas tras actualizar. - -[Notas completas de la versión original](https://github.com/ggml-org/llama.cpp/releases/tag/v0.9.0) -[Cambios desde la compilación anterior](https://github.com/ggml-org/llama.cpp/compare/b11960...b12110)`, - de_DE: `Aktualisiert llama.cpp auf Build b12110 der stabilen Veröffentlichung v0.9.0. Erfordert StartOS 0.4.1 oder neuer. - -- Ergänzt Unterstützung für Clover, Limite, Metis-1.6 und Mistral Large 4, FP8-E4M3-Quantisierung, Chatterbox-Sprachsynthese, Nemotron-3.5-Transkription und vordefinierte Pocket-TTS-Stimmen. -- Beschleunigt die Prompt-Verarbeitung bei Gemma 4 E2B/E4B und gleichzeitige Inferenz mit gemeinsamem KV-Cache. Verbessert GPU-Leistung, Modellladen und Werkzeugaufrufe. -- Behebt ignorierte Zusatzparameter in der Responses-API und verbessert das Scrollen im Chat, wartende Nachrichten und die Anzeige unterbrochener Werkzeugaufrufe. -- Modell festlegen verwechselt zwischengespeicherte F16- und BF16-Gewichte nicht mehr. Modelleinstellungen und heruntergeladene GGUF-Gewichte benötigen keine Konvertierung; benutzerdefinierte gespeicherte Slot-Caches müssen nach dem Update möglicherweise neu erstellt werden. - -[Vollständige Upstream-Veröffentlichungsnotizen](https://github.com/ggml-org/llama.cpp/releases/tag/v0.9.0) -[Änderungen seit dem vorherigen Build](https://github.com/ggml-org/llama.cpp/compare/b11960...b12110)`, - pl_PL: `Aktualizuje llama.cpp do kompilacji b12110 ze stabilnego wydania v0.9.0. Wymaga StartOS 0.4.1 lub nowszego. - -- Dodaje obsługę modeli Clover, Limite, Metis-1.6 i Mistral Large 4, kwantyzację FP8 E4M3, syntezę mowy Chatterbox, transkrypcję Nemotron 3.5 oraz gotowe głosy Pocket TTS. -- Przyspiesza przetwarzanie promptów w Gemma 4 E2B/E4B i równoczesne wnioskowanie ze wspólną pamięcią podręczną KV. Ulepsza wydajność GPU, wczytywanie modeli i wywoływanie narzędzi. -- Naprawia ignorowanie dodatkowych parametrów w API Responses oraz ulepsza przewijanie czatu, wiadomości w kolejce i wyświetlanie przerwanych wywołań narzędzi. -- Ustaw model nie myli już zapisanych wag F16 i BF16. Ustawienia modeli i pobrane wagi GGUF nie wymagają konwersji; po aktualizacji może być konieczne ponowne utworzenie zapisanych pamięci podręcznych slotów używanych z własnymi opcjami. - -[Pełne informacje o wydaniu projektu źródłowego](https://github.com/ggml-org/llama.cpp/releases/tag/v0.9.0) -[Zmiany od poprzedniej kompilacji](https://github.com/ggml-org/llama.cpp/compare/b11960...b12110)`, - fr_FR: `Met à jour llama.cpp vers la compilation b12110 de la version stable v0.9.0. Nécessite StartOS 0.4.1 ou ultérieur. - -- Ajoute la prise en charge de Clover, Limite, Metis-1.6 et Mistral Large 4, la quantification FP8 E4M3, la synthèse vocale Chatterbox, la transcription Nemotron 3.5 et les voix prédéfinies de Pocket TTS. -- Accélère le traitement des prompts de Gemma 4 E2B/E4B et l’inférence simultanée avec un cache KV unifié. Améliore les performances GPU, le chargement des modèles et les appels d’outils. -- Corrige les paramètres supplémentaires ignorés par l’API Responses et améliore le défilement des discussions, les messages en attente et l’affichage des appels d’outils interrompus. -- Définir le modèle ne confond plus les poids F16 et BF16 en cache. Les réglages du modèle et les poids GGUF téléchargés ne nécessitent aucune conversion ; les caches d’emplacement enregistrés avec des options personnalisées peuvent devoir être recréés après la mise à jour. - -[Notes complètes de la version amont](https://github.com/ggml-org/llama.cpp/releases/tag/v0.9.0) -[Modifications depuis la compilation précédente](https://github.com/ggml-org/llama.cpp/compare/b11960...b12110)`, + en_US: + 'Fixes downloading the Qwen2.5 7B, 14B and 32B and Llama 3.1 8B Instruct presets. A model you already downloaded keeps working unchanged.', + es_ES: + 'Corrige la descarga de los presets Qwen2.5 7B, 14B y 32B y Llama 3.1 8B Instruct. Un modelo que ya haya descargado sigue funcionando sin cambios.', + de_DE: + 'Behebt das Herunterladen der Presets Qwen2.5 7B, 14B und 32B sowie Llama 3.1 8B Instruct. Ein bereits heruntergeladenes Modell funktioniert unverändert weiter.', + pl_PL: + 'Naprawia pobieranie presetów Qwen2.5 7B, 14B i 32B oraz Llama 3.1 8B Instruct. Już pobrany model działa dalej bez zmian.', + fr_FR: + 'Corrige le téléchargement des préréglages Qwen2.5 7B, 14B et 32B et Llama 3.1 8B Instruct. Un modèle déjà téléchargé continue de fonctionner sans changement.', }, migrations: { - up: async ({ effects }) => {}, + up: async ({ effects }) => { + const serveArgs = await storeJson.read((s) => s?.serveArgs).once() + const repoArg = serveArgs && lastOptionValue(serveArgs, hfRepoFlags) + if (!repoArg) return + const [repo, quant] = repoArg.split(':') + const replacement = withdrawnRepos[repo] + if (!replacement) return + // llama-server falls back to cached weights when the repo lookup fails. + if ((await listCachedModels()).some((c) => c.repo === repo)) return + const i = serveArgs.lastIndexOf(repoArg) + await storeJson.merge(effects, { + serveArgs: serveArgs.map((arg, j) => + j === i ? (quant ? `${replacement}:${quant}` : replacement) : arg, + ), + }) + }, down: IMPOSSIBLE, }, }) From c5767f0b0b591404954b83ad80549911d5d9136b Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Sun, 22 Nov 2026 08:25:56 -0700 Subject: [PATCH 2/3] refactor: save presets by id and resolve their repo at start A preset selection used to be saved as a copy of its repo in serveArgs, modelSettings, modelSelection.custom and the extra flags, so a withdrawn upstream repo meant a data migration over all of them, plus a restore hook, since a cache-free restore never crosses the version edge. store.json now saves the model as {preset} or {hfRepo, hfFile} and the remaining server flags as settingsArgs. main.ts resolves a preset against presets.ts at every start: its hfRepo, unless only a repo in its new formerRepos has the weights cached, matched by the preset's quant rather than by repo. Settings are keyed the same way, and a repo entry that is a preset's quant counts as that preset. Replacing a preset's repo is now an edit to presets.ts; UPDATING.md and AGENTS.md say so. The 12110:1 migration is now a one-time conversion of the old store: every release wrote `-hf [-hff ]` first, so the model is split off the front of serveArgs and matched to a preset, and each modelSettings entry is matched the same way. Verified on demo.local (generic x86_64): installed 12110:0, ran Llama 3.2 1B, then selected Qwen2.5 7B and reproduced #46 (401, model loading error). Updated to this build: the store converted to {preset} entries with ctx and extra flags intact, Qwen2.5 7B downloaded from Qwen's split repo and served, and Set Model reopened on it with its settings. With the weights moved under the unsloth cache folder, the server ran -hf unsloth/...:Q4_K_M, got the 401, loaded the cached copy, and Delete Model Cache kept that folder in use. Custom, preset and unchanged-resubmit paths wrote clean refs, and the unchanged resubmit did not restart. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + README.md | 19 +-- UPDATING.md | 2 +- startos/actions/deleteModelCache.ts | 11 +- startos/actions/presets.ts | 6 + startos/actions/setModel.ts | 205 ++++++++++------------------ startos/fileModels/store.json.ts | 17 ++- startos/init/initializeService.ts | 9 +- startos/main.ts | 10 +- startos/modelCache.ts | 49 +++++++ startos/utils.ts | 74 ++++++++++ startos/versions/current.ts | 53 +++---- 12 files changed, 281 insertions(+), 175 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 28f9e52..7490aa4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,4 +38,5 @@ verified, tried, and decided belongs in the commit message and the PR body. - **Don't widen the AMD matcher to a bare `amdgpu` match.** ROCm fails on integrated Radeon, and StartOS's regex engine has no lookahead to exclude them, so it stays a positive allowlist of discrete product names. - **Don't shorten the health check's one-hour grace period.** It covers the model download on first start. - **New presets go in `startos/actions/presets.ts`**, with `minMemoryGB` set to the weights plus roughly 25% for the KV cache, and must pass `UPDATING.md`'s preset check: a public, ungated repo, the publisher's own where one exists. +- **Never write a preset's repo into `store.json`.** A preset is saved by id and resolved against `presets.ts` at start, so changing a preset's repo needs no migration — move the old one into `formerRepos`, which keeps cached copies in use. Never delete a preset id either: a saved selection of it raises the Set Model task. - **Keep the Web UI host on Basic auth and the API host on Bearer.** One binding takes one `ProxyAuth`, and StartOS enforces it on the bridge address too, so moving siblings to `api-multi` or merging the hosts locks out browsers or other services. diff --git a/README.md b/README.md index daf8370..91af873 100644 --- a/README.md +++ b/README.md @@ -79,18 +79,21 @@ Two models. Two of `store.json`'s keys decide whether the service can run at all | Key | Notes | | ---------------- | ----------------------------------------------------------------------------------------------- | -| `serveArgs` | The full argument list handed to `llama-server`, composed by the Set Model action | +| `model` | The model to serve: `{preset}` for a curated preset, `{hfRepo, hfFile}` for anything else | +| `settingsArgs` | The `llama-server` flags after the model's own (context, GPU layers, extras), from Set Model | | `uiPassword` | The password for the proxy's basic auth; the username is always `admin` | | `modelSelection` | What the Set Model form last submitted, so it can be prefilled next time — read by nothing else | | `modelSettings` | Context size, GPU layers and extra flags last used for each model — read only by Set Model | -Nothing else writes the file, and neither `serveArgs` nor `uiPassword` is defaulted — both are absent until you run their action, and each absence raises a task. +Nothing else writes the file, and neither `model` nor `uiPassword` is defaulted — both are absent until you run their action, and each absence raises a task. `credentials.json` on the `public` volume holds one key, `apiKey`: the Bearer token for the OpenAI-compatible API interface. Init generates it (32 alphanumeric characters) whenever it is missing — on install, on update from a version without it, or after it is deleted — so it is never empty while the service runs. Quant tags match whole tokens when identifying cached weights: `F16` does not select a `BF16` file. -`modelSelection` holds the chosen `selection` plus a `custom` object with the last Custom submission's fields; picking another entry leaves `custom` in place so Custom stays prefilled. `modelSettings` is a list of `{hfRepo, hfFile, ctx, ngl, extraArgs}`, one per model, replaced on each submit of that model. Entries are matched to the list by the weights they resolve to — the same cached file, or the same quant tag before download — so a Custom model keeps its settings once it shows up as a downloaded entry. Stores from before `modelSettings` fall back to `modelSelection.custom`. The daemon reads neither, so they cannot disagree with `serveArgs` about what is actually running — at worst they prefill a form with a stale answer. +`modelSelection` holds the chosen `selection` plus a `custom` object with the last Custom submission's fields; picking another entry leaves `custom` in place so Custom stays prefilled. `modelSettings` is a list of `{preset}` or `{hfRepo, hfFile}` entries with `ctx`, `ngl` and `extraArgs`, one per model, replaced on each submit of that model. A preset entry matches its preset; a repo entry matches by the weights it resolves to — the same cached file, or the same quant tag before download — so a Custom model keeps its settings once it shows up as a downloaded entry, and one that is a preset's quant counts as that preset. Stores from before `modelSettings` fall back to `modelSelection.custom`. The daemon reads neither, so they cannot disagree with `model` about what is actually running — at worst they prefill a form with a stale answer. + +**A preset's repo is resolved at every start, never saved.** `main.ts` looks the preset up in `startos/actions/presets.ts` and serves its `hfRepo`, unless those weights are not cached and a repo in its `formerRepos` has them cached, in which case it serves that one. A preset whose upstream repo is withdrawn therefore moves to its replacement on the next start for everyone without the old weights, restores included, while a server that already downloaded it keeps using its copy: llama-server falls back to cached files when HuggingFace refuses the repo. **No configuration file reaches the application.** Two environment variables are set, both redirecting caches onto the volume so downloaded weights survive a container rebuild: @@ -99,7 +102,7 @@ Quant tags match whole tokens when identifying cached weights: `F16` does not se | `LLAMA_CACHE` | `/data/models` | | `HF_HOME` | `/data/huggingface` | -Everything else about how the model is served is in `serveArgs`, and the package always appends the host and port itself so the server binds where the interface expects it. +Everything else about how the model is served is in `settingsArgs`, and the package always appends the host and port itself so the server binds where the interface expects it. ## Dependencies @@ -138,11 +141,11 @@ Four actions, all user-facing. Chooses what the server runs — either a curated preset or a model of your own. -- **What it changes:** `serveArgs` and `modelSelection` in `store.json`, replacing each entirely, and the chosen model's entry in `modelSettings`. +- **What it changes:** `model`, `settingsArgs` and `modelSelection` in `store.json`, replacing each entirely, and the chosen model's entry in `modelSettings`. - **Cost:** seconds to write, then a restart — and, if the model is not already cached, a download that can take a long time. - **Repeat safety:** safe to re-run. Switching back to a previously used model is fast, because the old one is still cached. - **Every entry has its own context size, GPU layers and extra flags**, prefilled with what that model last ran with (`modelSettings`), or with the preset's context and full GPU offload the first time. Switching to another model and back keeps them. -- **The form reopens on the running model**, which stays selectable: change its settings and submit to restart with them. Submitting it unchanged writes the same `serveArgs` and does not restart. With nothing chosen yet the form falls back to the hardware-filtered default. +- **The form reopens on the running model**, which stays selectable: change its settings and submit to restart with them. Submitting it unchanged writes the same `model` and `settingsArgs` and does not restart. With nothing chosen yet the form falls back to the hardware-filtered default. - **Presets are filtered to your hardware.** The form reads the accelerator's memory — VRAM on NVIDIA and ROCm, system memory otherwise — and disables any preset that would not fit, defaulting to the smallest that does. The field's help text lists every preset with the memory it needs. The estimate is the quantized weights plus roughly a quarter for the context cache. - **Models already downloaded to the volume appear in the same list**, so a model you fetched before can be reselected without retyping its repo or re-downloading it. A downloaded file that is a preset's quant stays under that preset, while other quants of the same repo get their own entries. A downloaded entry is passed to `llama-server` as `-hf / -hff ` so the exact cached quant is reused; a first-time downloaded entry defaults to an 8192-token context. When the entry is the running model, its repo and file arguments are kept as they were written. - **Custom** takes a HuggingFace GGUF repo, optionally a specific file, a context size, a GPU-layer count, and extra server flags. Those extra flags are split on whitespace, so a quoted value with spaces will not survive. @@ -170,7 +173,7 @@ Shows the Bearer key for the OpenAI-compatible API interface. Removes one downloaded model to reclaim disk. - **What it changes:** deletes the chosen `models----` folder from `/data/models` — every quantization downloaded from that repo goes with it. The form lists the cached repos with their size on disk, plus any loose `*.gguf` files left by older builds; it never takes a free-form path, and nothing is preselected. -- **Models in use cannot be deleted.** The main and speculative draft repos configured in `serveArgs` are disabled in the form and refused if submitted. Repeated HuggingFace options use the last value, matching llama-server. llama-server holds these models open, so the space would not come back until a restart, and the restart would download them again. Switch models with Set Model first. +- **Models in use cannot be deleted.** The main and speculative draft repos the server is started with are disabled in the form and refused if submitted. Repeated HuggingFace options use the last value, matching llama-server. llama-server holds these models open, so the space would not come back until a restart, and the restart would download them again. Switch models with Set Model first. - **Repeat safety:** fails with an error if the chosen model is no longer in the cache, rather than reporting success. - **Outputs:** the repo removed and the space freed. - **Not reversible**, but not destructive either — the model is re-downloaded if selected again. @@ -218,7 +221,7 @@ The `main` and `public` volumes are backed up — `sdk.Backups.ofVolumes('main', 8. **Models are excluded from backups.** After a restore, the selected model downloads again on first start. 9. **Downloaded models are listed by repo and file.** A cached file matching a curated preset's quant is not duplicated; other quants from the same repo remain separate entries. Settings are remembered per model, so deleting a model with Delete Model Cache and downloading it again keeps them. 10. **Saved inference states are upstream-version-specific.** Custom `--slot-save-path` caches may need to be recreated after an update; the package does not convert them. This does not affect downloaded GGUF weights or `store.json`. -11. **A model's HuggingFace repo must stay public.** If its publisher withdraws or gates it, `llama-server` logs `get_repo_commit: error: GET failed (401)` and fails to start unless that model's weights are already cached. Choose another preset or a public repo in Set Model. +11. **A Custom or downloaded model's HuggingFace repo must stay public.** If its publisher withdraws or gates it, `llama-server` logs `get_repo_commit: error: GET failed (401)` and fails to start unless that model's weights are already cached. Choose another model in Set Model. Presets are moved to a public repo by a package update instead. --- diff --git a/UPDATING.md b/UPDATING.md index bb8cfe9..5385619 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -75,4 +75,4 @@ Map the build tag `bNNNN` to the version `NNNN:`, keeping the complete done ``` - For a failing preset, point `hfRepo` at a public, ungated repo carrying the same model at the same quant, preferring the model publisher's own GGUF repo, and migrate a saved selection of the old repo that has no cached weights onto the new one, as version `12110:1` does. + For a failing preset, point `hfRepo` at a public, ungated repo carrying the same model at the same quant, preferring the model publisher's own GGUF repo, and add the old `repo:QUANT` to the preset's `formerRepos`. Saved selections follow on their next start; no migration is needed. diff --git a/startos/actions/deleteModelCache.ts b/startos/actions/deleteModelCache.ts index c79011e..1ff5667 100644 --- a/startos/actions/deleteModelCache.ts +++ b/startos/actions/deleteModelCache.ts @@ -7,10 +7,16 @@ import { entryLabel, formatBytes, listCacheEntries, + listCachedModels, repoFolderName, } from '../modelCache' import { sdk } from '../sdk' -import { hfDraftRepoFlags, hfRepoFlags, lastOptionValue } from '../utils' +import { + hfDraftRepoFlags, + hfRepoFlags, + lastOptionValue, + serveArgsOf, +} from '../utils' const { InputSpec, Value } = sdk @@ -18,7 +24,8 @@ const { InputSpec, Value } = sdk // as in llama-server. It keeps them open, so deleting one would free nothing // until a restart, which downloads it again. async function inUseEntries(): Promise> { - const serveArgs = (await storeJson.read((s) => s?.serveArgs).once()) ?? [] + const serveArgs = + serveArgsOf(await storeJson.read().once(), await listCachedModels()) ?? [] const repos = [hfRepoFlags, hfDraftRepoFlags] .map((flags) => lastOptionValue(serveArgs, flags)?.split(':')[0]) .filter((repo): repo is string => Boolean(repo)) diff --git a/startos/actions/presets.ts b/startos/actions/presets.ts index 2056720..475507d 100644 --- a/startos/actions/presets.ts +++ b/startos/actions/presets.ts @@ -7,6 +7,8 @@ export type ModelPreset = { hfRepo: string /** Optional explicit GGUF filename — overrides the implicit quant tag. */ hfFile?: string + /** Repos this preset served before, still used when their weights are cached. */ + formerRepos?: string[] /** Quantized weights size plus headroom (KV cache, activations) in GiB. */ minMemoryGB: number /** Conservative default context window. */ @@ -36,6 +38,7 @@ export const models: ModelPreset[] = [ id: 'qwen25-7b', displayName: 'Qwen2.5 7B Instruct', hfRepo: 'Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M', + formerRepos: ['unsloth/Qwen2.5-7B-Instruct-GGUF:Q4_K_M'], minMemoryGB: 6, defaultCtx: 8192, }, @@ -43,6 +46,7 @@ export const models: ModelPreset[] = [ id: 'llama-31-8b', displayName: 'Llama 3.1 8B Instruct', hfRepo: 'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M', + formerRepos: ['unsloth/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M'], minMemoryGB: 8, defaultCtx: 8192, }, @@ -50,6 +54,7 @@ export const models: ModelPreset[] = [ id: 'qwen25-14b', displayName: 'Qwen2.5 14B Instruct', hfRepo: 'Qwen/Qwen2.5-14B-Instruct-GGUF:Q4_K_M', + formerRepos: ['unsloth/Qwen2.5-14B-Instruct-GGUF:Q4_K_M'], minMemoryGB: 12, defaultCtx: 8192, }, @@ -71,6 +76,7 @@ export const models: ModelPreset[] = [ id: 'qwen25-32b', displayName: 'Qwen2.5 32B Instruct', hfRepo: 'Qwen/Qwen2.5-32B-Instruct-GGUF:Q4_K_M', + formerRepos: ['unsloth/Qwen2.5-32B-Instruct-GGUF:Q4_K_M'], minMemoryGB: 24, defaultCtx: 8192, }, diff --git a/startos/actions/setModel.ts b/startos/actions/setModel.ts index 848e5cf..3c076cc 100644 --- a/startos/actions/setModel.ts +++ b/startos/actions/setModel.ts @@ -1,20 +1,17 @@ import { T } from '@start9labs/start-sdk' import { i18n } from '../i18n' import { sdk } from '../sdk' -import { storeJson } from '../fileModels/store.json' +import { storeJson, type ModelRef } from '../fileModels/store.json' import { detectHardware } from '../hardware' import { listCachedModels, + parseTarget, repoFolderName, + targetFile, type CachedModel, } from '../modelCache' -import { - hfFileFlags, - hfRepoFlags, - isGpuVariant, - lastOptionValue, -} from '../utils' -import { models, type ModelPreset } from './presets' +import { isGpuVariant, matchingPreset, sameRef } from '../utils' +import { models } from './presets' const { InputSpec, Value, Variants } = sdk @@ -25,75 +22,23 @@ const defaultNgl = 999 const cachedId = (repo: string, file: string) => `${cachedPrefix}${repoFolderName(repo)}:${file}` -type ServeTarget = { repo: string; quant?: string; file?: string } - type ModelSettings = { ctx: number; ngl: number; extraArgs?: string } -type SavedSettings = ModelSettings & { hfRepo: string; hfFile?: string } +type SavedSettings = ModelSettings & ModelRef type Store = NonNullable>> const readStore = (effects: T.Effects) => storeJson.read().const(effects) -// `repo:QUANT` plus an optional explicit file, as given to `-hf`/`-hff`. -function parseTarget(hfRepo: string, hfFile?: string): ServeTarget { - const [repo, quant] = hfRepo.split(':') - return { repo, quant: quant || undefined, file: hfFile || undefined } -} - -const presetTarget = (model: ModelPreset) => - parseTarget(model.hfRepo, model.hfFile) - -// The repo, optional quant tag, and optional explicit file the daemon was last -// started with. Custom entries are written as `repo:QUANT` with no `-hff`, so -// the quant tag is what identifies the running file. -function serveTarget(store: Store | null): ServeTarget | null { - const serveArgs = store?.serveArgs ?? [] - const repoArg = lastOptionValue(serveArgs, hfRepoFlags) - if (!repoArg) return null - return parseTarget(repoArg, lastOptionValue(serveArgs, hfFileFlags)) -} - -// The cached file the target refers to. An explicit `-hff` wins; otherwise the -// quant tag matches a full token, excluding BF16 for F16, as llama-server -// resolves `repo:QUANT` (find_best_model in -// common/download.cpp). Without a tag, only a single cached file resolves. -function targetFile( - target: ServeTarget, - cached: CachedModel[], -): string | undefined { - if (target.file) return target.file - const files = cached.filter((c) => c.repo === target.repo).map((c) => c.file) - if (target.quant) { - const tag = target.quant.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - const pattern = new RegExp(`(^|[-./])${tag}[.-]`, 'i') - return files.find((f) => pattern.test(f)) - } - return files.length === 1 ? files[0] : undefined -} - -// Whether two targets name the same weights: the same cached file once both -// resolve to one, otherwise the same quant tag with no explicit file. -function sameModel(a: ServeTarget, b: ServeTarget, cached: CachedModel[]) { - if (a.repo !== b.repo) return false - const fileA = targetFile(a, cached) - const fileB = targetFile(b, cached) - if (fileA && fileB) return fileA === fileB - return ( - !a.file && - !b.file && - (a.quant ?? '').toLowerCase() === (b.quant ?? '').toLowerCase() - ) -} - -function matchingPreset(target: ServeTarget, cached: CachedModel[]) { - return models.find((model) => sameModel(target, presetTarget(model), cached)) -} +const cachedRef = (c: CachedModel): ModelRef => ({ + hfRepo: c.repo, + hfFile: c.file, +}) // The settings this model was last run with. Stores written before // `modelSettings` existed only have the last Custom submission. function settingsFor( - target: ServeTarget, + ref: ModelRef, store: Store | null, cached: CachedModel[], ): ModelSettings | undefined { @@ -101,9 +46,7 @@ function settingsFor( ...(store?.modelSelection?.custom ? [store.modelSelection.custom] : []), ...(store?.modelSettings ?? []), ] - const saved = candidates - .filter((s) => sameModel(target, parseTarget(s.hfRepo, s.hfFile), cached)) - .pop() + const saved = candidates.filter((s) => sameRef(s, ref, cached)).pop() return saved && { ctx: saved.ctx, ngl: saved.ngl, extraArgs: saved.extraArgs } } @@ -112,10 +55,14 @@ function settingsFor( // entry, so the running model shows up once rather than as a duplicate next to // a Custom. function inUseVariantId( - target: ServeTarget | null, + ref: ModelRef | undefined, cached: CachedModel[], ): string | null { - if (!target) return null + if (ref?.preset) { + return models.some((m) => m.id === ref.preset) ? ref.preset : null + } + if (!ref?.hfRepo) return null + const target = parseTarget(ref.hfRepo, ref.hfFile) const preset = matchingPreset(target, cached) if (preset) return preset.id const file = targetFile(target, cached) @@ -208,7 +155,7 @@ const inputSpec = InputSpec.of({ : c.repo, spec: InputSpec.of( settingsFields( - settingsFor(c, store, allCached) ?? { + settingsFor(cachedRef(c), store, allCached) ?? { ctx: cachedCtx, ngl: defaultNgl, }, @@ -225,7 +172,7 @@ const inputSpec = InputSpec.of({ name: i18n(m.displayName), spec: InputSpec.of( settingsFields( - settingsFor(presetTarget(m), store, allCached) ?? { + settingsFor({ preset: m.id }, store, allCached) ?? { ctx: m.defaultCtx, ngl: defaultNgl, }, @@ -240,7 +187,7 @@ const inputSpec = InputSpec.of({ // The running model stays selectable so its settings can be changed; // submitting it unchanged writes the same arguments and does not restart. - const inUseId = inUseVariantId(serveTarget(store), allCached) + const inUseId = inUseVariantId(store?.model, allCached) const enabledIds = new Set([ ...enabledPresets.map((m) => m.id), ...cachedVariants.map(([id]) => id as string), @@ -279,19 +226,14 @@ const settingsValue = (s: ModelSettings) => ({ extraArgs: s.extraArgs ?? null, }) -function serveArgsFor( - hfRepo: string, - hfFile: string | undefined, - settings: ModelSettings, -): string[] { - const serveArgs = ['-hf', hfRepo] - if (hfFile) serveArgs.push('-hff', hfFile) - if (settings.ctx > 0) serveArgs.push('-c', String(settings.ctx)) - if (isGpuVariant) serveArgs.push('-ngl', String(settings.ngl)) +function settingsArgsFor(settings: ModelSettings): string[] { + const args: string[] = [] + if (settings.ctx > 0) args.push('-c', String(settings.ctx)) + if (isGpuVariant) args.push('-ngl', String(settings.ngl)) if (settings.extraArgs) { - serveArgs.push(...settings.extraArgs.split(/\s+/).filter(Boolean)) + args.push(...settings.extraArgs.split(/\s+/).filter(Boolean)) } - return serveArgs + return args } export const setModel = sdk.Action.withInput( @@ -315,13 +257,13 @@ export const setModel = sdk.Action.withInput( async ({ effects }) => { const store = await readStore(effects) const cached = await listCachedModels() - const target = serveTarget(store) - const inUseId = inUseVariantId(target, cached) + const running = store?.model + const inUseId = inUseVariantId(running, cached) const saved = store?.modelSelection // Keep the Custom fields around so switching to Custom is still prefilled. const other = saved?.custom ? { other: { custom: saved.custom } } : {} - if (target && inUseId) { - const settings = settingsFor(target, store, cached) + if (running && inUseId) { + const settings = settingsFor(running, store, cached) return { config: { selection: inUseId, @@ -335,10 +277,10 @@ export const setModel = sdk.Action.withInput( if (selection === 'custom') { return { config: { selection, value: saved.custom ?? {} } } } - const preset = models.find((m) => m.id === selection) - const selected = preset - ? presetTarget(preset) - : cached.find((c) => cachedId(c.repo, c.file) === selection) + const match = cached.find((c) => cachedId(c.repo, c.file) === selection) + const selected = models.some((m) => m.id === selection) + ? { preset: selection } + : match && cachedRef(match) if (!selected) return {} const settings = settingsFor(selected, store, cached) return { @@ -354,61 +296,60 @@ export const setModel = sdk.Action.withInput( const config = input.config const store = await storeJson.read().once() const cached = await listCachedModels() - const running = serveTarget(store) + const running = store?.model const settings: ModelSettings = { ctx: config.value.ctx, ngl: config.value.ngl, extraArgs: config.value.extraArgs?.trim() || undefined, } - let hfRepo: string - let hfFile: string | undefined + let model: ModelRef if (config.selection === 'custom') { - hfRepo = config.value.hfRepo.trim() - hfFile = config.value.hfFile?.trim() || undefined - } else { - let target: ServeTarget - if (config.selection.startsWith(cachedPrefix)) { - const match = cached.find( - (c) => cachedId(c.repo, c.file) === config.selection, + model = { + hfRepo: config.value.hfRepo.trim(), + hfFile: config.value.hfFile?.trim() || undefined, + } + } else if (config.selection.startsWith(cachedPrefix)) { + const match = cached.find( + (c) => cachedId(c.repo, c.file) === config.selection, + ) + if (!match) { + throw new Error( + i18n('That downloaded model is no longer in the cache.'), ) - if (!match) { - throw new Error( - i18n('That downloaded model is no longer in the cache.'), - ) - } - target = match - } else { - const preset = models.find((m) => m.id === config.selection) - if (!preset) { - throw new Error(`Unknown preset: ${config.selection}`) - } - target = presetTarget(preset) } - // Already the running model: keep the repo and file arguments as they - // were written, so unchanged settings yield identical serveArgs and no - // restart. - if (running && sameModel(running, target, cached)) target = running - hfRepo = target.quant ? `${target.repo}:${target.quant}` : target.repo - hfFile = target.file + model = cachedRef(match) + } else { + if (!models.some((m) => m.id === config.selection)) { + throw new Error(`Unknown preset: ${config.selection}`) + } + model = { preset: config.selection } } + // Already the running model: keep it as it was saved, so unchanged + // settings write identical values and do not restart. + if (running && sameRef(running, model, cached)) model = running - const newTarget = parseTarget(hfRepo, hfFile) - const modelSettings: SavedSettings[] = [ - ...(store?.modelSettings ?? []).filter( - (s) => !sameModel(parseTarget(s.hfRepo, s.hfFile), newTarget, cached), - ), - { hfRepo, hfFile, ...settings }, - ] + // Every key is written so a preset and a repo never mix in the merge. + const modelRef = { + preset: model.preset, + hfRepo: model.hfRepo, + hfFile: model.hfFile, + } await storeJson.merge(effects, { - serveArgs: serveArgsFor(hfRepo, hfFile, settings), + model: modelRef, + settingsArgs: settingsArgsFor(settings), modelSelection: { selection: config.selection, custom: - config.selection === 'custom' - ? { hfRepo, hfFile, ...settings } + config.selection === 'custom' && model.hfRepo + ? { hfRepo: model.hfRepo, hfFile: model.hfFile, ...settings } : store?.modelSelection?.custom, }, - modelSettings, + modelSettings: [ + ...(store?.modelSettings ?? []).filter( + (s) => !sameRef(s, model, cached), + ), + { ...modelRef, ...settings }, + ], }) }, ) diff --git a/startos/fileModels/store.json.ts b/startos/fileModels/store.json.ts index d17a596..fb04618 100644 --- a/startos/fileModels/store.json.ts +++ b/startos/fileModels/store.json.ts @@ -1,7 +1,19 @@ import { FileHelper, z } from '@start9labs/start-sdk' import { sdk } from '../sdk' +// A preset is saved by id and resolved against `presets.ts` at start; any +// other model by its repo and optional file. +const modelRef = { + preset: z.string().optional(), + hfRepo: z.string().optional(), + hfFile: z.string().optional(), +} + const shape = z.looseObject({ + model: z.looseObject(modelRef).optional().catch(undefined), + // The server flags after the model's own: context, GPU layers, extras. + settingsArgs: z.array(z.string()).optional().catch(undefined), + // Model and settings flags together, as stores before 12110:1 saved them. serveArgs: z.array(z.string()).optional().catch(undefined), uiPassword: z.string().optional().catch(undefined), modelSelection: z @@ -22,8 +34,7 @@ const shape = z.looseObject({ modelSettings: z .array( z.looseObject({ - hfRepo: z.string(), - hfFile: z.string().optional(), + ...modelRef, ctx: z.number(), ngl: z.number(), extraArgs: z.string().optional(), @@ -33,6 +44,8 @@ const shape = z.looseObject({ .catch(undefined), }) +export type ModelRef = { preset?: string; hfRepo?: string; hfFile?: string } + export const storeJson = FileHelper.json( { base: sdk.volumes.main, subpath: 'store.json' }, shape, diff --git a/startos/init/initializeService.ts b/startos/init/initializeService.ts index cc94bc2..219d3db 100644 --- a/startos/init/initializeService.ts +++ b/startos/init/initializeService.ts @@ -4,7 +4,7 @@ import { credentialsJson } from '../fileModels/credentials.json' import { storeJson } from '../fileModels/store.json' import { i18n } from '../i18n' import { sdk } from '../sdk' -import { generateApiKey } from '../utils' +import { generateApiKey, refTarget } from '../utils' // Runs on every init (install, update, restore, and plain restart), and // re-runs reactively when the watched files change. @@ -30,9 +30,10 @@ export const initializeService = sdk.setupOnInit(async (effects) => { } // Prompt for a model whenever none is selected — covers first install and - // guards against the selection being cleared from store.json. - const serveArgs = await storeJson.read((s) => s?.serveArgs).const(effects) - if (!serveArgs || serveArgs.length === 0) { + // guards against the selection being cleared from store.json or naming a + // preset that no longer exists. + const model = await storeJson.read((s) => s?.model).const(effects) + if (!refTarget(model, [])) { await sdk.action.createOwnTask(effects, setModel, 'critical', { reason: i18n('Select which AI model llama.cpp should serve'), }) diff --git a/startos/main.ts b/startos/main.ts index 74891c6..ebfe13b 100644 --- a/startos/main.ts +++ b/startos/main.ts @@ -1,12 +1,18 @@ import { i18n } from './i18n' import { sdk } from './sdk' import { storeJson } from './fileModels/store.json' -import { apiPort } from './utils' +import { listCachedModels } from './modelCache' +import { apiPort, serveArgsOf } from './utils' export const main = sdk.setupMain(async ({ effects }) => { console.info(i18n('Starting llama.cpp!')) - const serveArgs = await storeJson.read((s) => s?.serveArgs).const(effects) + const serveArgs = serveArgsOf( + await storeJson + .read((s) => ({ model: s?.model, settingsArgs: s?.settingsArgs })) + .const(effects), + await listCachedModels(), + ) const subcontainer = sdk.SubContainer.of( effects, diff --git a/startos/modelCache.ts b/startos/modelCache.ts index 79ce7e1..227fe6c 100644 --- a/startos/modelCache.ts +++ b/startos/modelCache.ts @@ -56,6 +56,55 @@ export async function listCacheEntries(): Promise< export type CachedModel = { repo: string; file: string } +export type ServeTarget = { repo: string; quant?: string; file?: string } + +// `repo:QUANT` plus an optional explicit file, as given to `-hf`/`-hff`. +export function parseTarget(hfRepo: string, hfFile?: string): ServeTarget { + const [repo, quant] = hfRepo.split(':') + return { repo, quant: quant || undefined, file: hfFile || undefined } +} + +// The cached file the target refers to. An explicit `-hff` wins; otherwise the +// quant tag matches a full token, excluding BF16 for F16, as llama-server +// resolves `repo:QUANT` (find_best_model in +// common/download.cpp). Without a tag, only a single cached file resolves. +export function targetFile( + target: ServeTarget, + cached: CachedModel[], +): string | undefined { + if (target.file) return target.file + const files = cached.filter((c) => c.repo === target.repo).map((c) => c.file) + if (target.quant) { + const tag = target.quant.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + const pattern = new RegExp(`(^|[-./])${tag}[.-]`, 'i') + return files.find((f) => pattern.test(f)) + } + return files.length === 1 ? files[0] : undefined +} + +export function isCached(target: ServeTarget, cached: CachedModel[]) { + const file = targetFile(target, cached) + return cached.some((c) => c.repo === target.repo && c.file === file) +} + +// Whether two targets name the same weights: the same cached file once both +// resolve to one, otherwise the same quant tag with no explicit file. +export function sameModel( + a: ServeTarget, + b: ServeTarget, + cached: CachedModel[], +) { + if (a.repo !== b.repo) return false + const fileA = targetFile(a, cached) + const fileB = targetFile(b, cached) + if (fileA && fileB) return fileA === fileB + return ( + !a.file && + !b.file && + (a.quant ?? '').toLowerCase() === (b.quant ?? '').toLowerCase() + ) +} + function isModelStart(file: string): boolean { if (!file.endsWith('.gguf')) return false const name = basename(file) diff --git a/startos/utils.ts b/startos/utils.ts index f982a70..6a69729 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -1,4 +1,13 @@ import { utils } from '@start9labs/start-sdk' +import { models, type ModelPreset } from './actions/presets' +import type { ModelRef } from './fileModels/store.json' +import { + isCached, + parseTarget, + sameModel, + type CachedModel, + type ServeTarget, +} from './modelCache' export const apiPort = 8080 @@ -37,3 +46,68 @@ export function lastOptionValue(args: string[], flags: string[]) { } return value } + +// Every repo the preset has served, current first. +const presetTargets = (preset: ModelPreset) => [ + parseTarget(preset.hfRepo, preset.hfFile), + ...(preset.formerRepos ?? []).map((repo) => parseTarget(repo)), +] + +// The current repo, unless only a former one has the weights cached. +function presetTarget(preset: ModelPreset, cached: CachedModel[]) { + const [current, ...former] = presetTargets(preset) + if (isCached(current, cached)) return current + return former.find((t) => isCached(t, cached)) ?? current +} + +export const matchingPreset = (target: ServeTarget, cached: CachedModel[]) => + models.find((m) => presetTargets(m).some((t) => sameModel(target, t, cached))) + +export function refTarget( + ref: ModelRef | null | undefined, + cached: CachedModel[], +): ServeTarget | undefined { + if (ref?.preset) { + const preset = models.find((m) => m.id === ref.preset) + return preset && presetTarget(preset, cached) + } + return ref?.hfRepo ? parseTarget(ref.hfRepo, ref.hfFile) : undefined +} + +// Whether two saved refs name the same model: a preset matches its own id +// and any repo target that resolves to it. +export function sameRef(a: ModelRef, b: ModelRef, cached: CachedModel[]) { + if (a.preset || b.preset) { + const [preset, other] = a.preset ? [a, b] : [b, a] + if (other.preset) return other.preset === preset.preset + return ( + !!other.hfRepo && + matchingPreset(parseTarget(other.hfRepo, other.hfFile), cached)?.id === + preset.preset + ) + } + return ( + !!a.hfRepo && + !!b.hfRepo && + sameModel( + parseTarget(a.hfRepo, a.hfFile), + parseTarget(b.hfRepo, b.hfFile), + cached, + ) + ) +} + +const targetArgs = (target: ServeTarget) => [ + '-hf', + target.quant ? `${target.repo}:${target.quant}` : target.repo, + ...(target.file ? ['-hff', target.file] : []), +] + +// The llama-server arguments the saved model and settings resolve to. +export function serveArgsOf( + store: { model?: ModelRef; settingsArgs?: string[] } | null | undefined, + cached: CachedModel[], +) { + const target = refTarget(store?.model, cached) + return target && [...targetArgs(target), ...(store?.settingsArgs ?? [])] +} diff --git a/startos/versions/current.ts b/startos/versions/current.ts index 4cb1692..bdaf8c8 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,15 +1,7 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' -import { storeJson } from '../fileModels/store.json' -import { listCachedModels } from '../modelCache' -import { hfRepoFlags, lastOptionValue } from '../utils' - -const withdrawnRepos: Record = { - 'unsloth/Qwen2.5-7B-Instruct-GGUF': 'Qwen/Qwen2.5-7B-Instruct-GGUF', - 'unsloth/Qwen2.5-14B-Instruct-GGUF': 'Qwen/Qwen2.5-14B-Instruct-GGUF', - 'unsloth/Qwen2.5-32B-Instruct-GGUF': 'Qwen/Qwen2.5-32B-Instruct-GGUF', - 'unsloth/Meta-Llama-3.1-8B-Instruct-GGUF': - 'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF', -} +import { storeJson, type ModelRef } from '../fileModels/store.json' +import { listCachedModels, parseTarget } from '../modelCache' +import { hfFileFlags, hfRepoFlags, matchingPreset } from '../utils' export const current = VersionInfo.of({ version: '12110:1', @@ -27,19 +19,32 @@ export const current = VersionInfo.of({ }, migrations: { up: async ({ effects }) => { - const serveArgs = await storeJson.read((s) => s?.serveArgs).once() - const repoArg = serveArgs && lastOptionValue(serveArgs, hfRepoFlags) - if (!repoArg) return - const [repo, quant] = repoArg.split(':') - const replacement = withdrawnRepos[repo] - if (!replacement) return - // llama-server falls back to cached weights when the repo lookup fails. - if ((await listCachedModels()).some((c) => c.repo === repo)) return - const i = serveArgs.lastIndexOf(repoArg) - await storeJson.merge(effects, { - serveArgs: serveArgs.map((arg, j) => - j === i ? (quant ? `${replacement}:${quant}` : replacement) : arg, - ), + const cached = await listCachedModels() + const toRef = (hfRepo: string, hfFile?: string): ModelRef => { + const preset = matchingPreset(parseTarget(hfRepo, hfFile), cached) + return preset ? { preset: preset.id } : { hfRepo, hfFile } + } + await storeJson.update(effects, (store) => { + if (!store) return null + const { serveArgs = [], ...rest } = store + // Every earlier release wrote `-hf [-hff ]` first. + const modelEnd = hfFileFlags.includes(serveArgs[2]) ? 4 : 2 + const hasModel = hfRepoFlags.includes(serveArgs[0]) && !!serveArgs[1] + return { + ...rest, + model: hasModel + ? toRef(serveArgs[1], modelEnd === 4 ? serveArgs[3] : undefined) + : rest.model, + settingsArgs: hasModel + ? serveArgs.slice(modelEnd) + : rest.settingsArgs, + modelSettings: store.modelSettings?.map( + ({ preset, hfRepo, hfFile, ...settings }) => ({ + ...(hfRepo ? toRef(hfRepo, hfFile) : { preset }), + ...settings, + }), + ), + } }) }, down: IMPOSSIBLE, From 93e47b7e733a8047582998a52425f0559fd85e17 Mon Sep 17 00:00:00 2001 From: Matt Hill <9935159+MattDHill@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:04:50 -0700 Subject: [PATCH 3/3] fix: keep preset ids through migration, honor Custom, protect every preset repo Adopts helix-white's proposal on #47, with the saved-id migration guarded to presets whose current or former repo is the saved one. - Migration: a legacy store whose modelSelection is a preset keeps that id even when its explicit -hff can't be matched to the quant without the cache (backups exclude it), and so does its settings entry. - Set Model: Custom saves the submitted target and a preset saves its id; only a downloaded-cache selection keeps the running raw ref. - Delete Model Cache protects every cached repo of the selected preset, since a later download can change which one a start would choose. - UPDATING.md's check requires private == false and gated == false and runs under POSIX sh. Verified on demo.local: the check passes the nine presets under dash and flags google/gemma-3-1b-it-qat-q4_0-gguf as gated. With qwen25-7b running from cached unsloth weights, Custom Qwen/...:Q4_K_M saved that raw ref and its Custom fields, and selecting the preset again saved {preset}. With both repos cached, Delete Model Cache disabled both and refused the unsloth one. A fresh 12110:0 with a hand-written legacy store (preset selected, unsloth repo with explicit -hff, empty cache) migrated to {preset: qwen25-7b} with its settings and started with -hf Qwen/Qwen2.5-7B-Instruct-GGUF:Q4_K_M -c 2048. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- UPDATING.md | 4 ++- instructions.md | 2 +- startos/actions/deleteModelCache.ts | 13 +++++++--- startos/actions/setModel.ts | 12 ++++++--- startos/utils.ts | 23 +++++++++-------- startos/versions/current.ts | 38 ++++++++++++++++++++++------- 7 files changed, 64 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 91af873..25dc48b 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ Shows the Bearer key for the OpenAI-compatible API interface. Removes one downloaded model to reclaim disk. - **What it changes:** deletes the chosen `models----` folder from `/data/models` — every quantization downloaded from that repo goes with it. The form lists the cached repos with their size on disk, plus any loose `*.gguf` files left by older builds; it never takes a free-form path, and nothing is preselected. -- **Models in use cannot be deleted.** The main and speculative draft repos the server is started with are disabled in the form and refused if submitted. Repeated HuggingFace options use the last value, matching llama-server. llama-server holds these models open, so the space would not come back until a restart, and the restart would download them again. Switch models with Set Model first. +- **Models in use cannot be deleted.** The main and speculative draft repos the server is started with are disabled in the form and refused if submitted. A selected preset also protects cached copies of its current and former repos until another model is selected: a download can change which repo a future start would choose without changing the running server. Repeated HuggingFace options use the last value, matching llama-server. llama-server holds these models open, so the space would not come back until a restart, and the restart would download them again. Switch models with Set Model first. - **Repeat safety:** fails with an error if the chosen model is no longer in the cache, rather than reporting success. - **Outputs:** the repo removed and the space freed. - **Not reversible**, but not destructive either — the model is re-downloaded if selected again. diff --git a/UPDATING.md b/UPDATING.md index 5385619..30632b5 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -70,7 +70,9 @@ Map the build tag `bNNNN` to the version `NNNN:`, keeping the complete ```sh grep -o "hfRepo: '[^']*'" startos/actions/presets.ts | cut -d"'" -f2 | while IFS=: read -r repo quant; do json=$(curl -sf "https://huggingface.co/api/models/$repo") || { echo "UNAVAILABLE $repo"; continue; } - jq -r '.siblings[].rfilename' <<<"$json" | grep -qi -- "$quant" \ + printf '%s' "$json" | jq -e '.private == false and .gated == false' >/dev/null \ + || { echo "NOT PUBLIC/UNGATED $repo"; continue; } + printf '%s' "$json" | jq -r '.siblings[].rfilename' | grep -qi -- "$quant" \ && echo "OK $repo:$quant" || echo "NO $quant FILE $repo" done ``` diff --git a/instructions.md b/instructions.md index 19a67e3..c2dda0f 100644 --- a/instructions.md +++ b/instructions.md @@ -48,7 +48,7 @@ curl -s -H "Authorization: Bearer " /v1/chat/co - **Set Model** — switch to a different preset, a model you already downloaded, or a custom GGUF. The form opens on the model you are running, with its settings filled in, so you can change its context size or flags and submit; submitting without changes does not restart anything. Each model remembers its own settings, so switching away and back keeps them. The service restarts with the new weights; uncached models download on this restart. - **Set UI Password** — generate a new web UI password (username stays `admin`). Use it for first-time setup or to rotate the password later; when rotating, it asks you to confirm, since saved logins stop working. - **API Key** — show the key for the OpenAI-compatible API interface. Turn on **Generate a new key** to replace it; clients outside StartOS then need the new key, and StartOS apps pick it up when they restart. -- **Delete Model Cache** — pick a downloaded model from the list, with its size, and remove it to reclaim disk space. The model you are currently running can't be deleted; switch to another one with Set Model first. A deleted model will be re-downloaded if you select it again. +- **Delete Model Cache** — pick a downloaded model from the list, with its size, and remove it to reclaim disk space. The model you are currently running can't be deleted; a selected preset protects its cached copies from both current and former publishers. Switch to another model with Set Model first. A deleted model will be re-downloaded if you select it again. ## Limitations diff --git a/startos/actions/deleteModelCache.ts b/startos/actions/deleteModelCache.ts index 1ff5667..69e89c4 100644 --- a/startos/actions/deleteModelCache.ts +++ b/startos/actions/deleteModelCache.ts @@ -6,6 +6,7 @@ import { cacheDir, entryLabel, formatBytes, + isCached, listCacheEntries, listCachedModels, repoFolderName, @@ -15,6 +16,7 @@ import { hfDraftRepoFlags, hfRepoFlags, lastOptionValue, + refTargets, serveArgsOf, } from '../utils' @@ -24,12 +26,17 @@ const { InputSpec, Value } = sdk // as in llama-server. It keeps them open, so deleting one would free nothing // until a restart, which downloads it again. async function inUseEntries(): Promise> { - const serveArgs = - serveArgsOf(await storeJson.read().once(), await listCachedModels()) ?? [] + const store = await storeJson.read().once() + const cached = await listCachedModels() + const serveArgs = serveArgsOf(store, cached) ?? [] const repos = [hfRepoFlags, hfDraftRepoFlags] .map((flags) => lastOptionValue(serveArgs, flags)?.split(':')[0]) .filter((repo): repo is string => Boolean(repo)) - return new Set(repos.map(repoFolderName)) + // Cache changes must not make a running preset's repo deletable. + const candidates = refTargets(store?.model) + .filter((target) => isCached(target, cached)) + .map((target) => target.repo) + return new Set([...repos, ...candidates].map(repoFolderName)) } const inputSpec = InputSpec.of({ diff --git a/startos/actions/setModel.ts b/startos/actions/setModel.ts index 3c076cc..79a0cdf 100644 --- a/startos/actions/setModel.ts +++ b/startos/actions/setModel.ts @@ -324,9 +324,15 @@ export const setModel = sdk.Action.withInput( } model = { preset: config.selection } } - // Already the running model: keep it as it was saved, so unchanged - // settings write identical values and do not restart. - if (running && sameRef(running, model, cached)) model = running + // Cached selections keep their running repo/file; Custom honors its input. + if ( + config.selection.startsWith(cachedPrefix) && + running && + !running.preset && + sameRef(running, model, cached) + ) { + model = running + } // Every key is written so a preset and a repo never mix in the merge. const modelRef = { diff --git a/startos/utils.ts b/startos/utils.ts index 6a69729..4e4c0e8 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -53,25 +53,24 @@ const presetTargets = (preset: ModelPreset) => [ ...(preset.formerRepos ?? []).map((repo) => parseTarget(repo)), ] -// The current repo, unless only a former one has the weights cached. -function presetTarget(preset: ModelPreset, cached: CachedModel[]) { - const [current, ...former] = presetTargets(preset) - if (isCached(current, cached)) return current - return former.find((t) => isCached(t, cached)) ?? current -} - export const matchingPreset = (target: ServeTarget, cached: CachedModel[]) => models.find((m) => presetTargets(m).some((t) => sameModel(target, t, cached))) +export function refTargets(ref: ModelRef | null | undefined): ServeTarget[] { + if (ref?.preset) { + const preset = models.find((m) => m.id === ref.preset) + return preset ? presetTargets(preset) : [] + } + return ref?.hfRepo ? [parseTarget(ref.hfRepo, ref.hfFile)] : [] +} + +// The current repo, unless only a former one has the weights cached. export function refTarget( ref: ModelRef | null | undefined, cached: CachedModel[], ): ServeTarget | undefined { - if (ref?.preset) { - const preset = models.find((m) => m.id === ref.preset) - return preset && presetTarget(preset, cached) - } - return ref?.hfRepo ? parseTarget(ref.hfRepo, ref.hfFile) : undefined + const targets = refTargets(ref) + return targets.find((t) => isCached(t, cached)) ?? targets[0] } // Whether two saved refs name the same model: a preset matches its own id diff --git a/startos/versions/current.ts b/startos/versions/current.ts index bdaf8c8..a032165 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -1,7 +1,8 @@ import { IMPOSSIBLE, VersionInfo } from '@start9labs/start-sdk' import { storeJson, type ModelRef } from '../fileModels/store.json' -import { listCachedModels, parseTarget } from '../modelCache' -import { hfFileFlags, hfRepoFlags, matchingPreset } from '../utils' +import { models } from '../actions/presets' +import { listCachedModels, parseTarget, sameModel } from '../modelCache' +import { hfFileFlags, hfRepoFlags, matchingPreset, refTargets } from '../utils' export const current = VersionInfo.of({ version: '12110:1', @@ -30,19 +31,38 @@ export const current = VersionInfo.of({ // Every earlier release wrote `-hf [-hff ]` first. const modelEnd = hfFileFlags.includes(serveArgs[2]) ? 4 : 2 const hasModel = hfRepoFlags.includes(serveArgs[0]) && !!serveArgs[1] + const legacyTarget = hasModel + ? parseTarget(serveArgs[1], modelEnd === 4 ? serveArgs[3] : undefined) + : undefined + // The saved preset id survives backups that omit cached weights. + const selectedPreset = models.find( + (m) => + m.id === store.modelSelection?.selection && + refTargets({ preset: m.id }).some( + (t) => t.repo === legacyTarget?.repo, + ), + ) + const model = legacyTarget + ? selectedPreset + ? { preset: selectedPreset.id } + : toRef(serveArgs[1], legacyTarget.file) + : rest.model return { ...rest, - model: hasModel - ? toRef(serveArgs[1], modelEnd === 4 ? serveArgs[3] : undefined) - : rest.model, + model, settingsArgs: hasModel ? serveArgs.slice(modelEnd) : rest.settingsArgs, modelSettings: store.modelSettings?.map( - ({ preset, hfRepo, hfFile, ...settings }) => ({ - ...(hfRepo ? toRef(hfRepo, hfFile) : { preset }), - ...settings, - }), + ({ preset, hfRepo, hfFile, ...settings }) => { + const ref = hfRepo ? toRef(hfRepo, hfFile) : { preset } + const isSelected = + hfRepo && + model && + legacyTarget && + sameModel(parseTarget(hfRepo, hfFile), legacyTarget, cached) + return { ...(isSelected ? model : ref), ...settings } + }, ), } })