Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(models): a guessed quant is picked by the graphics memory (D7, GitHub #215)

purplefad1ed4607e3
diff --git a/src/api/__tests__/a-guessed-quant-fits-the-card-behaviour.test.ts b/src/api/__tests__/a-guessed-quant-fits-the-card-behaviour.test.ts
new file mode 100644
index 00000000..0506f1f6
--- /dev/null
+++ b/src/api/__tests__/a-guessed-quant-fits-the-card-behaviour.test.ts
@@ -0,0 +1,26 @@
+/**
+ * D7, GitHub #215: the behaviour alone, through functions that existed before
+ * the fix, so this file is red on the old code by its answer and not by a
+ * missing export. 16 GB card, budget 14.4 GiB in bytes.
+ *
+ * Run: npx vitest run src/api/__tests__/a-guessed-quant-fits-the-card-behaviour.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { selectGgufFromTree, type HfTreeEntry } from '../discover'
+import { defaultChoice, ggufChoicesFromTree } from '../../lib/hf-link'
+
+const GB = 1_000_000_000
+const file = (quant: string, gb: number): HfTreeEntry => ({ type: 'file', path: `M-27B-${quant}.gguf`, size: Math.round(gb * GB) })
+const TREE = [file('Q2_K', 10.2), file('Q3_K_M', 12.9), file('Q4_K_M', 15.8), file('Q4_K_L', 16.8)]
+const BUDGET_16 = Math.floor(14.4 * 1_073_741_824)
+
+describe('GitHub #215 on a 16 GB card', () => {
+ it('a guessed Q4_K_M of 15.8 GB becomes the Q3_K_M', () => {
+ const select = selectGgufFromTree as (...a: unknown[]) => ReturnType<typeof selectGgufFromTree>
+ expect(select(TREE, 'o/M-27B-GGUF', 'Q4_K_M', undefined, BUDGET_16)?.quant).toBe('Q3_K_M')
+ })
+ it('the link dialog preselects the Q3_K_M', () => {
+ const pick = defaultChoice as (...a: unknown[]) => ReturnType<typeof defaultChoice>
+ expect(pick(ggufChoicesFromTree(TREE), BUDGET_16)?.quant).toBe('Q3_K_M')
+ })
+})
diff --git a/src/api/__tests__/a-guessed-quant-fits-the-card.test.tsx b/src/api/__tests__/a-guessed-quant-fits-the-card.test.tsx
new file mode 100644
index 00000000..069b4cf3
--- /dev/null
+++ b/src/api/__tests__/a-guessed-quant-fits-the-card.test.tsx
@@ -0,0 +1,135 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * D7, GitHub #215 (Windows, RTX 5070 Ti 16 GB): the Hugging Face search in
+ * Models offered Huihui-Qwen3.8-27B-…-GGUF and fetched its Q4_K_M, 15.8 GB,
+ * on a 16 GB card. No room for the context, so it ran mostly on the CPU. The
+ * search only guessed Q4_K_M from the repo name, and the download took the
+ * guess although the repository's file list had every quant with its size.
+ *
+ * Now a quant nobody chose is taken by size: the largest that leaves the
+ * memory minus max(1.5 GB, 10 %). A file the user or the catalog names is
+ * never swapped. The link dialog preselects the same way and marks the
+ * files that won't fit.
+ *
+ * Run: npx vitest run src/api/__tests__/a-guessed-quant-fits-the-card.test.tsx
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { render, screen, cleanup, act } from '@testing-library/react'
+
+const backend = vi.hoisted(() => ({
+ fetchExternal: vi.fn(async (_url: string) => ''),
+ backendCall: vi.fn(async (_cmd: string): Promise<unknown> => null),
+}))
+vi.mock('../backend', () => ({
+ ...backend,
+ isTauri: () => true,
+ isMacOS: () => false,
+ isWindows: () => true,
+ openExternal: vi.fn(),
+}))
+const memory = vi.hoisted(() => ({ gb: 16 }))
+vi.mock('../../lib/hardware', async (orig) => ({
+ ...(await orig<typeof import('../../lib/hardware')>()),
+ getMaxVramGb: vi.fn(async () => memory.gb),
+}))
+
+import {
+ ggufRequestFor, quantBudgetBytes, searchHuggingFaceModels, selectGgufFromTree, type HfTreeEntry,
+} from '../discover'
+import { quantFitNote } from '../../components/models/DiscoverModels'
+import { defaultChoice, ggufChoicesFromTree, overBudgetLabel } from '../../lib/hf-link'
+import { HfLinkDialog } from '../../components/models/HfLinkDialog'
+
+const GB = 1_000_000_000 // Hugging Face states sizes in bytes; it shows decimal GB.
+const REPO = 'huihui-ai/Huihui-Qwen3.8-27B-Coder-abliterated-GGUF'
+const file = (quant: string, gb: number): HfTreeEntry => ({
+ type: 'file', path: `Huihui-Qwen3.8-27B-Coder-abliterated-${quant}.gguf`, size: Math.round(gb * GB),
+})
+// The sizes of the report: Q4_K_M 15.8 GB, Q4_K_L 16.8 GB, Q3_K_M below.
+const TREE: HfTreeEntry[] = [
+ file('Q2_K', 10.2), file('Q3_K_M', 12.9), file('Q4_K_M', 15.8), file('Q4_K_L', 16.8), file('Q5_K_M', 18.4),
+ { type: 'file', path: 'README.md', size: 2000 },
+]
+const BUDGET_16 = quantBudgetBytes(16)!
+
+afterEach(() => { cleanup(); vi.clearAllMocks(); memory.gb = 16 })
+
+describe('the memory budget', () => {
+ it('is the memory minus max(1.5 GB, 10 %), in bytes of GiB', () => {
+ expect(BUDGET_16).toBe(Math.floor(14.4 * 1_073_741_824))
+ expect(quantBudgetBytes(8)).toBe(Math.floor(6.5 * 1_073_741_824))
+ expect(quantBudgetBytes(24)).toBe(Math.floor(21.6 * 1_073_741_824))
+ expect(quantBudgetBytes(null)).toBeUndefined()
+ expect(quantBudgetBytes(1)).toBeUndefined()
+ })
+})
+
+describe('a search hit with a guessed quant', () => {
+ it('THE REPORT: on 16 GB the download takes Q3_K_M, not the 15.8 GB Q4_K_M', () => {
+ const picked = selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, BUDGET_16)
+ expect(picked?.quant).toBe('Q3_K_M')
+ expect(picked?.fitSwap).toEqual({ from: 'Q4_K_M', fromBytes: 15.8 * GB })
+ expect(picked?.files.map((f) => f.filename)).toEqual(['Huihui-Qwen3.8-27B-Coder-abliterated-Q3_K_M.gguf'])
+ })
+
+ it('a card with room keeps Q4_K_M, a bigger one still never gets more than the guess fits', () => {
+ expect(selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, quantBudgetBytes(24))?.quant).toBe('Q4_K_M')
+ expect(selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, quantBudgetBytes(24))?.fitSwap).toBeUndefined()
+ })
+
+ it('when nothing fits, the guess stays and says so', () => {
+ const picked = selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, quantBudgetBytes(8))
+ expect(picked?.quant).toBe('Q4_K_M')
+ expect(picked?.overBudget).toBe(true)
+ })
+
+ it('a file the caller names is never swapped, however big', () => {
+ const named = selectGgufFromTree(TREE, REPO, 'Q4_K_M', TREE[3].path, BUDGET_16)
+ expect(named?.quant).toBe('Q4_K_L')
+ expect(named?.fitSwap).toBeUndefined()
+ })
+
+ it('the search marks a repo name without a quant as guessed, and its request names no file', async () => {
+ backend.fetchExternal.mockResolvedValueOnce(JSON.stringify([
+ { id: REPO, downloads: 5000 },
+ { id: 'org/Model-7B-Q5_K_M-GGUF', downloads: 10 },
+ ]))
+ const [guessed, named] = await searchHuggingFaceModels('huihui qwen')
+ expect(guessed.quantGuessed).toBe(true)
+ expect(guessed.tags).toEqual(['GGUF'])
+ expect(named.quantGuessed).toBeUndefined()
+ const request = ggufRequestFor(guessed)
+ expect(request?.quantGuessed).toBe(true)
+ expect(request?.exactPath).toBeUndefined()
+ expect(ggufRequestFor(named)?.exactPath).toBe('Model-7B-Q5_K_M.gguf')
+ })
+
+ it('the line under the list says what was picked and why', () => {
+ const picked = selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, BUDGET_16)
+ const note = quantFitNote('Huihui-Qwen3.8-27B', picked, 16, false)
+ expect(note).toContain('LU picked Q3_K_M (12.0 GB)')
+ expect(note).toContain('your 16 GB of graphics memory')
+ expect(note).toContain('Q4_K_M (14.7 GB) would not fit fully')
+ expect(quantFitNote('x', selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, quantBudgetBytes(24)), 24, false)).toBeNull()
+ expect(quantFitNote('x', selectGgufFromTree(TREE, REPO, 'Q4_K_M', undefined, quantBudgetBytes(8)), 8, false)).toContain("no quant of it fits fully")
+ })
+})
+
+describe('the Hugging Face link dialog', () => {
+ it('preselects the largest file that fits and marks the bigger ones', async () => {
+ const choices = ggufChoicesFromTree(TREE)
+ expect(defaultChoice(choices, BUDGET_16)?.quant).toBe('Q3_K_M')
+ expect(defaultChoice(choices)?.quant).toBe('Q4_K_M')
+ expect(overBudgetLabel(15.8 * GB, BUDGET_16)).toBe(" · won't fit fully in GPU memory")
+ expect(overBudgetLabel(12.9 * GB, BUDGET_16)).toBe('')
+
+ backend.fetchExternal.mockResolvedValue(JSON.stringify(TREE))
+ render(<HfLinkDialog link={{ repo: REPO, file: null }} onCancel={vi.fn()} onConfirm={vi.fn()} />)
+ await act(async () => { for (let i = 0; i < 5; i++) await Promise.resolve() })
+ expect(screen.getByTestId('hf-link-quant').textContent).toBe('Q3_K_M')
+ const options = [...(screen.getByTestId('hf-link-file-select') as HTMLSelectElement).options].map((o) => o.textContent ?? '')
+ expect(options.find((o) => o.includes('Q4_K_M'))).toContain("won't fit fully in GPU memory")
+ expect(options.find((o) => o.includes('Q3_K_M'))).not.toContain("won't fit")
+ })
+})
diff --git a/src/api/discover.ts b/src/api/discover.ts
index fbfdd243..a8159ca8 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -1659,6 +1659,8 @@ export async function searchHuggingFaceModels(query: string): Promise<DiscoverMo
if (typeof repo?.id !== 'string') continue
const repoName = repo.id.split('/').pop() || ''
const q4File = deriveQ4FilenameFromRepo(repoName)
+ // D7: the repo name named no quant, so Q4_K_M is only a guess.
+ const quantGuessed = q4File !== `${repoName.replace(/-GGUF$/i, '')}.gguf`
const downloadUrl = `https://huggingface.co/${repo.id}/resolve/main/${q4File}`
// Display name = repo basename without the GGUF suffix. The previous
@@ -1676,11 +1678,13 @@ export async function searchHuggingFaceModels(query: string): Promise<DiscoverMo
name: displayName,
description: repo.id,
pulls: pullsStr,
- tags: ['Q4_K_M', 'GGUF'],
+ // D7: a guessed quant is no promise, the download picks it by size.
+ tags: quantGuessed ? ['GGUF'] : ['Q4_K_M', 'GGUF'],
updated: '',
downloadUrl,
filename: q4File,
url: `https://huggingface.co/${repo.id}`,
+ ...(quantGuessed ? { quantGuessed: true } : {}),
})
}
return models
@@ -1726,6 +1730,12 @@ export interface HfGgufResolution {
/** The image part the same repository ships, when it ships one. For a model
* the catalog does not know, this is what is offered with it. */
imagePart?: ImagePartSource
+ /** D7: the guessed quant did not fit the memory budget and this smaller one
+ * was taken instead. `from` is what the guess would have fetched. */
+ fitSwap?: { from: string; fromBytes: number }
+ /** D7: even the chosen file is bigger than the memory budget (no quant of
+ * the repository fits). It downloads and runs, partly on the CPU. */
+ overBudget?: boolean
/** Set when the chosen file is a split set the repository holds only some
* parts of (an upload still running). `files` is empty then: llama.cpp
* cannot load the set, so nothing of it is downloaded. */
@@ -1780,6 +1790,9 @@ export function selectGgufFromTree(
repoId: string,
preferredQuant?: string,
exactPath?: string,
+ /** D7: the most a guessed quant may weigh, in bytes (`quantBudgetBytes`).
+ * Only for a quant nobody chose; a named file is never swapped. */
+ budgetBytes?: number,
): HfGgufResolution | null {
const allGguf = entries.filter(e => e.type === 'file' && /\.gguf$/i.test(e.path))
// An image part is a GGUF too and carries a quant token of its own
@@ -1811,14 +1824,34 @@ export function selectGgufFromTree(
const wanted = preferredQuant?.toUpperCase()
const byQuant = (g: GgufGroup) => g.quant === wanted
const byKey = (g: GgufGroup) => !!wanted && g.key.toUpperCase().includes(wanted)
- const picked =
- groupOfNamedFile(all, exactPath) ||
+ const named = groupOfNamedFile(all, exactPath)
+ let picked =
+ named ||
(wanted ? complete.find(byQuant) || all.find(byQuant) : undefined) ||
(wanted ? complete.find(byKey) || all.find(byKey) : undefined) ||
complete.find(g => g.quant === 'Q4_K_M') ||
complete[0] ||
all[0]
if (!picked) return null
+ // D7 (GitHub #215): a 16 GB card got the 15.8 GB Q4_K_M, which leaves no
+ // room for the context and runs mostly on the CPU. A quant nobody chose is
+ // taken from the list by size instead: the largest one that fits.
+ let fitSwap: HfGgufResolution['fitSwap']
+ let overBudget = false
+ if (!named && budgetBytes && budgetBytes > 0 && !picked.gap) {
+ const pickedBytes = groupBytes(picked)
+ if (pickedBytes > budgetBytes) {
+ const fitting = complete
+ .filter(g => g.quant && groupBytes(g) > 0 && groupBytes(g) <= budgetBytes)
+ .sort((a, b) => groupBytes(b) - groupBytes(a))[0]
+ if (fitting) {
+ fitSwap = { from: picked.quant ?? picked.key, fromBytes: pickedBytes }
+ picked = fitting
+ } else {
+ overBudget = true
+ }
+ }
+ }
if (picked.gap) {
return { sharded: true, files: [], totalBytes: 0, quant: picked.quant, incomplete: picked.gap }
}
@@ -1839,6 +1872,8 @@ export function selectGgufFromTree(
files,
totalBytes: files.reduce((s, f) => s + f.sizeBytes, 0),
quant: picked.quant,
+ ...(fitSwap ? { fitSwap } : {}),
+ ...(overBudget ? { overBudget } : {}),
...(upstreamPart
? {
imagePart: {
@@ -1851,6 +1886,23 @@ export function selectGgufFromTree(
}
}
+function groupBytes(g: GgufGroup): number {
+ return g.parts.reduce((s, p) => s + (p.size || p.lfs?.size || 0), 0)
+}
+
+/**
+ * D7: how much a quant LU picks by itself may weigh. The model shares the
+ * graphics memory with its context (KV cache) and with the system, so the
+ * file gets the memory minus max(1.5 GB, 10 %). 16 GB leaves 14.4 GB. The
+ * memory arrives in GiB (MiB / 1024), the file sizes in bytes.
+ */
+export function quantBudgetBytes(memoryGb: number | null | undefined): number | undefined {
+ if (!memoryGb || memoryGb <= 0) return undefined
+ const headroom = Math.max(1.5, memoryGb * 0.1)
+ const gb = memoryGb - headroom
+ return gb > 0 ? Math.floor(gb * 1_073_741_824) : undefined
+}
+
/** What the download asks the repo tree for one entry. */
export interface GgufRequest {
repoId: string
@@ -1858,6 +1910,8 @@ export interface GgufRequest {
exactPath?: string
/** Read from the file name. Only the fallback, see `selectGgufFromTree`. */
preferredQuant?: string
+ /** D7: the quant is a guess, so it may be swapped for one that fits. */
+ quantGuessed?: boolean
}
/**
@@ -1865,14 +1919,16 @@ export interface GgufRequest {
* its address is not a HuggingFace file address. One place, so the Models tab
* and the test that walks the whole catalog ask the same thing.
*/
-export function ggufRequestFor(model: Pick<DiscoverModel, 'downloadUrl' | 'filename'>): GgufRequest | null {
+export function ggufRequestFor(model: Pick<DiscoverModel, 'downloadUrl' | 'filename' | 'quantGuessed'>): GgufRequest | null {
if (!model.downloadUrl) return null
const parsed = parseHfUrl(model.downloadUrl)
if (!parsed) return null
return {
repoId: `${parsed.user}/${parsed.repo}`,
- exactPath: hfUrlToTreePath(model.downloadUrl) ?? undefined,
+ // A guessed file name is no choice: it must not pin the Q4_K_M (D7).
+ exactPath: model.quantGuessed ? undefined : hfUrlToTreePath(model.downloadUrl) ?? undefined,
preferredQuant: model.filename ? extractGgufQuant(model.filename) : undefined,
+ ...(model.quantGuessed ? { quantGuessed: true } : {}),
}
}
@@ -1905,6 +1961,7 @@ export async function resolveHfGgufFiles(
repoId: string,
preferredQuant?: string,
exactPath?: string,
+ budgetBytes?: number,
): Promise<HfGgufResolution | null> {
try {
const url = `https://huggingface.co/api/models/${repoId}/tree/main?recursive=true`
@@ -1918,7 +1975,7 @@ export async function resolveHfGgufFiles(
}
const entries = JSON.parse(json)
if (!Array.isArray(entries)) return null
- return selectGgufFromTree(entries as HfTreeEntry[], repoId, preferredQuant, exactPath)
+ return selectGgufFromTree(entries as HfTreeEntry[], repoId, preferredQuant, exactPath, budgetBytes)
} catch (err) {
log.warn('[discover] HF tree resolve failed', { repoId, err })
return null
diff --git a/src/api/model-bundles.ts b/src/api/model-bundles.ts
index 1a94ad21..1f24dae8 100644
--- a/src/api/model-bundles.ts
+++ b/src/api/model-bundles.ts
@@ -39,6 +39,10 @@ export interface DiscoverModel {
/** Exact byte count, when the catalog knows it to the byte. A file of the same name
* and another size is NOT this file (a mirror's repack), so it never counts as installed. */
sizeBytes?: number
+ /** D7 (GitHub #215): a search hit whose quant LU only guessed (the repo
+ * name named none, so Q4_K_M was assumed). Its download picks the quant
+ * from the repository's file list by the graphics memory instead. */
+ quantGuessed?: boolean
// The image part that belongs to `downloadUrl` (llama.cpp calls it mmproj).
// A text GGUF carries no image tower: the engine sees images only when this
// second file lies next to the model and is passed along at start. When it
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index e056da93..6cf60cc0 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -11,7 +11,7 @@ import {
getUncensoredTextModels, getMainstreamTextModels,
detectProviderModelPath, luEngineDownloadDir,
startModelDownload,
- installBundleComplete, remoteBundleNotice, checkBundlesOnDisk, resolveHfGgufFiles, ggufRequestFor, planModelDownload,
+ installBundleComplete, remoteBundleNotice, checkBundlesOnDisk, resolveHfGgufFiles, ggufRequestFor, quantBudgetBytes, planModelDownload,
imagePartFor, imagePartOf, checkDownloadSpace,
type DiscoverModel, type DownloadProgress, type ModelBundle, type HfGgufFile, type ImagePartSource, type PlannedDownload,
} from '../../api/discover'
@@ -239,6 +239,33 @@ export function awaitDownloadedFile(
})
}
+/**
+ * D7 (GitHub #215): the line that says which quant a search hit got and why.
+ * Null when nothing was swapped and the file fits.
+ */
+export function quantFitNote(
+ name: string,
+ resolution: { quant?: string; totalBytes: number; fitSwap?: { from: string; fromBytes: number }; overBudget?: boolean } | null | undefined,
+ memoryGb: number | null,
+ sharedMemory: boolean,
+): string | null {
+ if (!resolution || !memoryGb) return null
+ const gb = (b: number) => (b / 1_073_741_824).toFixed(1)
+ const where = sharedMemory ? `the ${Math.round(memoryGb)} GB this Mac can give a model` : `your ${Math.round(memoryGb)} GB of graphics memory`
+ if (resolution.fitSwap) {
+ return `${name}: LU picked ${resolution.quant ?? 'a smaller quant'} (${gb(resolution.totalBytes)} GB), so it fits ${where} with room for the context. ${resolution.fitSwap.from} (${gb(resolution.fitSwap.fromBytes)} GB) would not fit fully and would run partly on the CPU, much slower.`
+ }
+ if (resolution.overBudget) {
+ return `${name}: no quant of it fits fully in ${where}. LU fetches ${resolution.quant ?? 'the GGUF'} (${gb(resolution.totalBytes)} GB); it runs, partly on the CPU and much slower. A smaller model will be faster.`
+ }
+ return null
+}
+
+/** A later line of the same download keeps the quant line in front of it. */
+function withFitNote(fitNote: string | null, line: string): string {
+ return fitNote ? `${fitNote} ${line}` : line
+}
+
export function DiscoverModels({ category, search = '', searchSubmitToken = 0, originalFor = null }: Props) {
const [loading, setLoading] = useState(false)
const systemVRAM = useGraphicsMemoryGb()
@@ -795,9 +822,12 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o
// name the repo does not carry: on its own it cannot tell two families in
// one repo apart, and it reads nothing from `-0731.gguf` or `_K_P.gguf`.
const request = ggufRequestFor(model)
+ // D7 (GitHub #215): a quant nobody chose is taken by the memory there is.
+ const budget = request?.quantGuessed ? quantBudgetBytes(chatFitGb) : undefined
const resolution = request
- ? await resolveHfGgufFiles(request.repoId, request.preferredQuant, request.exactPath)
+ ? await resolveHfGgufFiles(request.repoId, request.preferredQuant, request.exactPath, budget)
: null
+ const fitNote = quantFitNote(model.name, resolution, chatFitGb, sharedMemory)
// A split set the uploader has not finished: llama.cpp loads it only with
// every part, so none of it is fetched.
@@ -805,6 +835,7 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o
setInstallError(`${model.name} is not complete on Hugging Face yet: only ${resolution.incomplete.have} of ${resolution.incomplete.of} parts are there, and the model loads only with all of them. Try again later.`)
return
}
+ if (fitNote) setInstallNotice(fitNote)
const lmStudioEnabled = !!providers.openai?.enabled && (providers.openai?.name || '').toLowerCase().includes('lm studio')
const ollamaEnabledNow = !!providers.ollama?.enabled
@@ -913,13 +944,13 @@ export function DiscoverModels({ category, search = '', searchSubmitToken = 0, o
])
if (both && !both.fits && alone?.fits) {
withPart = false
- setInstallNotice(`${model.name} is downloading without ${partInputWord(model)}: the drive has no room for the extra ${gbOf(part.sizeBytes)} GB. You can add it later under Installed.`)
+ setInstallNotice(withFitNote(fitNote, `${model.name} is downloading without ${partInputWord(model)}: the drive has no room for the extra ${gbOf(part.sizeBytes)} GB. You can add it later under Installed.`))
}
}
const plan = planModelDownload(model, realUrl, realName, realBytes, single?.sha256, { part, withImagePart: withPart })
await startPlannedDownload(plan, targetDir, model.group || model.name)
if (isActiveBuiltin && keepChatModel) {
- setInstallNotice(`${model.name} is downloading to the LU Engine. Your chat stays on its model; the Neuron tweaker and the model list show it once it is done.`)
+ setInstallNotice(withFitNote(fitNote, `${model.name} is downloading to the LU Engine. Your chat stays on its model; the Neuron tweaker and the model list show it once it is done.`))
} else if (isActiveBuiltin) {
// Built-in engine: await the flat GGUF, then make it the active chat
// model so the freshly-added model is chat-ready without a manual switch.
diff --git a/src/components/models/HfLinkDialog.tsx b/src/components/models/HfLinkDialog.tsx
index f29455b7..a750986c 100644
--- a/src/components/models/HfLinkDialog.tsx
+++ b/src/components/models/HfLinkDialog.tsx
@@ -1,9 +1,11 @@
import { useEffect, useState } from 'react'
-import { fetchExternal } from '../../api/backend'
-import { selectGgufFromTree, type HfTreeEntry } from '../../api/discover'
+import { fetchExternal, isMacOS } from '../../api/backend'
+import { getMaxVramGb } from '../../lib/hardware'
+import { chatModelBudgetGb } from '../../lib/shared-memory-wording'
+import { quantBudgetBytes, selectGgufFromTree, type HfTreeEntry } from '../../api/discover'
import type { DiscoverModel } from '../../api/model-bundles'
import {
- choiceForFile, defaultChoice, ggufChoicesFromTree, hfRepoPage, hfTreeApi, incompleteLabel, linkModel, sizeLabel,
+ choiceForFile, defaultChoice, ggufChoicesFromTree, hfRepoPage, hfTreeApi, incompleteLabel, linkModel, overBudgetLabel, sizeLabel,
type HfLinkChoice, type HfModelLink,
} from '../../lib/hf-link'
import { log } from '../../lib/logger'
@@ -33,6 +35,8 @@ interface Props {
export function HfLinkDialog({ link, onCancel, onConfirm }: Props) {
const [load, setLoad] = useState<Load>({ state: 'loading' })
const [picked, setPicked] = useState<string | null>(null)
+ // D7: what a model may weigh here, for the preselection and the list.
+ const [budget, setBudget] = useState<number | undefined>(undefined)
useEffect(() => {
// A new link remounts the dialog (DiscoverModels keys it by the link),
@@ -40,8 +44,14 @@ export function HfLinkDialog({ link, onCancel, onConfirm }: Props) {
let gone = false
void (async () => {
try {
- const entries = JSON.parse(await fetchExternal(hfTreeApi(link.repo))) as unknown
+ const [text, memoryGb] = await Promise.all([
+ fetchExternal(hfTreeApi(link.repo)),
+ getMaxVramGb().catch(() => 0),
+ ])
+ const entries = JSON.parse(text) as unknown
if (gone) return
+ const budgetBytes = quantBudgetBytes(chatModelBudgetGb(isMacOS(), memoryGb || null, null))
+ setBudget(budgetBytes)
if (!Array.isArray(entries)) {
setLoad({ state: 'failed', message: 'Hugging Face has no public model repository under this name.' })
return
@@ -51,7 +61,7 @@ export function HfLinkDialog({ link, onCancel, onConfirm }: Props) {
setLoad({ state: 'failed', message: 'This repository has no GGUF model file. Locally Uncensored runs GGUF models.' })
return
}
- const named = link.file ? choiceForFile(choices, link.file) : defaultChoice(choices)
+ const named = link.file ? choiceForFile(choices, link.file) : defaultChoice(choices, budgetBytes)
if (!named) {
setLoad({ state: 'failed', message: 'The repository has no model file under the name the link gives.' })
return
@@ -94,7 +104,7 @@ export function HfLinkDialog({ link, onCancel, onConfirm }: Props) {
>
{load.choices.map((c) => (
<option key={c.path} value={c.path} disabled={!!c.incomplete}>
- {c.path} · {c.quant ?? 'GGUF'} · {sizeLabel(c.bytes)}{c.incomplete ? ` · ${incompleteLabel(c.incomplete)}` : c.parts > 1 ? ` · ${c.parts} parts` : ''}
+ {c.path} · {c.quant ?? 'GGUF'} · {sizeLabel(c.bytes)}{c.incomplete ? ` · ${incompleteLabel(c.incomplete)}` : c.parts > 1 ? ` · ${c.parts} parts` : ''}{c.incomplete ? '' : overBudgetLabel(c.bytes, budget)}
</option>
))}
</select>
@@ -108,7 +118,7 @@ export function HfLinkDialog({ link, onCancel, onConfirm }: Props) {
<dd className="text-gray-800 dark:text-gray-100" data-testid="hf-link-quant">{choice.quant ?? 'not in the name'}</dd>
<dt className="text-gray-500">Size</dt>
<dd className="text-gray-800 dark:text-gray-100" data-testid="hf-link-size">
- {sizeLabel(choice.bytes)}{choice.parts > 1 ? ` in ${choice.parts} parts` : ''}
+ {sizeLabel(choice.bytes)}{choice.parts > 1 ? ` in ${choice.parts} parts` : ''}{choice.incomplete ? '' : overBudgetLabel(choice.bytes, budget)}
</dd>
{choice.incomplete && (
<>
diff --git a/src/lib/hf-link.ts b/src/lib/hf-link.ts
index e804e297..92ac21f8 100644
--- a/src/lib/hf-link.ts
+++ b/src/lib/hf-link.ts
@@ -136,11 +136,24 @@ export function choiceForFile(choices: readonly HfLinkChoice[], file: string): H
/** The row preselected when the link names no file: Q4_K_M, else the
* smallest, a complete one before an incomplete split set. */
-export function defaultChoice(choices: readonly HfLinkChoice[]): HfLinkChoice | null {
+export function defaultChoice(choices: readonly HfLinkChoice[], budgetBytes?: number): HfLinkChoice | null {
const loadable = choices.filter((c) => !c.incomplete)
+ // D7 (GitHub #215): with the memory known, the largest file that leaves
+ // room for the context (quantBudgetBytes), not a Q4_K_M that does not fit.
+ if (budgetBytes && budgetBytes > 0) {
+ const fitting = loadable
+ .filter((c) => c.quant && c.bytes > 0 && c.bytes <= budgetBytes)
+ .sort((a, b) => b.bytes - a.bytes)[0]
+ if (fitting) return fitting
+ }
return loadable.find((c) => c.quant === 'Q4_K_M') ?? loadable[0] ?? choices[0] ?? null
}
+/** D7: the words after a file that will not fit fully in graphics memory. */
+export function overBudgetLabel(bytes: number, budgetBytes?: number): string {
+ return budgetBytes && bytes > budgetBytes ? " · won't fit fully in GPU memory" : ''
+}
+
/** The line a split set with parts missing gets. */
export function incompleteLabel(gap: ShardGap): string {
return `incomplete: ${gap.have} of ${gap.of} parts, try again later`