diff --git a/README.md b/README.md index 25dc48b..7ae5b51 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Quant tags match whole tokens when identifying cached weights: `F16` does not se `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. +**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. Once the current repo is cached, `main.ts` deletes unused former repos' folders before starting; a folder that also holds another quant, or is the effective main or draft model's repo (including overrides in Extra arguments), is kept. A split model counts as cached only with every part on disk, so an interrupted download never displaces a complete copy. **No configuration file reaches the application.** Two environment variables are set, both redirecting caches onto the volume so downloaded weights survive a container rebuild: @@ -148,6 +148,8 @@ Chooses what the server runs — either a curated preset or a model of your own. - **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. +- **The form shows how much disk downloaded models use**, under the model list. +- **Delete other downloaded models**, off by default, removes every cache entry except the selected model and its draft model after saving the selection, as Delete Model Cache would one at a time. A selected preset keeps all its cached copies until its next start removes the superseded ones. - **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. ### Set UI Password diff --git a/instructions.md b/instructions.md index c2dda0f..fec0845 100644 --- a/instructions.md +++ b/instructions.md @@ -45,7 +45,7 @@ curl -s -H "Authorization: Bearer " /v1/chat/co ### Actions -- **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 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. Models you switch away from stay downloaded so switching back is instant; the form shows how much disk they use, and turning on **Delete other downloaded models** removes all of them except the one you select. - **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; 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. diff --git a/startos/actions/deleteModelCache.ts b/startos/actions/deleteModelCache.ts index 69e89c4..d59e48b 100644 --- a/startos/actions/deleteModelCache.ts +++ b/startos/actions/deleteModelCache.ts @@ -6,38 +6,16 @@ import { cacheDir, entryLabel, formatBytes, - isCached, listCacheEntries, listCachedModels, - repoFolderName, } from '../modelCache' import { sdk } from '../sdk' -import { - hfDraftRepoFlags, - hfRepoFlags, - lastOptionValue, - refTargets, - serveArgsOf, -} from '../utils' +import { cacheEntriesInUse } from '../utils' const { InputSpec, Value } = sdk -// Cache folders of the configured main and draft models, last flag winning -// 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 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)) - // 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 inUseEntries = async () => + cacheEntriesInUse(await storeJson.read().once(), await listCachedModels()) const inputSpec = InputSpec.of({ model: Value.dynamicSelect(async () => { diff --git a/startos/actions/setModel.ts b/startos/actions/setModel.ts index 79a0cdf..a7225dd 100644 --- a/startos/actions/setModel.ts +++ b/startos/actions/setModel.ts @@ -1,16 +1,26 @@ +import { rm } from 'node:fs/promises' +import { join } from 'node:path' import { T } from '@start9labs/start-sdk' import { i18n } from '../i18n' import { sdk } from '../sdk' import { storeJson, type ModelRef } from '../fileModels/store.json' import { detectHardware } from '../hardware' import { + cacheDir, + formatBytes, + listCacheEntries, listCachedModels, parseTarget, repoFolderName, targetFile, type CachedModel, } from '../modelCache' -import { isGpuVariant, matchingPreset, sameRef } from '../utils' +import { + cacheEntriesInUse, + isGpuVariant, + matchingPreset, + sameRef, +} from '../utils' import { models } from './presets' const { InputSpec, Value, Variants } = sdk @@ -139,6 +149,10 @@ const inputSpec = InputSpec.of({ // Anything already on disk can be selected again without re-downloading. // Preset files are left out because their entry is already in the list. const allCached = await listCachedModels() + const cacheBytes = (await listCacheEntries()).reduce( + (total, e) => total + e.bytes, + 0, + ) const cached = allCached.filter((c) => !matchingPreset(c, allCached)) // Label by repo alone when it has one cached file; append the file only // when a repo has several, where it is needed to tell them apart. @@ -211,12 +225,27 @@ const inputSpec = InputSpec.of({ `- ${i18n(m.displayName)}: ${i18n('needs about ${memory} GB of memory', { memory: m.minMemoryGB })}`, ), `- ${i18n('Custom')}: ${i18n('any HuggingFace GGUF model, with your own context size, GPU layers and server flags')}`, + ...(cacheBytes > 0 + ? [ + '', + i18n('Downloaded models use ${size} of disk.', { + size: formatBytes(cacheBytes), + }), + ] + : []), ].join('\n'), variants: Variants.of(variants), default: defaultId as string, disabled: disabledIds.length > 0 ? disabledIds : false, } }), + deleteOthers: Value.toggle({ + name: i18n('Delete other downloaded models'), + description: i18n( + 'Remove every downloaded model except the one selected here and its draft model, freeing their disk space. A deleted model downloads again if you select it later.', + ), + default: false, + }), }) // The settings as form values; the text field takes null, not undefined. @@ -340,9 +369,10 @@ export const setModel = sdk.Action.withInput( hfRepo: model.hfRepo, hfFile: model.hfFile, } + const settingsArgs = settingsArgsFor(settings) await storeJson.merge(effects, { model: modelRef, - settingsArgs: settingsArgsFor(settings), + settingsArgs, modelSelection: { selection: config.selection, custom: @@ -357,5 +387,12 @@ export const setModel = sdk.Action.withInput( { ...modelRef, ...settings }, ], }) + + if (input.deleteOthers) { + const keep = cacheEntriesInUse({ model: modelRef, settingsArgs }, cached) + for (const { name } of await listCacheEntries()) { + if (!keep.has(name)) await rm(join(cacheDir, name), { recursive: true }) + } + } }, ) diff --git a/startos/i18n/dictionaries/default.ts b/startos/i18n/dictionaries/default.ts index 0c1f624..2939d9a 100644 --- a/startos/i18n/dictionaries/default.ts +++ b/startos/i18n/dictionaries/default.ts @@ -2,6 +2,7 @@ export const DEFAULT_LANG = 'en_US' const dict = { // main.ts + 'Removed ${model}, which the selected preset no longer uses.': 64, 'Starting llama.cpp!': 0, 'llama.cpp API': 1, 'The llama.cpp API is ready': 2, @@ -34,6 +35,9 @@ const dict = { 'needs about ${memory} GB of memory': 47, 'any HuggingFace GGUF model, with your own context size, GPU layers and server flags': 48, 'That downloaded model is no longer in the cache.': 53, + 'Delete other downloaded models': 61, + 'Remove every downloaded model except the one selected here and its draft model, freeing their disk space. A deleted model downloads again if you select it later.': 62, + 'Downloaded models use ${size} of disk.': 63, // model preset labels 'Llama 3.2 1B Instruct': 22, diff --git a/startos/i18n/dictionaries/translations.ts b/startos/i18n/dictionaries/translations.ts index 3eb79d2..a6cc5d0 100644 --- a/startos/i18n/dictionaries/translations.ts +++ b/startos/i18n/dictionaries/translations.ts @@ -63,6 +63,10 @@ export default { 58: 'Clave de API', 59: 'Muestra la clave de la interfaz API compatible con OpenAI o genera una nueva.', 60: 'Envíe esta clave como "Authorization: Bearer " a la interfaz API compatible con OpenAI. En la mayoría de los clientes, establezca la URL base en la dirección de esa interfaz con /v1 añadido y pegue esto como clave de API.', + 61: 'Eliminar los demás modelos descargados', + 62: 'Elimina todos los modelos descargados excepto el seleccionado aquí y su modelo borrador, liberando su espacio en disco. Un modelo eliminado se vuelve a descargar si lo selecciona más adelante.', + 63: 'Los modelos descargados ocupan ${size} de disco.', + 64: 'Se eliminó ${model}, que el preset seleccionado ya no usa.', }, de_DE: { 0: 'Starte llama.cpp!', @@ -126,6 +130,10 @@ export default { 58: 'API-Schlüssel', 59: 'Zeigt den Schlüssel für die OpenAI-kompatible API-Schnittstelle an oder erzeugt einen neuen.', 60: 'Senden Sie diesen Schlüssel als „Authorization: Bearer “ an die OpenAI-kompatible API-Schnittstelle. In den meisten Clients setzen Sie die Basis-URL auf die Adresse dieser Schnittstelle mit angehängtem /v1 und fügen dies als API-Schlüssel ein.', + 61: 'Andere heruntergeladene Modelle löschen', + 62: 'Entfernt alle heruntergeladenen Modelle außer dem hier ausgewählten und seinem Entwurfsmodell und gibt ihren Speicherplatz frei. Ein gelöschtes Modell wird erneut heruntergeladen, wenn Sie es später auswählen.', + 63: 'Heruntergeladene Modelle belegen ${size} Speicherplatz.', + 64: '${model} wurde entfernt, da das ausgewählte Preset es nicht mehr verwendet.', }, pl_PL: { 0: 'Uruchamianie llama.cpp!', @@ -189,6 +197,10 @@ export default { 58: 'Klucz API', 59: 'Pokazuje klucz do interfejsu API zgodnego z OpenAI lub generuje nowy.', 60: 'Wysyłaj ten klucz jako „Authorization: Bearer ” do interfejsu API zgodnego z OpenAI. W większości klientów ustaw bazowy URL na adres tego interfejsu z dopisanym /v1 i wklej to jako klucz API.', + 61: 'Usuń pozostałe pobrane modele', + 62: 'Usuwa wszystkie pobrane modele oprócz wybranego tutaj i jego modelu szkicowego, zwalniając miejsce na dysku. Usunięty model zostanie pobrany ponownie, jeśli wybierzesz go później.', + 63: 'Pobrane modele zajmują ${size} na dysku.', + 64: 'Usunięto ${model}, którego wybrany preset już nie używa.', }, fr_FR: { 0: 'Démarrage de llama.cpp !', @@ -252,5 +264,9 @@ export default { 58: 'Clé d’API', 59: 'Affiche la clé de l’interface API compatible OpenAI, ou en génère une nouvelle.', 60: 'Envoyez cette clé sous la forme « Authorization: Bearer » à l’interface API compatible OpenAI. Dans la plupart des clients, définissez l’URL de base sur l’adresse de cette interface suivie de /v1 et collez ceci comme clé d’API.', + 61: 'Supprimer les autres modèles téléchargés', + 62: 'Supprime tous les modèles téléchargés sauf celui sélectionné ici et son modèle brouillon, libérant leur espace disque. Un modèle supprimé est retéléchargé si vous le sélectionnez plus tard.', + 63: 'Les modèles téléchargés occupent ${size} d’espace disque.', + 64: '${model} a été supprimé, car le préréglage sélectionné ne l’utilise plus.', }, } satisfies Record diff --git a/startos/main.ts b/startos/main.ts index ebfe13b..0287ee2 100644 --- a/startos/main.ts +++ b/startos/main.ts @@ -1,18 +1,34 @@ import { i18n } from './i18n' import { sdk } from './sdk' import { storeJson } from './fileModels/store.json' -import { listCachedModels } from './modelCache' -import { apiPort, serveArgsOf } from './utils' +import { rm } from 'node:fs/promises' +import { join } from 'node:path' +import { + cacheDir, + entryLabel, + listCachedModels, + readdirSafe, +} from './modelCache' +import { apiPort, serveArgsOf, supersededCopies } from './utils' export const main = sdk.setupMain(async ({ effects }) => { console.info(i18n('Starting llama.cpp!')) - const serveArgs = serveArgsOf( - await storeJson - .read((s) => ({ model: s?.model, settingsArgs: s?.settingsArgs })) - .const(effects), - await listCachedModels(), - ) + const store = await storeJson + .read((s) => ({ model: s?.model, settingsArgs: s?.settingsArgs })) + .const(effects) + const cached = await listCachedModels() + const onDisk = await readdirSafe(cacheDir) + for (const name of supersededCopies(store, cached)) { + if (!onDisk.includes(name)) continue + await rm(join(cacheDir, name), { recursive: true }) + console.info( + i18n('Removed ${model}, which the selected preset no longer uses.', { + model: entryLabel(name), + }), + ) + } + const serveArgs = serveArgsOf(store, cached) const subcontainer = sdk.SubContainer.of( effects, diff --git a/startos/modelCache.ts b/startos/modelCache.ts index 227fe6c..6e2efa5 100644 --- a/startos/modelCache.ts +++ b/startos/modelCache.ts @@ -1,5 +1,5 @@ import { lstat, readdir, stat } from 'node:fs/promises' -import { basename, join } from 'node:path' +import { basename, dirname, join } from 'node:path' import { sdk } from './sdk' // llama-server's LLAMA_CACHE (see main.ts), as seen from the action. @@ -119,6 +119,28 @@ function isModelStart(file: string): boolean { return !split || Number(split[2]) <= 1 || Number(split[1]) === 1 } +const isFile = (path: string) => + stat(path).then( + (info) => info.isFile(), + (e: NodeJS.ErrnoException) => { + if (e.code === 'ENOENT') return false + throw e + }, + ) + +// A split model counts only with every part on disk: an interrupted download +// leaves the first part without the rest. +async function isComplete(path: string) { + const split = basename(path).match(/^(.+-)00001-of-([0-9]{5})(\.gguf)$/i) + if (!split) return isFile(path) + const [, stem, total, ext] = split + for (let part = 1; part <= Number(total); part++) { + const name = `${stem}${String(part).padStart(5, '0')}-of-${total}${ext}` + if (!(await isFile(join(dirname(path), name)))) return false + } + return true +} + async function snapshotFiles( path: string, files: Set, @@ -131,16 +153,8 @@ async function snapshotFiles( const info = await lstat(child) if (info.isDirectory()) { await snapshotFiles(child, files, file) - } else if (isModelStart(file)) { - if (info.isFile()) { - files.add(file) - } else if (info.isSymbolicLink()) { - try { - if ((await stat(child)).isFile()) files.add(file) - } catch (e: any) { - if (e.code !== 'ENOENT') throw e - } - } + } else if (isModelStart(file) && (await isComplete(child))) { + files.add(file) } } } diff --git a/startos/utils.ts b/startos/utils.ts index 4e4c0e8..43e9e27 100644 --- a/startos/utils.ts +++ b/startos/utils.ts @@ -4,6 +4,7 @@ import type { ModelRef } from './fileModels/store.json' import { isCached, parseTarget, + repoFolderName, sameModel, type CachedModel, type ServeTarget, @@ -42,7 +43,11 @@ export const hfDraftRepoFlags = [ export function lastOptionValue(args: string[], flags: string[]) { let value: string | undefined for (let i = 0; i < args.length; i++) { - if (flags.includes(args[i])) value = args[++i] + // llama-server accepts underscores in long option names. + const flag = args[i].startsWith('--') + ? args[i].replaceAll('_', '-') + : args[i] + if (flags.includes(flag)) value = args[++i] } return value } @@ -110,3 +115,51 @@ export function serveArgsOf( const target = refTarget(store?.model, cached) return target && [...targetArgs(target), ...(store?.settingsArgs ?? [])] } + +type SavedModel = { model?: ModelRef; settingsArgs?: string[] } + +// Cache folders of the main and draft repos llama-server will load: the last +// flag wins, so an override in the extra arguments counts. +function effectiveCacheEntries( + store: SavedModel | null | undefined, + cached: CachedModel[], +) { + 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)) +} + +// Those, plus every cached repo of a selected preset, since a download can +// change which one the next start resolves to. +export function cacheEntriesInUse( + store: SavedModel | null | undefined, + cached: CachedModel[], +) { + const entries = effectiveCacheEntries(store, cached) + for (const target of refTargets(store?.model)) { + if (isCached(target, cached)) entries.add(repoFolderName(target.repo)) + } + return entries +} + +// Cache folders of a selected preset's former repos once its current repo is +// cached. A folder that also holds other files, or is loaded anyway, is kept. +export function supersededCopies( + store: SavedModel | null | undefined, + cached: CachedModel[], +) { + const [current, ...former] = refTargets(store?.model) + if (!store?.model?.preset || !current || !isCached(current, cached)) return [] + const inUse = effectiveCacheEntries(store, cached) + return former + .filter( + (target) => + !inUse.has(repoFolderName(target.repo)) && + cached + .filter((c) => c.repo === target.repo) + .every((c) => sameModel(c, target, cached)), + ) + .map((target) => repoFolderName(target.repo)) +} diff --git a/startos/versions/current.ts b/startos/versions/current.ts index a032165..a2be0f5 100644 --- a/startos/versions/current.ts +++ b/startos/versions/current.ts @@ -8,15 +8,15 @@ export const current = VersionInfo.of({ version: '12110:1', releaseNotes: { 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.', + 'Fixes downloading the Qwen2.5 7B, 14B and 32B and Llama 3.1 8B Instruct presets. A model you already downloaded keeps working unchanged.\n\nSet Model shows how much disk downloaded models use and can delete every model but the one selected.', 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.', + '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.\n\nEstablecer modelo muestra cuánto disco ocupan los modelos descargados y puede eliminar todos salvo el seleccionado.', 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.', + '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.\n\nModell festlegen zeigt, wie viel Speicherplatz heruntergeladene Modelle belegen, und kann alle außer dem ausgewählten löschen.', 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.', + 'Naprawia pobieranie presetów Qwen2.5 7B, 14B i 32B oraz Llama 3.1 8B Instruct. Już pobrany model działa dalej bez zmian.\n\nUstaw model pokazuje, ile miejsca na dysku zajmują pobrane modele, i może usunąć wszystkie poza wybranym.', 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.', + '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.\n\nDéfinir le modèle indique l’espace disque occupé par les modèles téléchargés et peut supprimer tous ceux autres que le modèle sélectionné.', }, migrations: { up: async ({ effects }) => {