From 0247f257fbcc571a83108862b541f445fae750b8 Mon Sep 17 00:00:00 2001 From: Pascal Linxweiler Date: Mon, 5 Oct 2026 23:10:53 +0200 Subject: [PATCH] Recommended files with a quant; floating selection bar Picking model weights in Add model or Download more also selects the files that usually go with them (chat template, MTP head, mmproj, ...), shown in a strip where each can be unchecked. Variants are matched by quant, otherwise the best single one; kinds already selected aren't added twice. Which kinds is set in Settings -> Downloads. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +- README.md | 3 +- src/app/(app)/[org]/[repo]/download-more.tsx | 36 +++++-- src/app/(app)/[org]/[repo]/files-tab.tsx | 1 + src/app/(app)/add-model-form.tsx | 52 +++++++--- src/app/(app)/layout.tsx | 10 +- src/app/(app)/settings/downloads/page.tsx | 10 ++ .../downloads/recommended-settings.tsx | 96 +++++++++++++++++++ src/app/(app)/settings/layout.tsx | 3 +- src/app/api/settings/downloads/route.ts | 22 +++++ src/components/labels.tsx | 27 +++++- src/components/recommended-strip.tsx | 63 ++++++++++++ src/hooks/use-recommended.ts | 43 +++++++++ src/lib/recommend.test.ts | 56 +++++++++++ src/lib/recommend.ts | 93 ++++++++++++++++++ src/lib/settings.ts | 17 ++++ 16 files changed, 514 insertions(+), 27 deletions(-) create mode 100644 src/app/(app)/settings/downloads/page.tsx create mode 100644 src/app/(app)/settings/downloads/recommended-settings.tsx create mode 100644 src/app/api/settings/downloads/route.ts create mode 100644 src/components/recommended-strip.tsx create mode 100644 src/hooks/use-recommended.ts create mode 100644 src/lib/recommend.test.ts create mode 100644 src/lib/recommend.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 4dbf711..d36a8fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,12 @@ step 1 (Hugging Face downloader) is released as a minor version. job runs `hf download` into the existing folder: hf 2.1.1 hashes files it didn't download itself, keeps those that match and downloads only missing or different ones. Other files in the folder are left alone. Jobs show the purpose "import". +- **Recommended files:** picking a quant (chip or checkbox) in Add model or Download more also + selects the files that usually go with it, shown in a "Recommended with your quant" strip where + each can be unchecked. They drop out again when you deselect the quant. Variants are matched: + the MTP head or mmproj with the same quant if there is one, otherwise the best single one (mmproj: + F16, BF16, Q8_0, F32); nothing is added if the model already has one of that kind. Which kinds + (default: chat template, MTP, vision) is set in the new **Settings → Downloads**. - Create tags in Settings (name and color), before any model uses them. - Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your existing tags with their colors, and "Manage tags…". @@ -59,7 +65,8 @@ step 1 (Hugging Face downloader) is released as a minor version. - Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP, mmproj or imatrix files. - Tags are no longer deleted automatically when no model uses them anymore; delete them in Settings. -- Settings has separate pages for **File labels** and **Tags**. +- Settings has separate pages for **File labels**, **Tags** and **Downloads**. +- The selection bar at the bottom of Add model is a floating card like the rest of the page. - Header: app icon, navigation with icons and the current page highlighted. ### Fixed diff --git a/README.md b/README.md index 01571fc..585c9fc 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,8 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname

- **Add model:** enter a repo ID like `unsloth/Qwen3-8B-GGUF` (or paste the URL), click a quant, and - **Add & download**. You can add tags right there. + **Add & download**. Files that belong with the quant (chat template, MTP head, vision projector) + are selected along with it; choose which kinds in Settings → Downloads. You can add tags right there. - **Search:** type anything: `unsloth qwen`, `q4_k_m`, `gemma`, `roleplay`. Every word has to match somewhere (repo, author, base model family, architecture, quant, tags). - **Filter:** combine Author, Family, Quant, Tag and Status filters. The URL keeps the filters, so diff --git a/src/app/(app)/[org]/[repo]/download-more.tsx b/src/app/(app)/[org]/[repo]/download-more.tsx index 3ddcacd..6a45d3c 100644 --- a/src/app/(app)/[org]/[repo]/download-more.tsx +++ b/src/app/(app)/[org]/[repo]/download-more.tsx @@ -5,9 +5,11 @@ import { useRouter } from "next/navigation"; import { useMemo, useState } from "react"; import { toast } from "sonner"; import { FileRoleBadge } from "@/components/labels"; +import { RecommendedStrip } from "@/components/recommended-strip"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Progress } from "@/components/ui/progress"; +import { useRecommended } from "@/hooks/use-recommended"; import { groupSplitFiles } from "@/lib/file-groups"; import { formatBytes, percent, shortSha } from "@/lib/format"; import { quantGroup } from "@/lib/selection"; @@ -26,6 +28,7 @@ export function FilesHeader({ localCount, localBytes, candidates, + selectedPaths, freeBytes, busy, hubMissing, @@ -37,6 +40,8 @@ export function FilesHeader({ localCount: number; localBytes: number; candidates: Candidate[]; + /** Files the model already has selected (no second mmproj/MTP is recommended). */ + selectedPaths: string[]; freeBytes: number | null; /** A download is queued/running; adding files has to wait. */ busy: boolean; @@ -61,13 +66,18 @@ export function FilesHeader({ return [...m.entries()].sort(([a], [b]) => a.localeCompare(b, undefined, { numeric: true })); }, [candidates]); + // Companions (template, MTP, mmproj, …) of newly picked model files come along. + const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended(candidates, picked, { have: selectedPaths }); + const chosen = useMemo(() => new Set([...picked, ...recActive]), [picked, recActive]); + // Split files are one entry; its checkbox selects all parts. const entries = useMemo(() => groupSplitFiles(candidates), [candidates]); - const pickedEntries = entries.filter((e) => e.parts.every((p) => picked.has(p.path))).length; - const pickedBytes = candidates.filter((c) => picked.has(c.path)).reduce((s, c) => s + c.size, 0); + const pickedEntries = entries.filter((e) => e.parts.every((p) => chosen.has(p.path))).length; + const pickedBytes = candidates.filter((c) => chosen.has(c.path)).reduce((s, c) => s + c.size, 0); const tooBig = freeBytes != null && pickedBytes > freeBytes; function toggle(paths: string[], on: boolean) { + setRecommendedOn(paths, on); setPicked((prev) => { const next = new Set(prev); for (const p of paths) { @@ -84,7 +94,7 @@ export function FilesHeader({ const res = await fetch(`/api/models/${modelId}/files`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ add: [...picked] }), + body: JSON.stringify({ add: [...chosen] }), }); const body = await res.json().catch(() => ({})); if (!res.ok) { @@ -94,6 +104,7 @@ export function FilesHeader({ toast.success(`${body.added} file${body.added === 1 ? "" : "s"} added, download queued`); setOpen(false); setPicked(new Set()); + resetRecommended(); router.refresh(); } finally { setSubmitting(false); @@ -165,10 +176,13 @@ export function FilesHeader({ )} + +
    {entries.map((e) => { const paths = e.parts.map((p) => p.path); - const on = paths.every((p) => picked.has(p)); + const on = paths.every((p) => chosen.has(p)); + const isRecommended = paths.every((p) => recAll.includes(p)); return (
  • @@ -202,10 +221,15 @@ export function FilesHeader({ )}
    - -
    diff --git a/src/app/(app)/[org]/[repo]/files-tab.tsx b/src/app/(app)/[org]/[repo]/files-tab.tsx index 88ca3ee..90cce00 100644 --- a/src/app/(app)/[org]/[repo]/files-tab.tsx +++ b/src/app/(app)/[org]/[repo]/files-tab.tsx @@ -155,6 +155,7 @@ export function FilesTab({ localCount={localEntries.length} localBytes={localBytes} candidates={others.map((f) => ({ path: f.path, size: f.size }))} + selectedPaths={selected.map((f) => f.path)} freeBytes={freeBytes} busy={busy} hubMissing={hubMissing} diff --git a/src/app/(app)/add-model-form.tsx b/src/app/(app)/add-model-form.tsx index 43a80d6..8642d78 100644 --- a/src/app/(app)/add-model-form.tsx +++ b/src/app/(app)/add-model-form.tsx @@ -2,9 +2,10 @@ import { XIcon } from "lucide-react"; import Link from "next/link"; -import { useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { toast } from "sonner"; import { FileRoleBadge } from "@/components/labels"; +import { RecommendedStrip } from "@/components/recommended-strip"; import { TagBadge } from "@/components/tag-badge"; import { TagPicker } from "@/components/tag-picker"; import { Badge } from "@/components/ui/badge"; @@ -14,6 +15,7 @@ import { Checkbox } from "@/components/ui/checkbox"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { useRecommended } from "@/hooks/use-recommended"; import { groupSplitFiles } from "@/lib/file-groups"; import { formatBytes, shortSha } from "@/lib/format"; import type { LookupResult } from "@/lib/hub/lookup"; @@ -57,6 +59,22 @@ export function AddModelForm({ const [submitting, setSubmitting] = useState(false); const [tags, setTags] = useState<{ name: string; color?: string | null }[]>([]); + const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]); + const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]); + + const repoFiles = useMemo(() => result?.files ?? [], [result]); + const isExcluded = useCallback((path: string) => matchesAny(path, excludePatterns), [excludePatterns]); + // Picked by checkbox or include pattern; recommended companions come on top. + const picked = useMemo( + () => repoFiles.filter((f) => (checked.has(f.path) || matchesAny(f.path, includePatterns)) && !isExcluded(f.path)).map((f) => f.path), + [repoFiles, checked, includePatterns, isExcluded], + ); + const { all: recAll, active: recActive, setOn: setRecommendedOn, reset: resetRecommended } = useRecommended( + repoFiles, + picked, + { isExcluded }, + ); + // Local files of the imported folder by path. const onDisk = useMemo(() => new Map((importFolder?.files ?? []).map((f) => [f.path, f.size])), [importFolder]); @@ -70,6 +88,7 @@ export function AddModelForm({ setRevision(r.revision); // Import: preselect every repo file that's already in the folder. setChecked(new Set(r.files.filter((f) => onDisk.has(f.path)).map((f) => f.path))); + resetRecommended(); setIncludeText(""); setExcludeText(""); setTags([]); @@ -90,23 +109,22 @@ export function AddModelForm({ // eslint-disable-next-line react-hooks/exhaustive-deps -- run once for the folder being imported }, [importFolder]); - const includePatterns = useMemo(() => parsePatternList(includeText), [includeText]); - const excludePatterns = useMemo(() => parsePatternList(excludeText), [excludeText]); const files = useMemo(() => { - if (!result) return []; - return result.files.map((f) => { + const pickedSet = new Set(picked); + return repoFiles.map((f) => { const byPattern = matchesAny(f.path, includePatterns); - const excluded = matchesAny(f.path, excludePatterns); + const excluded = isExcluded(f.path); return { ...f, group: quantGroup(f.path), byPattern, excluded, - selected: (checked.has(f.path) || byPattern) && !excluded, + recommended: recAll.includes(f.path), + selected: pickedSet.has(f.path) || recActive.has(f.path), }; }); - }, [result, checked, includePatterns, excludePatterns]); + }, [repoFiles, picked, includePatterns, isExcluded, recAll, recActive]); const groups = useMemo(() => { const m = new Map(); @@ -134,6 +152,7 @@ export function AddModelForm({ const notInRepo = importFolder ? importFolder.files.filter((f) => !repoPaths.has(f.path)).length : 0; function toggle(paths: string[], on: boolean) { + setRecommendedOn(paths, on); setChecked((prev) => { const next = new Set(prev); for (const path of paths) { @@ -164,7 +183,7 @@ export function AddModelForm({ repoId: result.repoId, revision: result.revision, sha: result.sha, - include: [...includePatterns, ...[...checked].sort().map(escapeGlob)], + include: [...includePatterns, ...[...new Set([...checked, ...recActive])].sort().map(escapeGlob)], exclude: excludePatterns, tags: tags.map((t) => t.name), localPath: importFolder?.path, @@ -300,6 +319,8 @@ export function AddModelForm({ )} + +
    @@ -378,6 +399,7 @@ export function AddModelForm({ const some = !all && parts.some((f) => f.selected); const byPattern = parts.every((f) => f.byPattern); const excluded = parts.every((f) => f.excluded); + const isRecommended = parts.every((f) => f.recommended); return ( @@ -400,6 +422,11 @@ export function AddModelForm({ )} {excluded && (excluded)} + {isRecommended && ( + + recommended + + )} {importFolder && } @@ -414,7 +441,7 @@ export function AddModelForm({ -
    +
    @@ -429,7 +456,10 @@ export function AddModelForm({ )}
    -
    ); diff --git a/src/app/(app)/settings/downloads/page.tsx b/src/app/(app)/settings/downloads/page.tsx new file mode 100644 index 0000000..c556ae7 --- /dev/null +++ b/src/app/(app)/settings/downloads/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; +import { getRecommendedRoles } from "@/lib/settings"; +import { RecommendedSettings } from "./recommended-settings"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Downloads · Settings" }; + +export default async function DownloadSettingsPage() { + return ; +} diff --git a/src/app/(app)/settings/downloads/recommended-settings.tsx b/src/app/(app)/settings/downloads/recommended-settings.tsx new file mode 100644 index 0000000..f5e2ab5 --- /dev/null +++ b/src/app/(app)/settings/downloads/recommended-settings.tsx @@ -0,0 +1,96 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useState } from "react"; +import { toast } from "sonner"; +import { FileRoleBadge } from "@/components/labels"; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; +import { Checkbox } from "@/components/ui/checkbox"; +import { FILE_ROLES, type FileRole } from "@/lib/file-roles"; +import { RECOMMENDABLE_ROLES } from "@/lib/recommend"; + +/** Example file name per kind, so the badge shows the configured label and color. */ +const EXAMPLE: Partial> = { + template: "chat_template.jinja", + mtp: "mtp-model.gguf", + vision: "mmproj-F16.gguf", + draft: "model-draft.gguf", + config: "config.json", + tokenizer: "tokenizer.json", + imatrix: "imatrix.dat", + adapter: "adapter_model.safetensors", + docs: "README.md", +}; + +const HINT: Partial> = { + mtp: "The variant with the same quant as your model file, otherwise the closest one.", + vision: "One mmproj file: same quant if there is one, otherwise F16, BF16, Q8_0, F32.", + draft: "One draft model, picked like MTP.", + imatrix: "Only needed to make your own quants.", + config: "GGUF files already contain it; useful for safetensors repos.", + tokenizer: "GGUF files already contain it; useful for safetensors repos.", +}; + +/** Which file kinds are selected automatically when you pick model weights. Saves on change. */ +export function RecommendedSettings({ initial }: { initial: FileRole[] }) { + const router = useRouter(); + const [roles, setRoles] = useState(new Set(initial)); + const [saving, setSaving] = useState(false); + + async function toggle(role: FileRole, on: boolean) { + const before = roles; + const next = new Set(roles); + if (on) next.add(role); + else next.delete(role); + setRoles(next); + setSaving(true); + try { + const res = await fetch("/api/settings/downloads", { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ recommendedRoles: [...next] }), + }); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + toast.error(body.error?.message ?? `Could not save (${res.status})`); + setRoles(before); + return; + } + router.refresh(); + } finally { + setSaving(false); + } + } + + return ( + + + Recommended files + + When you pick model weights (a quant) in Add model or Download more, files of these kinds are selected along + with them. You can still uncheck them before downloading. + + + +
    + {RECOMMENDABLE_ROLES.map((role) => ( + + ))} +
    +
    +
    + ); +} diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx index 5570031..18798a6 100644 --- a/src/app/(app)/settings/layout.tsx +++ b/src/app/(app)/settings/layout.tsx @@ -1,9 +1,10 @@ -import { TagIcon, TagsIcon } from "lucide-react"; +import { DownloadIcon, TagIcon, TagsIcon } from "lucide-react"; import { SettingsNav } from "./settings-nav"; const SECTIONS = [ { href: "/settings/labels", label: "File labels", icon: }, { href: "/settings/tags", label: "Tags", icon: }, + { href: "/settings/downloads", label: "Downloads", icon: }, ]; export default function SettingsLayout({ children }: LayoutProps<"/settings">) { diff --git a/src/app/api/settings/downloads/route.ts b/src/app/api/settings/downloads/route.ts new file mode 100644 index 0000000..bfb6ce9 --- /dev/null +++ b/src/app/api/settings/downloads/route.ts @@ -0,0 +1,22 @@ +import { NextResponse } from "next/server"; +import { z } from "zod"; +import { withAuth } from "@/lib/api-auth"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { getRecommendedRoles, saveRecommendedRoles, SettingsError } from "@/lib/settings"; + +export const dynamic = "force-dynamic"; + +/** Download settings: which file kinds are picked along with model weights. */ +export const GET = withAuth(async () => NextResponse.json({ recommendedRoles: await getRecommendedRoles() })); + +const Body = z.object({ recommendedRoles: z.array(z.string()).max(32) }); + +export const PUT = withAuth(async (req) => { + try { + const { recommendedRoles } = Body.parse(await req.json()); + return NextResponse.json({ recommendedRoles: await saveRecommendedRoles(recommendedRoles) }); + } catch (err) { + if (err instanceof SettingsError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/components/labels.tsx b/src/components/labels.tsx index 5389004..ab0d84a 100644 --- a/src/components/labels.tsx +++ b/src/components/labels.tsx @@ -2,7 +2,8 @@ import { createContext, useContext } from "react"; import { BADGE_CLASS } from "@/lib/colors"; -import { FILE_ROLES, fileRole, type FileRoleStyles } from "@/lib/file-roles"; +import { FILE_ROLES, fileRole, type FileRole, type FileRoleStyles } from "@/lib/file-roles"; +import { DEFAULT_RECOMMENDED_ROLES } from "@/lib/recommend"; import { cn } from "@/lib/utils"; const defaults = Object.fromEntries( @@ -10,16 +11,34 @@ const defaults = Object.fromEntries( ) as FileRoleStyles; const LabelContext = createContext(defaults); +const RecommendedContext = createContext(DEFAULT_RECOMMENDED_ROLES); -/** Provides the label settings (from the Settings page) to client components. */ -export function LabelSettingsProvider({ fileRoles, children }: { fileRoles: FileRoleStyles; children: React.ReactNode }) { - return {children}; +/** Provides file label and download settings (from the Settings page) to client components. */ +export function LabelSettingsProvider({ + fileRoles, + recommendedRoles, + children, +}: { + fileRoles: FileRoleStyles; + recommendedRoles: FileRole[]; + children: React.ReactNode; +}) { + return ( + + {children} + + ); } export function useFileRoleStyles(): FileRoleStyles { return useContext(LabelContext); } +/** File kinds picked automatically along with model weights. */ +export function useRecommendedRoles(): FileRole[] { + return useContext(RecommendedContext); +} + /** Label in front of a file name telling what the file is (Model, MTP, Vision, …). */ export function FileRoleBadge({ path, className }: { path: string; className?: string }) { const styles = useFileRoleStyles(); diff --git a/src/components/recommended-strip.tsx b/src/components/recommended-strip.tsx new file mode 100644 index 0000000..76ee8c0 --- /dev/null +++ b/src/components/recommended-strip.tsx @@ -0,0 +1,63 @@ +"use client"; + +import { SparklesIcon } from "lucide-react"; +import Link from "next/link"; +import { FileRoleBadge } from "@/components/labels"; +import { Checkbox } from "@/components/ui/checkbox"; +import { groupSplitFiles } from "@/lib/file-groups"; +import { formatBytes } from "@/lib/format"; +import { cn } from "@/lib/utils"; + +/** Companion files picked along with the chosen quant; each can be unchecked. */ +export function RecommendedStrip({ + files, + paths, + active, + onToggle, + className, +}: { + files: { path: string; size: number }[]; + /** All recommended paths (checked or not). */ + paths: string[]; + active: Set; + onToggle: (paths: string[], on: boolean) => void; + className?: string; +}) { + if (paths.length === 0) return null; + const wanted = new Set(paths); + const entries = groupSplitFiles(files.filter((f) => wanted.has(f.path))); + + return ( +
    +
    + + + Recommended with your quant + + + Change in Settings + +
    +
    + {entries.map((e) => { + const parts = e.parts.map((p) => p.path); + const on = parts.every((p) => active.has(p)); + return ( + + ); + })} +
    +
    + ); +} diff --git a/src/hooks/use-recommended.ts b/src/hooks/use-recommended.ts new file mode 100644 index 0000000..8beff17 --- /dev/null +++ b/src/hooks/use-recommended.ts @@ -0,0 +1,43 @@ +"use client"; + +import { useMemo, useState } from "react"; +import { useRecommendedRoles } from "@/components/labels"; +import { modelFilePaths, recommendFiles } from "@/lib/recommend"; + +/** + * Companion files (template, MTP, mmproj, …) for the model weights in `picked`, per the + * "Recommended files" setting. They count as selected unless the user unchecked them (`dismissed`), + * and drop out by themselves when the model file they belong to is deselected. + */ +export function useRecommended( + files: { path: string; size: number }[], + picked: Iterable, + options: { isExcluded?: (path: string) => boolean; have?: string[] } = {}, +) { + const { isExcluded, have } = options; + const roles = useRecommendedRoles(); + const [dismissed, setDismissed] = useState>(new Set()); + const pickedList = useMemo(() => [...picked], [picked]); + + const all = useMemo(() => { + const already = new Set(pickedList); + return recommendFiles(files, modelFilePaths(pickedList), roles, [...pickedList, ...(have ?? [])]).filter( + (p) => !already.has(p) && !isExcluded?.(p), + ); + }, [files, pickedList, roles, isExcluded, have]); + const active = useMemo(() => new Set(all.filter((p) => !dismissed.has(p))), [all, dismissed]); + + /** Check or uncheck recommended paths (unchecking remembers the choice). */ + function setOn(paths: string[], on: boolean) { + setDismissed((prev) => { + const next = new Set(prev); + for (const p of paths) { + if (on) next.delete(p); + else next.add(p); + } + return next; + }); + } + + return { all, active, setOn, reset: () => setDismissed(new Set()) }; +} diff --git a/src/lib/recommend.test.ts b/src/lib/recommend.test.ts new file mode 100644 index 0000000..f5626e1 --- /dev/null +++ b/src/lib/recommend.test.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { DEFAULT_RECOMMENDED_ROLES, quantTag, recommendFiles } from "./recommend"; + +const f = (path: string, size = 1) => ({ path, size }); + +// Trimmed from unsloth/Qwen3.8-27B-GGUF and unsloth/Qwen3-8B-GGUF. +const qwen38 = [ + f(".gitattributes"), + f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf", 1_369_590_656), + f("Qwen3.8-27B-Q4_0.gguf"), + f("Qwen3.8-27B-UD-Q4_K_XL.gguf"), + f("README.md"), + f("config.json"), + f("imatrix_unsloth.gguf"), + f("mmproj-BF16.gguf", 931_146_432), + f("mmproj-F16.gguf", 927_607_488), +]; +const qwen3 = [f("Qwen3-8B-Q4_K_M.gguf"), f("Qwen3-8B-Q8_0.gguf"), f("params"), f("template"), f("config.json"), f("imatrix_unsloth.dat")]; + +describe("quantTag", () => { + it("reads quant and precision tags", () => { + assert.equal(quantTag("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"), "q4_0"); + assert.equal(quantTag("mmproj-F16.gguf"), "f16"); + assert.equal(quantTag("Qwen3.8-27B-UD-Q4_K_XL.gguf"), "ud-q4_k_xl"); + }); +}); + +describe("recommendFiles", () => { + it("adds the only MTP head and prefers the F16 mmproj", () => { + const rec = recommendFiles(qwen38, ["Qwen3.8-27B-UD-Q4_K_XL.gguf"], DEFAULT_RECOMMENDED_ROLES); + assert.deepEqual(rec.sort(), ["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "mmproj-F16.gguf"]); + }); + + it("matches the variant with the same quant", () => { + const files = [...qwen38, f("MTP/mtp-Qwen3.8-27B-Q8_0.gguf"), f("Qwen3.8-27B-Q8_0.gguf")]; + assert.deepEqual(recommendFiles(files, ["Qwen3.8-27B-Q8_0.gguf"], ["mtp"]), ["MTP/mtp-Qwen3.8-27B-Q8_0.gguf"]); + assert.deepEqual(recommendFiles(files, ["Qwen3.8-27B-Q4_0.gguf"], ["mtp"]), ["MTP/mtp-Qwen3.8-27B-Q4_0.gguf"]); + }); + + it("adds the chat template, and config only when enabled", () => { + assert.deepEqual(recommendFiles(qwen3, ["Qwen3-8B-Q4_K_M.gguf"], DEFAULT_RECOMMENDED_ROLES), ["template"]); + assert.deepEqual(recommendFiles(qwen3, ["Qwen3-8B-Q4_K_M.gguf"], ["config"]).sort(), ["config.json", "params"]); + }); + + it("doesn't add a second variant when one is already selected", () => { + assert.deepEqual(recommendFiles(qwen38, ["Qwen3.8-27B-Q4_0.gguf"], ["vision"], ["mmproj-BF16.gguf"]), []); + assert.deepEqual(recommendFiles(qwen38, ["Qwen3.8-27B-Q4_0.gguf", "mmproj-BF16.gguf"], ["vision", "mtp"]), [ + "MTP/mtp-Qwen3.8-27B-Q4_0.gguf", + ]); + }); + + it("recommends nothing without picked model files", () => { + assert.deepEqual(recommendFiles(qwen38, [], DEFAULT_RECOMMENDED_ROLES), []); + }); +}); diff --git a/src/lib/recommend.ts b/src/lib/recommend.ts new file mode 100644 index 0000000..3dd4076 --- /dev/null +++ b/src/lib/recommend.ts @@ -0,0 +1,93 @@ +// Files that usually go with the model weights you pick: chat template, MTP head, vision +// projector (mmproj), … Which kinds is a setting. Shared by UI and server (pure functions). + +import { groupSplitFiles } from "./file-groups"; +import { fileRole, type FileRole } from "./file-roles"; +import { quantGroup } from "./selection"; + +/** File kinds that can be recommended, in display order. */ +export const RECOMMENDABLE_ROLES: FileRole[] = ["template", "mtp", "vision", "draft", "config", "tokenizer", "imatrix", "adapter", "docs"]; +export const DEFAULT_RECOMMENDED_ROLES: FileRole[] = ["template", "mtp", "vision"]; + +/** Kinds where a repo has alternatives (one per quant or precision) and one is enough. */ +const VARIANT_ROLES = new Set(["mtp", "vision", "draft", "adapter", "imatrix"]); +/** Preferred precision when no variant matches the picked quant. */ +const PRECISION_ORDER = ["f16", "bf16", "q8_0", "f32"]; + +const basename = (p: string) => p.slice(p.lastIndexOf("/") + 1); +const dirname = (p: string) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : ""); + +/** Quant/precision tag from a file name: "mtp-X-Q4_0.gguf" → "q4_0", "mmproj-F16.gguf" → "f16". */ +export function quantTag(path: string): string | null { + const g = quantGroup(basename(path)); + return g ? g.replace(/^mmproj-/i, "").toLowerCase() : null; +} + +const withoutUd = (q: string) => q.replace(/^ud-/, ""); +const bits = (q: string) => q.match(/^(?:ud-)?(?:i?q|tq|bf|f)(\d+)/)?.[1] ?? null; + +/** + * Paths to download along with `modelPaths` (model weights), for the given kinds. Variant kinds + * (MTP, mmproj, …) get the variant matching a picked quant, else the best single one; other kinds + * (template, config, …) get every such file at the repo root or next to a picked model file. + * `have`: everything already selected; a variant kind that's already there isn't added again. + */ +export function recommendFiles( + files: { path: string; size: number }[], + modelPaths: string[], + roles: FileRole[], + have: string[] = [], +): string[] { + if (modelPaths.length === 0 || roles.length === 0) return []; + const picked = new Set([...modelPaths, ...have]); + const haveRoles = new Set([...picked].map(fileRole)); + const quants = modelPaths.map(quantTag).filter((q): q is string => !!q); + const dirs = new Set(["", ...modelPaths.map(dirname)]); + const out: string[] = []; + + for (const role of roles) { + const entries = groupSplitFiles(files.filter((f) => !picked.has(f.path) && fileRole(f.path) === role)); + if (entries.length === 0) continue; + if (!VARIANT_ROLES.has(role)) { + for (const e of entries) if (dirs.has(dirname(e.path))) out.push(...e.parts.map((p) => p.path)); + continue; + } + if (haveRoles.has(role)) continue; // e.g. an mmproj is already selected + if (entries.length === 1) { + out.push(...entries[0].parts.map((p) => p.path)); + continue; + } + const tag = (e: (typeof entries)[number]) => quantTag(e.path) ?? ""; + // Same quant as a picked model file (ignoring unsloth's "UD-" prefix): take those. + const same = entries.filter((e) => quants.some((q) => withoutUd(q) === withoutUd(tag(e)))); + if (same.length > 0) { + for (const e of same) out.push(...e.parts.map((p) => p.path)); + continue; + } + // Otherwise one variant: next to the model, then preferred precision, then same bit width, then smallest. + const pickedBits = new Set(quants.map(bits).filter(Boolean)); + const score = (e: (typeof entries)[number]) => { + const t = tag(e); + const precision = PRECISION_ORDER.indexOf(t); + return [ + dirs.has(dirname(e.path)) && dirname(e.path) !== "" ? 0 : 1, + precision === -1 ? PRECISION_ORDER.length : precision, + pickedBits.has(bits(t)) ? 0 : 1, + e.size, + ]; + }; + const best = [...entries].sort((a, b) => { + const sa = score(a); + const sb = score(b); + for (let i = 0; i < sa.length; i++) if (sa[i] !== sb[i]) return sa[i] - sb[i]; + return 0; + })[0]; + out.push(...best.parts.map((p) => p.path)); + } + return [...new Set(out)]; +} + +/** Model-weight paths among `paths`. */ +export function modelFilePaths(paths: Iterable): string[] { + return [...paths].filter((p) => fileRole(p) === "model"); +} diff --git a/src/lib/settings.ts b/src/lib/settings.ts index ec4252a..7f71b81 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -4,6 +4,7 @@ import { db } from "@/lib/db/client"; import { settings } from "@/lib/db/schema"; import { isLabelColor } from "@/lib/colors"; import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles"; +import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend"; const FILE_ROLES_KEY = "labels.fileRoles"; export const FILE_ROLE_LABEL_MAX = 24; @@ -67,3 +68,19 @@ export async function saveFileRoleStyles(input: Record { + const stored = await read(RECOMMENDED_KEY); + if (!Array.isArray(stored)) return DEFAULT_RECOMMENDED_ROLES; + return RECOMMENDABLE_ROLES.filter((r) => stored.includes(r)); +} + +export async function saveRecommendedRoles(roles: string[]): Promise { + const unknown = roles.find((r) => !RECOMMENDABLE_ROLES.includes(r as FileRole)); + if (unknown) throw new SettingsError(`"${unknown}" can't be recommended.`); + await write(RECOMMENDED_KEY, RECOMMENDABLE_ROLES.filter((r) => roles.includes(r))); + return getRecommendedRoles(); +}