Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.
TypeScript ai-meeting-assistantai-notetakerelectrongranola-alternativelinuxllama-cpplocal-ailocal-firstmacosmcpmeeting-minutesmeeting-notesoffline-firstopen-sourceprivacyspeech-to-texttranscriptionwhisperwhisper-cppwindows
With a graphics card next to built-in graphics, the notes model plans for the card's own memory and leaves room for whisper-server; when the card runs out of memory it loads again with half the layers, then on the processor, and remembers that; the card is named for the card (#165)
christianmat3e8012342a5a
diff --git a/app/src/engine/handler.ts b/app/src/engine/handler.tsindex 8573a918..970f0dfd 100644--- a/app/src/engine/handler.ts+++ b/app/src/engine/handler.ts@@ -14,7 +14,7 @@ export function createHandler(llm: Llm, send: (e: EngineEvent) => void) {const run = serial()const handle = async (req: EngineRequest): Promise<unknown> => {- if (req.type === 'load') return llm.load(req.modelPath, req.contextSize, req.minContext)+ if (req.type === 'load') return llm.load(req.modelPath, req.contextSize, req.minContext, req.gpuLayers)if (req.type === 'unload') return llm.unload()if (req.type === 'count') return llm.count(req.texts)if (req.type === 'embed') return llm.embed(req.modelPath, req.texts)diff --git a/app/src/engine/llm.ts b/app/src/engine/llm.tsindex 632027aa..d1355f78 100644--- a/app/src/engine/llm.ts+++ b/app/src/engine/llm.ts@@ -3,8 +3,9 @@ import { cleanAnswer, streamCleaner } from './control'import { samplingFor } from './sampling'import { holds } from './prefix'import { engineThreads } from './threads'+import { vramCap } from './vram'import { availableParallelism } from 'node:os'-import type { EngineMessage } from '../shared/engine-protocol'+import { outOfGraphicsMemory, type EngineMessage } from '../shared/engine-protocol'const toHistory = (messages: EngineMessage[]): ChatHistoryItem[] =>messages.map((m) => (m.role === 'system' ? { type: 'system', text: m.content } : m.role === 'user' ? { type: 'user', text: m.content } : { type: 'model', response: [m.content] }))@@ -12,7 +13,8 @@ const toHistory = (messages: EngineMessage[]): ChatHistoryItem[] =>/*** The notes model itself: load, count tokens, write. Used by the worker process. Callers run one thing at a time (the worker's serial()).*/-export function createLlm() {+export function createLlm(o: { platform?: string } = {}) {+ const platform = o.platform ?? process.platformlet llama: Llama | undefined/** the processor alone, when the graphics have no room at all (#57) */let cpuLlama: Llama | undefined@@ -25,7 +27,20 @@ export function createLlm() {// YOGURT_ENGINE_GPU=off: the graphics card crashed the engine before, on Windows or Linux; =vulkan: the default// (CUDA) build found no card but Vulkan did (#32). Both come from src/main/engine.ts.const gpu = process.env.YOGURT_ENGINE_GPU- const getL = async () => (llama ??= await getLlama(gpu === 'off' ? { gpu: false } : gpu === 'vulkan' ? { gpu: 'vulkan' } : undefined))+ /** the graphics memory as node-llama-cpp found it, before the cap below: what the probe reports */+ let found: { total: number; unifiedSize: number } | undefined+ /** plans only for the card's own memory, less room for whisper-server (#165: a 4 GB card counted as 21 GB) */+ const fitCard = async (l: Llama): Promise<Llama> => {+ if (!l.gpu) return l+ found = await l.getVramState()+ const cap = vramCap(found, platform)+ if (cap !== null) { await l.setVramCap(cap); console.info(`notes engine: plans for ${(cap / 1024 ** 3).toFixed(1)} GiB of graphics memory`) }+ return l+ }+ const getL = async (): Promise<Llama> => {+ if (!llama) llama = await fitCard(await getLlama(gpu === 'off' ? { gpu: false } : gpu === 'vulkan' ? { gpu: 'vulkan' } : undefined))+ return llama+ }// Gemma's auto wrapper requests thinking; a zero token budget cuts it off instead of disabling it.const threads = (l: Llama) => { const n = engineThreads(process.platform, l.cpuMathCores, availableParallelism()); return n === undefined ? {} : { threads: n } }const chatWrapper = () => model?.fileInfo.metadata.general.architecture === 'gemma4' ? new Gemma4ChatWrapper({ reasoning: false }) : 'auto' as const@@ -47,7 +62,8 @@ export function createLlm() {/** the graphics this engine can use: a Mac never asks */async probe() {const l = await getL()- const v = await l.getVramState()+ // as found, not as capped: the picker takes the card's own memory from it (main/hardware.ts)+ const v = found ?? await l.getVramState()const GB = 1e9return { gpuType: l.gpu, vramTotalGB: v.total / GB, unifiedGB: v.unifiedSize / GB, gpuNames: await l.getGpuDeviceNames() }},@@ -67,9 +83,11 @@ export function createLlm() {return out},/** gpu: what it runs on (cuda, vulkan, metal, or false: the processor alone), for the log */- async load(modelPath: string, contextSize: number, minContext: number): Promise<{ contextSize: number; gpu: string | false; gpuLayers: number }> {+ /** maxGpuLayers: the most layers on the card, after it ran out of memory with more (#165); 0: the processor alone */+ async load(modelPath: string, contextSize: number, minContext: number, maxGpuLayers?: number): Promise<{ contextSize: number; gpu: string | false; gpuLayers: number }> {await unload()- const l = await getL()+ // the processor alone never touches the graphics+ const l = maxGpuLayers === 0 ? (cpuLlama ??= await getLlama({ gpu: false })) : await getL()const size = { min: Math.min(minContext, contextSize), max: contextSize }// The model fills the graphics card first and keeps room for only a tiny context; on a card with little memory the// notes' context then doesn't fit (InsufficientMemoryError, every summary failing). So: load again leaving room for@@ -77,8 +95,11 @@ export function createLlm() {// A model that doesn't fit on the card at all can fail to load outright (#37): that gets the same fewer layers.// Integrated graphics can say the context won't fit even with no layers on them (an Intel Arc, #57): last, the// graphics are left out altogether and the processor does it all.- const steps: Array<{ cpu?: true; gpuLayers?: { fitContext: { contextSize: number } } | 0 }> =- [{}, { gpuLayers: { fitContext: { contextSize: size.min } } }, { gpuLayers: 0 }, ...(l.gpu ? [{ cpu: true as const }] : [])]+ // With a cap the same steps, never over it.+ const max = maxGpuLayers ? { max: maxGpuLayers } : {}+ type Step = { cpu?: true; gpuLayers?: { max?: number; fitContext?: { contextSize: number } } | 0 }+ const steps: Step[] = maxGpuLayers === 0 ? [{ cpu: true }]+ : [maxGpuLayers ? { gpuLayers: max } : {}, { gpuLayers: { ...max, fitContext: { contextSize: size.min } } }, { gpuLayers: 0 }, ...(l.gpu ? [{ cpu: true as const }] : [])]let used = lfor (const [i, step] of steps.entries()) {const last = i === steps.length - 1@@ -88,16 +109,24 @@ export function createLlm() {console.warn('the notes model did not load; loading it again with fewer layers on the graphics', (e as Error).message)continue}- try { context = await model.createContext({ contextSize: size, ...threads(used) }); break } catch (e) {+ try { context = await model.createContext({ contextSize: size, ...threads(used) }) } catch (e) {if (!(e instanceof InsufficientMemoryError) || last) throw econsole.warn('the notes did not fit next to the model; loading it again with fewer layers on the graphics', e.message)await model.dispose(); model = undefined+ continue+ }+ main = context.getSequence()+ // the first evaluation pages the weights in from disk: pay it here, not on the first word of the notes. The card+ // can run out of memory only now, as it first computes (#165): fewer layers again.+ try { await main.evaluateWithoutGeneratingNewTokens(model.tokenize('Hello')); break } catch (e) {+ if (!outOfGraphicsMemory((e as Error).message) || last) throw e+ console.warn('the graphics card ran out of memory reading in; loading it again with fewer layers on the graphics', (e as Error).message)+ main = undefined+ await context.dispose(); context = undefined+ await model.dispose(); model = undefined}}- if (!model || !context) throw new Error('The notes model did not load')- main = context.getSequence()- // the first evaluation pages the weights in from disk: pay it here, not on the first word of the notes- await main.evaluateWithoutGeneratingNewTokens(model.tokenize('Hello'))+ if (!model || !context || !main) throw new Error('The notes model did not load')return { contextSize: context.contextSize, gpu: model.gpuLayers === 0 ? false : used.gpu, gpuLayers: model.gpuLayers }},count(texts: string[]): number[] {diff --git a/app/src/engine/vram.ts b/app/src/engine/vram.tsnew file mode 100644index 00000000..c108d717--- /dev/null+++ b/app/src/engine/vram.ts@@ -0,0 +1,20 @@+const GiB = 1024 ** 3+/** whisper-server on the same card: large-v3-turbo's 0.57 GB, beam 5's buffers and Vulkan's own, with a little to spare */+export const WHISPER_VRAM = 1.25 * GiB+/** node-llama-cpp's own safety margin (its defaultLlamaVramPadding), for the card's memory alone */+const margin = (bytes: number) => Math.floor(Math.min(bytes * 0.08, 1.6 * GiB))++/**+ * Windows and Linux: how much graphics memory the notes model may plan for, or null for node-llama-cpp's own count (#165).+ * With a card next to graphics built into the processor, llama.cpp runs on the card alone, but node-llama-cpp adds the+ * shared memory the built-in graphics could use to the card's own: 21.2 GB for a 4 GB RTX A2000 next to an Iris Xe, so+ * every layer and a 32k context went on the card. whisper-server sits on the same card too.+ */+export function vramCap(s: { total: number; unifiedSize: number }, platform: string): number | null {+ if (platform === 'darwin') return null+ const own = s.total - s.unifiedSize+ // no card, or a small one: as before (the same 2 GB as main/hardware.ts)+ if (own < 2e9) return null+ // with built-in graphics, node-llama-cpp's margin came off the whole 21 GB: it goes on the card's own here+ return Math.max(0, Math.floor(own - (s.unifiedSize > 0 ? margin(own) : 0) - WHISPER_VRAM))+}diff --git a/app/src/main/engine.ts b/app/src/main/engine.tsindex f1e7cc70..4e89d6e5 100644--- a/app/src/main/engine.ts+++ b/app/src/main/engine.ts@@ -1,10 +1,19 @@import { utilityProcess, type UtilityProcess } from 'electron'-import type { EngineEvent, EngineMessage, EngineRequest } from '../shared/engine-protocol'+import { outOfGraphicsMemory, type EngineEvent, type EngineMessage, type EngineRequest } from '../shared/engine-protocol'+export { outOfGraphicsMemory }import type { GpuProbe } from './hardware'export class InsufficientMemoryError extends Error { name = 'InsufficientMemoryError' }/** Windows and Linux: the graphics card took too long (or crashed), so the engine starts again without it; try once more */export class GraphicsGaveUpError extends Error { name = 'GraphicsGaveUpError' }+/** the card ran out of memory: the engine starts again with fewer layers on it, each time down to the processor (#165) */+export class GraphicsFullError extends GraphicsGaveUpError { name = 'GraphicsFullError' }++/** after the card ran out of memory with this many layers on it: the most for the next try, 0 for the processor alone */+export const fewerLayers = (layers: number): number => layers >= 8 ? Math.floor(layers / 2) : 0+/** the most layers a model may put on the card (kept in settings, so the next launch doesn't run out again) */+export type GpuLayers = { model: string; layers: number }+const fileName = (path: string) => path.split(/[\\/]/).pop() ?? path/*** Off a Mac, how long a step may take before the graphics card counts as stuck (a hang, not a crash: some drivers do).@@ -75,16 +84,41 @@ export class UtilityEngine implements Engine {private limits: Limitsprivate backend: Backend+ /** the cap on layers after the card ran out of memory (#165), and what the model in this process put on the card */+ private gpuLayers: GpuLayers | undefined+ private onCard: GpuLayers | undefined+ /** the model being loaded or last loaded */+ private model = ''/*** cpuCrashes (Linux without the shim): the engine dies on the processor alone (code 132: Electron's allocator refuses* llama.cpp's single > 2 GiB weight buffer), so a lost graphics card starts the engine again on the card, not without it.* preload: the shim that prevents that crash (engineShim), put in the engine's LD_PRELOAD.* backends (backendOrder): what probe() checks the graphics with until one finds a card; onBackend: the one that did.+ * gpuLayers: the cap kept from an earlier launch; onGpuLayers: a new one, after the card ran out of memory (#165).*/- constructor(private workerPath: string, private opts: { gpuFallback?: boolean; cpuCrashes?: boolean; preload?: string; backends?: Backend[]; onBackend?: (b: Backend) => void } & Partial<Limits> = {}) {+ constructor(private workerPath: string, private opts: { gpuFallback?: boolean; cpuCrashes?: boolean; preload?: string; backends?: Backend[]; onBackend?: (b: Backend) => void; gpuLayers?: GpuLayers; onGpuLayers?: (l: GpuLayers) => void } & Partial<Limits> = {}) {this.limits = { ...WATCH, ...opts }this.backend = opts.backends?.[0] ?? 'auto'+ this.gpuLayers = opts.gpuLayers+ }++ /** the cap for this model, if it ran out of memory before */+ private capFor(model: string) { return this.gpuLayers?.model === model ? this.gpuLayers.layers : undefined }++ /**+ * The card ran out of memory (#165: a 4 GB card given every layer and a 32k context): the next engine gets half the+ * layers, then the processor alone, and that is kept. On the processor already, there is nothing to step down from.+ */+ private outOfMemory(message: string): boolean {+ if (!this.opts.gpuFallback || this.cpuOnly || !this.model || !outOfGraphicsMemory(message)) return false+ const was = this.onCard?.model === this.model ? this.onCard.layers : undefined+ if (was === 0 || this.capFor(this.model) === 0) return false+ // a load that still ran out (its own fewer layers did not help): the processor+ this.gpuLayers = { model: this.model, layers: was === undefined ? 0 : fewerLayers(was) }+ console.warn(`notes engine: the graphics card ran out of memory (${message}); starting it again ${this.gpuLayers.layers ? `with at most ${this.gpuLayers.layers} layers on it` : 'without the graphics card'}`)+ this.opts.onGpuLayers?.(this.gpuLayers)+ return true}/** a different backend means a fresh engine process, and a fresh try on the card */@@ -116,6 +150,7 @@ export class UtilityEngine implements Engine {private drop(error: () => Error) {const proc = this.procthis.proc = undefined+ this.onCard = undefinedconst waiting = [...this.pending.values()]this.pending.clear()proc?.kill()@@ -145,7 +180,11 @@ export class UtilityEngine implements Engine {clearTimeout(p.timer)if (e.type === 'result' && p.model) this.loaded = trueif (e.type === 'result') p.resolve(e.data)- else if (this.opts.gpuFallback && deviceLost(e.message)) {+ else if (this.outOfMemory(e.message)) {+ // a fresh process: one that ran out may not give the memory back+ this.pending.set(e.id, p)+ this.drop(() => new GraphicsFullError(`The graphics card ran out of memory: ${e.message}`))+ } else if (this.opts.gpuFallback && deviceLost(e.message)) {// the card was reset under it: a fresh engine (on the processor, where that works) is the only way onif (!this.opts.cpuCrashes) this.cpuOnly = trueconsole.warn(`notes engine: the graphics card was lost (${e.message}); starting it again${this.cpuOnly ? ' without the graphics card' : ''}`)@@ -157,6 +196,7 @@ export class UtilityEngine implements Engine {// stopped as stuck (drop): already dealt withif (this.proc !== proc) returnthis.proc = undefined+ this.onCard = undefinedconst loading = !!this.opts.gpuFallback && !this.loaded && [...this.pending.values()].some((p) => p.load)const starting = loading && !this.cpuOnly// it died starting without the card too (Linux, code 132): staying off the card would only crash again, so the@@ -212,10 +252,17 @@ export class UtilityEngine implements Engine {return done}load(modelPath: string, contextSize: number, minContext: number) {- console.info('NOTES', `loading the notes model ${modelPath.split(/[\\/]/).pop()}${this.opts.gpuFallback ? (this.cpuOnly ? ' without the graphics card' : ' (graphics card allowed)') : ''}`)- const { id, done } = this.call<{ contextSize: number; gpu?: string | false; gpuLayers?: number }>({ type: 'load', modelPath, contextSize, minContext })+ const model = this.model = fileName(modelPath)+ this.onCard = undefined+ const cap = this.capFor(model)+ console.info('NOTES', `loading the notes model ${model}${this.opts.gpuFallback ? (this.cpuOnly || cap === 0 ? ' without the graphics card' : ` (graphics card allowed${cap ? `, at most ${cap} layers: it ran out of memory with more` : ''})`) : ''}`)+ const { id, done } = this.call<{ contextSize: number; gpu?: string | false; gpuLayers?: number }>({ type: 'load', modelPath, contextSize, minContext, ...(cap !== undefined ? { gpuLayers: cap } : {}) })this.watch(id, 'loading the model', this.limits.loadMs, this.limits.cpuLoadMs)- return done.then((r) => { console.info('NOTES', `notes model loaded: context ${r.contextSize}, graphics ${r.gpu === undefined ? 'unknown' : r.gpu || 'none'}${r.gpu && r.gpuLayers !== undefined ? ` (${r.gpuLayers} layers)` : ''}`); return r })+ return done.then((r) => {+ if (this.model === model && r.gpu !== undefined) this.onCard = { model, layers: r.gpu ? r.gpuLayers ?? 0 : 0 }+ console.info('NOTES', `notes model loaded: context ${r.contextSize}, graphics ${r.gpu === undefined ? 'unknown' : r.gpu || 'none'}${r.gpu && r.gpuLayers !== undefined ? ` (${r.gpuLayers} layers)` : ''}`)+ return r+ })}async unload() { if (this.proc) await this.call({ type: 'unload' }).done }count(texts: string[]) { return this.call<number[]>({ type: 'count', texts }).done }diff --git a/app/src/main/hardware.ts b/app/src/main/hardware.tsindex cb7e074f..ddad81c5 100644--- a/app/src/main/hardware.ts+++ b/app/src/main/hardware.ts@@ -7,6 +7,17 @@ export type SysInfo = { platform: string; arch: string; cpuModel: string; totalR/** What the notes engine found (node-llama-cpp): the graphics it can use, their memory, their names. gpuType false: none */export type GpuProbe = { gpuType: string | false; vramTotalGB: number; unifiedGB: number; gpuNames: string[] }+/**+ * Graphics built into the processor, by the name the engine reports (it gives names, not kinds). Intel's Iris, UHD, HD+ * and plain "Graphics" (an Arc without a model number is built in; an A770 or B580 is a card), AMD's Radeon Graphics,+ * Vega and 680M-890M, and the software renderer.+ */+export const integratedGpu = (name: string): boolean =>+ /\bIntel\b.*\b(Iris|UHD|HD Graphics)\b/i.test(name) || /^Intel(\(R\))? Graphics\b/i.test(name)+ || (/\bIntel\b.*\bArc\b/i.test(name) && !/\b[AB]\d{3}M?\b/.test(name))+ || /\bRadeon(\(TM\))?( Vega \d+)? Graphics\b/i.test(name) || /\bRadeon(\(TM\))? \d{3}M\b/i.test(name)+ || /^llvmpipe\b/i.test(name)+/*** A Mac (Apple Silicon) shares memory with its graphics: no probe needed, as always. Windows and Linux ask the notes* engine what it can use: a card with its own memory, graphics sharing the memory, or none (also when the@@ -17,7 +28,9 @@ export function toHardware(sys: SysInfo, probe?: GpuProbe | null): Hardware {// A card next to graphics built into the processor: node-llama-cpp adds the card's memory to the shared memory, but// llama.cpp runs on the card, so it's a card with what's left once the shared part is taken out (#37)const ownGB = probe ? probe.vramTotalGB - probe.unifiedGB : 0- const kind = mac ? 'unified' : !probe?.gpuType ? 'none' : probe.unifiedGB > 0 && ownGB < 2 ? 'unified' : 'discrete'+ // names that are all built-in graphics are never called a card, whatever the memory says (#165)+ const builtIn = !!probe?.gpuNames.length && probe.gpuNames.every(integratedGpu)+ const kind = mac ? 'unified' : !probe?.gpuType ? 'none' : builtIn || (probe.unifiedGB > 0 && ownGB < 2) ? 'unified' : 'discrete'return {os: sys.platform as OS,arch: sys.arch,@@ -25,7 +38,8 @@ export function toHardware(sys: SysInfo, probe?: GpuProbe | null): Hardware {totalRamGB: Math.round((sys.totalRamBytes / 1e9) * 10) / 10,freeDiskGB: Math.round(sys.freeDiskGB * 10) / 10,gpu: mac ? { kind, name: sys.cpuModel, vramGB: 0 }- : { kind, name: kind === 'none' ? '' : probe?.gpuNames[0] ?? '', vramGB: kind === 'none' ? 0 : Math.round((kind === 'discrete' ? ownGB : probe?.vramTotalGB ?? 0) * 10) / 10 },+ // the card by name, never the built-in graphics next to it, whichever comes first (#165)+ : { kind, name: kind === 'none' ? '' : (kind === 'discrete' && probe?.gpuNames.find((n) => !integratedGpu(n))) || (probe?.gpuNames[0] ?? ''), vramGB: kind === 'none' ? 0 : Math.round((kind === 'discrete' ? ownGB : probe?.vramTotalGB ?? 0) * 10) / 10 },...(!mac && sys.cores ? { cores: sys.cores } : {}),}}diff --git a/app/src/main/index.ts b/app/src/main/index.tsindex adab4ecb..eefb7269 100644--- a/app/src/main/index.ts+++ b/app/src/main/index.ts@@ -720,10 +720,13 @@ app.whenReady().then(() => {const shim = engineShim(process.platform, [process.resourcesPath && join(process.resourcesPath, 'bin', SHIM), join(__dirname, '../../resources/bin', SHIM)].filter((x): x is string => !!x), existsSync)if (process.platform === 'linux') console.info('NOTES', shim ? `big allocations go through ${shim}` : `${SHIM} is missing: the notes engine can crash on the processor`)// Windows and Linux: a CUDA build that won't start finds no card; Vulkan is tried next, and kept when it finds one (#32)- const backends = backendOrder(process.platform, process.env, loadSettings(settingsFile).notesGpuBackend)+ const saved = loadSettings(settingsFile)+ const backends = backendOrder(process.platform, process.env, saved.notesGpuBackend)const engine = isFake() ? new FakeEngine() : new UtilityEngine(join(__dirname, 'engine.js'), {gpuFallback: process.platform !== 'darwin', cpuCrashes: process.platform === 'linux' && !shim, ...(shim ? { preload: shim } : {}),backends, onBackend: (b) => { console.info('NOTES', `graphics found with ${b === 'auto' ? 'the default build' : b}; kept for next time`); updateSettings(settingsFile, { notesGpuBackend: b === 'vulkan' ? b : undefined }) },+ // the card ran out of memory (#165): fewer layers from the next launch on, too+ ...(saved.notesGpuLayers ? { gpuLayers: saved.notesGpuLayers } : {}), onGpuLayers: (l) => updateSettings(settingsFile, { notesGpuLayers: l }),})if (engine instanceof UtilityEngine) probeGpu = () => engine.probe().then((g) => {console.info('NOTES', `graphics: ${g.gpuType || 'none'}${g.gpuNames.length ? ` (${g.gpuNames.join(', ')})` : ''}, ${g.vramTotalGB.toFixed(1)} GB`)diff --git a/app/src/main/notes/model.ts b/app/src/main/notes/model.tsindex a6c958a8..d3283df2 100644--- a/app/src/main/notes/model.ts+++ b/app/src/main/notes/model.ts@@ -1,5 +1,5 @@import { CONTEXT, MIN_CONTEXT, type EngineMessage } from '../../shared/engine-protocol'-import { GraphicsGaveUpError, type Engine } from '../engine'+import { GraphicsFullError, GraphicsGaveUpError, type Engine } from '../engine'import type { Llm } from './enhance'import { readInSteps } from './readAhead'@@ -16,6 +16,9 @@ export function heldMatch(held: string, prompt: string): string {return `differs from what was read ahead at char ${same.toLocaleString('en-US')} of ${held.length.toLocaleString('en-US')} (line ${line}): read again from there`}+/** steps down when the card runs out of memory: 43 layers, 21, 10, 5, then the processor */+const FULL_TRIES = 5+/** an earlier prompt and answer, as the conversation they were */const before = (pairs: string[] = []): EngineMessage[] => pairs.map((content, i) => ({ role: i % 2 ? 'assistant' : 'user', content }))@@ -50,10 +53,14 @@ export function createNotesModel(o: { engine: Engine; modelPath: () => string |}).finally(() => { loading = undefined })return loading}- /** Windows and Linux: the graphics card gave up (stuck or crashed while starting); the engine now runs without it, once more */- const again = <T>(run: () => Promise<T>, ok = () => true): Promise<T> => run().catch((e) => {+ /**+ * Windows and Linux: the graphics card gave up (stuck or crashed while starting); the engine now runs without it, once+ * more. Out of memory on it, once for each step down to the processor (half the layers each time, #165).+ */+ const again = <T>(run: () => Promise<T>, ok = () => true, full = 0): Promise<T> => run().catch((e) => {if (!(e instanceof GraphicsGaveUpError) || !ok()) throw eloaded = undefined; loading = undefined; held = ''+ if (e instanceof GraphicsFullError && full < FULL_TRIES) return again(run, ok, full + 1)return run()})const load = () => again(ensure)diff --git a/app/src/main/settings.ts b/app/src/main/settings.tsindex e349d61e..ab22a8f0 100644--- a/app/src/main/settings.ts+++ b/app/src/main/settings.ts@@ -14,6 +14,8 @@ export type Settings = { theme?: 'light' | 'dark'; language?: string; /** what tnotesUpgradeSkipped?: boolean/** Windows and Linux: the notes engine found the graphics card with Vulkan, not its default (CUDA) build (#32) */notesGpuBackend?: 'vulkan'+ /** Windows and Linux: the most layers this notes model may put on the graphics card, after it ran out of memory with more (#165); 0: the processor */+ notesGpuLayers?: { model: string; layers: number }/** home's Finish setup was put away while these were missing; it comes back only when something else is */setupDismissed?: import('./permissions').PermissionKind[]/** opens when the Mac starts; off unless the person said yes */diff --git a/app/src/shared/engine-protocol.ts b/app/src/shared/engine-protocol.tsindex f78658ed..c180576d 100644--- a/app/src/shared/engine-protocol.ts+++ b/app/src/shared/engine-protocol.ts@@ -3,11 +3,16 @@export const CONTEXT = 32_768export const MIN_CONTEXT = 8192+/** the graphics card ran out of its own memory (Vulkan or CUDA), as a load or the first words computed on it (#165) */+export const outOfGraphicsMemory = (message: string): boolean =>+ /ErrorOutOfDeviceMemory|VK_ERROR_OUT_OF_DEVICE_MEMORY|CUDA error: out of memory|cudaMalloc failed: out of memory/i.test(message)+export type EngineMessage = { role: 'system' | 'user' | 'assistant'; content: string }export type EngineRequest =/** contextSize: the most worth having; the worker takes what memory allows down to minContext */- | { id: number; type: 'load'; modelPath: string; contextSize: number; minContext: number }+ /** gpuLayers: the most layers on the graphics card (it ran out of memory with more, #165); 0: the processor alone */+ | { id: number; type: 'load'; modelPath: string; contextSize: number; minContext: number; gpuLayers?: number }| { id: number; type: 'unload' }/** tokens in each text, by the loaded model's tokenizer */| { id: number; type: 'count'; texts: string[] }diff --git a/app/test/engineOutOfMemory.test.ts b/app/test/engineOutOfMemory.test.tsnew file mode 100644index 00000000..ffea8bf2--- /dev/null+++ b/app/test/engineOutOfMemory.test.ts@@ -0,0 +1,114 @@+import { EventEmitter } from 'node:events'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++/** a stand-in utility process: records what it was sent and how it was started; answers only when told */+class Proc extends EventEmitter {+ sent: any[] = []+ killed = false+ constructor(public env?: Record<string, string | undefined>) { super() }+ postMessage(m: any) { this.sent.push(m) }+ kill() { if (this.killed) return true; this.killed = true; queueMicrotask(() => this.emit('exit', 1)); return true }+ last(type: string) { return this.sent.filter((x) => x.type === type).at(-1) }+ answer(type: string, data: unknown = null) { this.emit('message', { id: this.last(type).id, type: 'result', data }) }+ fail(type: string, message: string) { this.emit('message', { id: this.last(type).id, type: 'error', message }) }+}+const procs: Proc[] = []+vi.mock('electron', () => ({ utilityProcess: { fork: (_p: string, _a: string[], o: { env?: Record<string, string> }) => { const p = new Proc(o.env); procs.push(p); return p } } }))+const { UtilityEngine, GraphicsGaveUpError, GraphicsFullError, fewerLayers, outOfGraphicsMemory } = await import('../src/main/engine')++const chat = { messages: [{ role: 'user' as const, content: 'hi' }] }+const OOM = 'vk::Device::allocateMemory: ErrorOutOfDeviceMemory'++beforeEach(() => { procs.length = 0; vi.spyOn(console, 'warn').mockImplementation(() => {}); vi.spyOn(console, 'error').mockImplementation(() => {}); vi.spyOn(console, 'info').mockImplementation(() => {}) })+afterEach(() => { vi.restoreAllMocks() })++describe('the graphics card running out of memory (#165)', () => {+ it('knows Vulkan and CUDA running out of memory, and nothing else', () => {+ expect(outOfGraphicsMemory(OOM)).toBe(true)+ expect(outOfGraphicsMemory('VK_ERROR_OUT_OF_DEVICE_MEMORY')).toBe(true)+ expect(outOfGraphicsMemory('CUDA error: out of memory')).toBe(true)+ expect(outOfGraphicsMemory('ggml_backend_cuda_buffer_type_alloc_buffer: allocating 512.00 MiB on device 0: cudaMalloc failed: out of memory')).toBe(true)+ expect(outOfGraphicsMemory('vk::Queue::submit: ErrorDeviceLost')).toBe(false)+ expect(outOfGraphicsMemory('Last message must be from the user')).toBe(false)+ })++ it('each time: half the layers, then the processor alone', () => {+ expect(fewerLayers(43)).toBe(21)+ expect(fewerLayers(21)).toBe(10)+ expect(fewerLayers(10)).toBe(5)+ expect(fewerLayers(5)).toBe(0)+ expect(fewerLayers(0)).toBe(0)+ })+})++describe('the notes engine when the card runs out of memory (#165)', () => {+ const load = async (e: InstanceType<typeof UtilityEngine>, layers: number, file = 'C:\\m\\gemma-4-e4b.gguf') => {+ const l = e.load(file, 32768, 8192)+ const p = procs.at(-1)!+ p.answer('load', { contextSize: 32768, gpu: layers ? 'vulkan' : false, gpuLayers: layers })+ await l+ return p+ }++ it('at the first question: a fresh engine with half the layers, kept for next launch, and a give-up the notes try again', async () => {+ const saved: unknown[] = []+ const e = new UtilityEngine('engine.js', { gpuFallback: true, onGpuLayers: (l) => saved.push(l) })+ const first = await load(e, 43)+ expect(first.last('load').gpuLayers).toBeUndefined()+ const c = e.chat(chat, () => {}).catch((x) => x)+ first.fail('chat', OOM)+ const err = await c+ expect(err).toBeInstanceOf(GraphicsFullError)+ expect(err).toBeInstanceOf(GraphicsGaveUpError)+ expect(first.killed).toBe(true)+ expect(saved).toEqual([{ model: 'gemma-4-e4b.gguf', layers: 21 }])+ // the card stays on: only fewer layers+ const second = await load(e, 21)+ expect(second.env?.YOGURT_ENGINE_GPU).toBeUndefined()+ expect(second.last('load').gpuLayers).toBe(21)+ })++ it('reading a meeting in ahead counts too; down to the processor, where it stops stepping', async () => {+ const saved: unknown[] = []+ const e = new UtilityEngine('engine.js', { gpuFallback: true, onGpuLayers: (l) => saved.push(l) })+ for (const layers of [43, 21, 10, 5]) {+ const p = await load(e, layers)+ const r = e.preload(chat.messages).catch((x) => x)+ p.fail('preload', OOM)+ expect(await r).toBeInstanceOf(GraphicsFullError)+ }+ expect(saved.map((s: any) => s.layers)).toEqual([21, 10, 5, 0])+ const cpu = await load(e, 0)+ expect(cpu.last('load').gpuLayers).toBe(0)+ // on the processor the card can't run out: a plain error, the engine keeps running+ const r = e.chat(chat, () => {}).catch((x) => x)+ cpu.fail('chat', OOM)+ expect(await r).not.toBeInstanceOf(GraphicsGaveUpError)+ expect(cpu.killed).toBe(false)+ })++ it('a load that still runs out (its own fewer layers did not help): straight to the processor', async () => {+ const saved: unknown[] = []+ const e = new UtilityEngine('engine.js', { gpuFallback: true, onGpuLayers: (l) => saved.push(l) })+ const l = e.load('/m/gemma-4-e4b.gguf', 32768, 8192).catch((x) => x)+ procs[0].fail('load', OOM)+ expect(await l).toBeInstanceOf(GraphicsFullError)+ expect(saved).toEqual([{ model: 'gemma-4-e4b.gguf', layers: 0 }])+ })++ it('what was kept from last time is used from the first load, for that model only', async () => {+ const e = new UtilityEngine('engine.js', { gpuFallback: true, gpuLayers: { model: 'gemma-4-e4b.gguf', layers: 10 } })+ const p = await load(e, 10)+ expect(p.last('load').gpuLayers).toBe(10)+ void e.load('/m/gemma-4-26b.gguf', 32768, 8192).catch(() => {})+ expect(p.last('load').gpuLayers).toBeUndefined()+ })++ it('a Mac never steps down', async () => {+ const e = new UtilityEngine('engine.js')+ const p = await load(e, 43)+ const c = e.chat(chat, () => {}).catch((x) => x)+ p.fail('chat', OOM)+ expect(await c).not.toBeInstanceOf(GraphicsGaveUpError)+ })+})diff --git a/app/test/hardware.test.ts b/app/test/hardware.test.tsindex 3ed1b7ab..9c010333 100644--- a/app/test/hardware.test.ts+++ b/app/test/hardware.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { toHardware } from '../src/main/hardware'+import { integratedGpu, toHardware } from '../src/main/hardware'const sys = { platform: 'darwin', arch: 'arm64', cpuModel: 'Apple M2', totalRamBytes: 8_589_934_592, freeDiskGB: 123.456 }@@ -31,6 +31,14 @@ describe('graphics on Windows and Linux (the notes engine checks the card)', ()expect(toHardware(pc, { gpuType: 'vulkan', vramTotalGB: 67.8, unifiedGB: 55.8, gpuNames: ['NVIDIA GeForce RTX 4070 Ti', 'AMD Radeon(TM) Graphics'] }).gpu).toEqual({ kind: 'discrete', name: 'NVIDIA GeForce RTX 4070 Ti', vramGB: 12 })})+ it('the card is named for the card, whichever order the graphics come in: never the built-in Iris Xe (#165)', () => {+ expect(toHardware(pc, { gpuType: 'vulkan', vramTotalGB: 21.2, unifiedGB: 17.0, gpuNames: ['Intel(R) Iris(R) Xe Graphics', 'NVIDIA RTX A2000 Laptop GPU'] }).gpu)+ .toEqual({ kind: 'discrete', name: 'NVIDIA RTX A2000 Laptop GPU', vramGB: 4.2 })+ expect(toHardware(pc, { gpuType: 'vulkan', vramTotalGB: 24, unifiedGB: 16, gpuNames: ['AMD Radeon(TM) 780M', 'AMD Radeon RX 7600M XT'] }).gpu.name).toBe('AMD Radeon RX 7600M XT')+ })+ it('built-in graphics alone are never called a card, even when none of their memory shows as shared (#165)', () => {+ expect(toHardware(pc, { gpuType: 'vulkan', vramTotalGB: 16, unifiedGB: 0, gpuNames: ['Intel(R) Iris(R) Xe Graphics'] }).gpu).toEqual({ kind: 'unified', name: 'Intel(R) Iris(R) Xe Graphics', vramGB: 16 })+ })it('no usable graphics, or a check that failed: the processor only', () => {expect(toHardware(pc, { gpuType: false, vramTotalGB: 0, unifiedGB: 0, gpuNames: [] }).gpu).toEqual({ kind: 'none', name: '', vramGB: 0 })expect(toHardware(pc, null).gpu.kind).toBe('none')@@ -46,3 +54,12 @@ describe('processor cores', () => {expect(toHardware({ ...sys, cores: 8 }).cores).toBeUndefined()})})++describe('graphics built into the processor, by name (#165)', () => {+ it.each(['Intel(R) Iris(R) Xe Graphics', 'Intel(R) UHD Graphics 770', 'Intel(R) HD Graphics 620', 'Intel(R) Graphics', 'Intel(R) Arc(TM) Graphics', 'AMD Radeon(TM) Graphics', 'AMD Radeon 780M Graphics', 'AMD Radeon(TM) 890M', 'AMD Radeon Vega 8 Graphics', 'AMD Radeon Graphics (RADV RENOIR)', 'llvmpipe (LLVM 17.0.6, 256 bits)'])('%s is built in', (name) => {+ expect(integratedGpu(name)).toBe(true)+ })+ it.each(['NVIDIA RTX A2000 Laptop GPU', 'NVIDIA GeForce RTX 4060 Laptop GPU', 'AMD Radeon RX 7900 XTX', 'AMD Radeon RX 7600M XT', 'AMD Radeon Pro W6800', 'Intel(R) Arc(TM) A770 Graphics', 'Intel(R) Arc(TM) B580 Graphics', 'Intel(R) Arc(TM) A370M Graphics'])('%s is a card', (name) => {+ expect(integratedGpu(name)).toBe(false)+ })+})diff --git a/app/test/llm.test.ts b/app/test/llm.test.tsindex c38bff8f..8c17534c 100644--- a/app/test/llm.test.ts+++ b/app/test/llm.test.ts@@ -2,13 +2,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import { Gemma4ChatWrapper, type LlamaChatSessionOptions } from 'node-llama-cpp'import { createLlm } from '../src/engine/llm'-const fake = vi.hoisted(() => ({ architecture: 'gemma4', sessions: [] as unknown[], loads: [] as unknown[], llamas: [] as unknown[], disposed: 0, contextFails: 0, loadFails: 0, contextError: undefined as (() => Error) | undefined }))+const fake = vi.hoisted(() => ({ architecture: 'gemma4', sessions: [] as unknown[], loads: [] as unknown[], llamas: [] as unknown[], disposed: 0, contextFails: 0, loadFails: 0, contextError: undefined as (() => Error) | undefined, warmFails: 0, vram: { total: 0, unifiedSize: 0 }, caps: [] as unknown[] }))vi.mock('node-llama-cpp', async (original) => {const actual = await original<typeof import('node-llama-cpp')>()- const sequence = { contextTokens: [], tokenMeter: { usedInputTokens: 0 }, evaluateWithoutGeneratingNewTokens: async () => {} }+ const sequence = { contextTokens: [], tokenMeter: { usedInputTokens: 0 }, evaluateWithoutGeneratingNewTokens: async () => { if (fake.warmFails > 0) { fake.warmFails--; throw new Error('vk::Device::allocateMemory: ErrorOutOfDeviceMemory') } } }return {...actual,- getLlama: async (opts?: { gpu?: false }) => (fake.llamas.push(opts), { gpu: opts?.gpu === false ? false : 'vulkan', loadModel: async (o: { gpuLayers?: unknown }) => {+ getLlama: async (opts?: { gpu?: false }) => (fake.llamas.push(opts), { gpu: opts?.gpu === false ? false : 'vulkan', getVramState: async () => ({ ...fake.vram, free: fake.vram.total, used: 0 }), setVramCap: async (b: number) => { fake.caps.push(b) }, getGpuDeviceNames: async () => [], loadModel: async (o: { gpuLayers?: unknown }) => {fake.loads.push(o.gpuLayers)if (fake.loadFails > 0 && o.gpuLayers !== 0) { fake.loadFails--; throw new Error('Failed to load model') }return {@@ -30,7 +30,7 @@ vi.mock('node-llama-cpp', async (original) => {}})-beforeEach(() => { fake.sessions.length = 0; fake.loads.length = 0; fake.llamas.length = 0; fake.disposed = 0; fake.contextFails = 0; fake.loadFails = 0; fake.contextError = undefined })+beforeEach(() => { fake.sessions.length = 0; fake.loads.length = 0; fake.llamas.length = 0; fake.disposed = 0; fake.contextFails = 0; fake.loadFails = 0; fake.contextError = undefined; fake.warmFails = 0; fake.vram = { total: 0, unifiedSize: 0 }; fake.caps.length = 0 })describe('model prompt wrapper', () => {it.each(['gemma4', 'qwen3', 'gpt-oss'])('preload and answers use the same format for %s', async (architecture) => {@@ -101,3 +101,34 @@ describe('too little room on the graphics card for the notes', () => {expect(fake.loads).toEqual([undefined])})})++describe('the card\'s real memory, and fewer layers after it ran out (#165)', () => {+ it('a card next to built-in graphics: the model plans for the card\'s own memory only', async () => {+ fake.vram = { total: 21.2 * 1024 ** 3, unifiedSize: 17.2 * 1024 ** 3 }+ await createLlm({ platform: 'win32' }).load('fixture.gguf', 32768, 8192)+ expect(fake.caps).toHaveLength(1)+ expect(fake.caps[0]).toBeLessThan(4 * 1024 ** 3)+ // the check of the graphics still reports them as found: the picker needs the whole picture+ const llm = createLlm({ platform: 'win32' })+ fake.llamas.length = 0+ expect(await llm.probe()).toMatchObject({ vramTotalGB: 21.2 * 1024 ** 3 / 1e9, unifiedGB: 17.2 * 1024 ** 3 / 1e9 })+ // a Mac: as before+ fake.caps.length = 0+ await createLlm({ platform: 'darwin' }).load('fixture.gguf', 32768, 8192)+ expect(fake.caps).toHaveLength(0)+ })+ it('with a cap from the engine: never more layers than that, then fewer, then the processor', async () => {+ fake.contextFails = 2+ expect(await createLlm().load('fixture.gguf', 32768, 8192, 21)).toMatchObject({ gpu: false, gpuLayers: 0 })+ expect(fake.loads).toEqual([{ max: 21 }, { max: 21, fitContext: { contextSize: 8192 } }, 0])+ })+ it('a cap of none: the processor alone, the graphics never touched', async () => {+ expect(await createLlm().load('fixture.gguf', 32768, 8192, 0)).toMatchObject({ gpu: false, gpuLayers: 0 })+ expect(fake.llamas).toEqual([{ gpu: false }])+ })+ it('running out at the first words read in: loaded again with fewer layers', async () => {+ fake.warmFails = 1+ expect(await createLlm().load('fixture.gguf', 32768, 8192)).toMatchObject({ gpu: 'vulkan', gpuLayers: 20 })+ expect(fake.loads).toEqual([undefined, { fitContext: { contextSize: 8192 } }])+ })+})diff --git a/app/test/notesModelFallback.test.ts b/app/test/notesModelFallback.test.tsindex 6db2d63a..b919add2 100644--- a/app/test/notesModelFallback.test.ts+++ b/app/test/notesModelFallback.test.ts@@ -1,9 +1,9 @@import { describe, expect, it, vi } from 'vitest'import { createNotesModel } from '../src/main/notes/model'-import { GraphicsGaveUpError, type Engine } from '../src/main/engine'+import { GraphicsFullError, GraphicsGaveUpError, type Engine } from '../src/main/engine'/** an engine whose graphics card gives up the first `fails` times a step is tried */-function rig(o: { loadFails?: number; chatFails?: number; chatError?: Error }) {+function rig(o: { loadFails?: number; chatFails?: number; chatError?: () => Error }) {let loadFails = o.loadFails ?? 0, chatFails = o.chatFails ?? 0const exits: (() => void)[] = []const calls: string[] = []@@ -13,7 +13,7 @@ function rig(o: { loadFails?: number; chatFails?: number; chatError?: Error }) {onExit: (cb) => { exits.push(cb) },chat: vi.fn(async (_r, onToken) => {calls.push('chat')- if (chatFails-- > 0) { exits.forEach((f) => f()); throw o.chatError ?? new GraphicsGaveUpError('no first word') }+ if (chatFails-- > 0) { exits.forEach((f) => f()); throw o.chatError?.() ?? new GraphicsGaveUpError('no first word') }onToken('Hi'); return 'Hi'}),}@@ -42,8 +42,15 @@ describe('the notes model when the graphics card gives up (Windows and Linux)',expect(words).toEqual(['Hi'])})+ it('the card running out of memory: tried again each time the engine steps down, until the processor (#165)', async () => {+ const r = rig({ chatFails: 3, chatError: () => new GraphicsFullError('out of memory') })+ const llm = await r.model.llm()+ await expect(llm.chat('the prompt', () => {})).resolves.toBe('Hi')+ expect(r.calls).toEqual(['load', 'chat', 'load', 'chat', 'load', 'chat', 'load', 'chat'])+ })+it('any other failure is not retried', async () => {- const r = rig({ chatFails: 1, chatError: new Error('Stopped') })+ const r = rig({ chatFails: 1, chatError: () => new Error('Stopped') })const llm = await r.model.llm()await expect(llm.chat('the prompt', () => {})).rejects.toThrow('Stopped')expect(r.calls).toEqual(['load', 'chat'])diff --git a/app/test/vram.test.ts b/app/test/vram.test.tsnew file mode 100644index 00000000..efa732dd--- /dev/null+++ b/app/test/vram.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest'+import { vramCap, WHISPER_VRAM } from '../src/engine/vram'++const GiB = 1024 ** 3++describe('how much graphics memory the notes model plans for (#165)', () => {+ it('an RTX A2000 Laptop (4 GB) next to an Iris Xe: only the card\'s own memory, less room for whisper-server', () => {+ // node-llama-cpp's 21.2 GB: the Iris Xe's 17.2 GB of shared memory plus the card's 4 GB+ const cap = vramCap({ total: 21.2 * GiB, unifiedSize: 17.2 * GiB }, 'win32')!+ expect(cap).toBeLessThan(4 * GiB - WHISPER_VRAM)+ expect(cap).toBeGreaterThan(2 * GiB)+ })+ it('a card alone: all of it, less room for whisper-server', () => {+ expect(vramCap({ total: 12 * GiB, unifiedSize: 0 }, 'linux')).toBe(12 * GiB - WHISPER_VRAM)+ })+ it('graphics built into the processor only, no graphics, or a Mac: node-llama-cpp\'s own count, as before', () => {+ expect(vramCap({ total: 16 * GiB, unifiedSize: 16 * GiB }, 'win32')).toBeNull()+ expect(vramCap({ total: 0, unifiedSize: 0 }, 'linux')).toBeNull()+ expect(vramCap({ total: 64 * GiB, unifiedSize: 64 * GiB }, 'darwin')).toBeNull()+ })+})