Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(llamacpp): replace mmap and mlock checkboxes with a load-mode setting

Akarshan Biswas7d1249a6afbb
diff --git a/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx b/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx
index af6660199..bddcb9d64 100644
--- a/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx
+++ b/docs/src/pages/docs/desktop/local-engine/llama-cpp.mdx
@@ -148,9 +148,8 @@ These engine-wide settings control how every loaded model uses system and GPU me
| Setting | What It Does | Default | When to Change |
|---------|-------------|---------|----------------|
| **Flash Attention** | Enable Flash Attention kernel | Auto | Force On or Off only if you hit kernel issues |
-| **Disable mmap** | Don't memory-map model files | Disabled | Enable if experiencing crashes or pageouts |
-| **Lazy Tensor Reading** | Read the rows of large arch-marked tensors (e.g. per-layer embeddings) from disk on demand instead of keeping them in memory; Auto applies it above 4 GiB | Auto | Off keeps those tensors in memory; requires mmap, so it has no effect with Disable mmap on |
-| **MLock** | Keep model in RAM, prevent swapping | Disabled | Enable if you have enough RAM and want consistent performance |
+| **Load Mode** | How model weights are read into memory: Auto (mmap if the device supports it), None (no mmap), mmap, mlock (no mmap, weights locked in RAM), mmap + mlock, or Direct I/O | Auto | Choose None if mmap causes crashes or pageouts; add mlock if you have enough RAM and want consistent performance, since it keeps the model from being swapped out. Each model can override it |
+| **Lazy Tensor Reading** | Read the rows of large arch-marked tensors (e.g. per-layer embeddings) from disk on demand instead of keeping them in memory; Auto applies it above 4 GiB | Auto | Off keeps those tensors in memory; requires mmap, so it has no effect with a Load Mode that does not memory-map (None, mlock or Direct I/O) |
| **Context Shift** | Allow trimming the start of the prompt when context fills | Disabled | Enable for very long chats or multiple tool calls |
| **Disable KV Cache Offload** | Keep the KV cache in system RAM instead of GPU memory | Disabled | When VRAM is scarce, at the cost of speed |
| **Unified KV Cache** | Use a single KV buffer shared across all slots | Auto | Saves memory when running multiple parallel slots |
@@ -159,7 +158,7 @@ These engine-wide settings control how every loaded model uses system and GPU me
| **KV Cache V Type** | KV-cache precision for values | f16 | Switch to q8_0 / q4_0 to save VRAM |
<Callout type="info">
-**Per-model settings** (configured on each model's page, not here): Context Size, GPU Layers, Batch Size, **Disable KV Offload** (enable to keep the KV cache on CPU when GPU VRAM is tight), Override Tensor Buffer Type, Custom Jinja Chat template, Chat template options (`chat_template_kwargs`), and sampling parameters. Jan writes the engine-wide settings as the `[*]` defaults in `router.preset.ini` in its data folder, and each model's own settings override them.
+**Per-model settings** (configured on each model's page, not here): Context Size, GPU Layers, Batch Size, **Load Mode** (Inherit global by default; any explicit choice, including Auto, overrides the engine-wide setting for that model), **Disable KV Offload** (enable to keep the KV cache on CPU when GPU VRAM is tight), Override Tensor Buffer Type, Custom Jinja Chat template, Chat template options (`chat_template_kwargs`), and sampling parameters. Jan writes the engine-wide settings as the `[*]` defaults in `router.preset.ini` in its data folder, and each model's own settings override them.
</Callout>
### KV Cache Types Explained
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 66b3f61fd..207121747 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -286,18 +286,44 @@
}
},
{
- "key": "no_mmap",
- "title": "Disable mmap",
- "description": "Do not memory-map model (slower load but may reduce pageouts if not using mlock).",
- "controllerType": "checkbox",
+ "key": "load_mode",
+ "title": "Load Mode",
+ "description": "How model weights are read into memory. Auto memory-maps the file unless a device cannot. None reads the weights without mmap (slower load, may reduce pageouts). mlock keeps them in RAM so they are never swapped out, with or without mmap. Direct I/O bypasses the OS page cache where available. Individual models can override this.",
+ "controllerType": "dropdown",
"controllerProps": {
- "value": false
+ "value": "auto",
+ "options": [
+ {
+ "value": "auto",
+ "name": "Auto (mmap if supported)"
+ },
+ {
+ "value": "none",
+ "name": "None (no mmap)"
+ },
+ {
+ "value": "mmap",
+ "name": "mmap"
+ },
+ {
+ "value": "mlock",
+ "name": "mlock (no mmap)"
+ },
+ {
+ "value": "mmap+mlock",
+ "name": "mmap + mlock"
+ },
+ {
+ "value": "dio",
+ "name": "Direct I/O"
+ }
+ ]
}
},
{
"key": "lazy_mode",
"title": "Lazy Tensor Reading",
- "description": "Read the rows of large arch-marked tensors (e.g. per-layer embeddings) from disk on demand instead of keeping them in memory. Auto applies it above 4 GiB. Requires mmap.",
+ "description": "Read the rows of large arch-marked tensors (e.g. per-layer embeddings) from disk on demand instead of keeping them in memory. Auto applies it above 4 GiB. Requires mmap, so pick a Load Mode that memory-maps (Auto, mmap or mmap + mlock).",
"controllerType": "dropdown",
"controllerProps": {
"value": "auto",
@@ -317,15 +343,6 @@
]
}
},
- {
- "key": "mlock",
- "title": "MLock",
- "description": "Lock the model in RAM so it is never swapped out. Combined with \"Disable mmap\" this loads the weights without mmap and then locks them.",
- "controllerType": "checkbox",
- "controllerProps": {
- "value": false
- }
- },
{
"key": "cache_type_k",
"title": "KV Cache K Type",
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 763efcff1..9a0387bd3 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -39,6 +39,7 @@ import {
} from './settings-store'
import { applyPlatformFitDefault } from './fit-default'
import { findModelEntries } from './model-tree'
+import { applyLegacyLoadMode, parseLoadMode } from './load-mode'
import {
getProxyConfig,
@@ -138,8 +139,7 @@ const PRESET_AFFECTING_KEYS = new Set<string>([
'device',
'split_mode',
'main_gpu',
- 'no_mmap',
- 'mlock',
+ 'load_mode',
'rope_scaling',
'rope_freq_base',
'rope_freq_scale',
@@ -359,6 +359,10 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<
yamlKey: 'mmproj_offload',
coerce: (v) => (v === false ? false : null),
},
+ // Empty is the UI's "inherit global": null drops the key, so the model gets
+ // no load-mode line. Any valid value, auto included, is kept because it
+ // overrides a non-auto global.
+ load_mode: { yamlKey: 'load_mode', coerce: parseLoadMode },
}
async function readPersistedLlamacppModels(): Promise<PersistedModelState[]> {
@@ -809,6 +813,9 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEng
})
const old = await readSettingsFile()
if (old.length) {
+ // Before the merge below: the stored mlock / no_mmap checkboxes have no
+ // counterpart in `settings` any more, so the merge would silently drop them.
+ applyLegacyLoadMode(settings, old)
settings.forEach((s) => {
const prev = old.find((o) => o.key === s.key)
if (!prev) return
diff --git a/extensions/llamacpp-extension/src/load-mode.test.ts b/extensions/llamacpp-extension/src/load-mode.test.ts
new file mode 100644
index 000000000..ec7e6e814
--- /dev/null
+++ b/extensions/llamacpp-extension/src/load-mode.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect } from 'vitest'
+import type { SettingComponentProps } from '@janhq/core'
+import settingsJson from '../settings.json'
+import {
+ LOAD_MODES,
+ applyLegacyLoadMode,
+ legacyLoadMode,
+ parseLoadMode,
+} from './load-mode'
+
+const entry = (key: string, value: unknown): SettingComponentProps =>
+ ({
+ key,
+ title: key,
+ description: '',
+ controllerType: 'checkbox',
+ controllerProps: { value },
+ }) as SettingComponentProps
+
+const shipped = (): SettingComponentProps[] =>
+ structuredClone(settingsJson) as unknown as SettingComponentProps[]
+
+const loadModeOf = (settings: SettingComponentProps[]) =>
+ settings.find((s) => s.key === 'load_mode')?.controllerProps.value
+
+describe('parseLoadMode', () => {
+ it('accepts exactly the values llama.cpp accepts', () => {
+ expect([...LOAD_MODES]).toEqual([
+ 'auto',
+ 'none',
+ 'mmap',
+ 'mlock',
+ 'mmap+mlock',
+ 'dio',
+ ])
+ for (const mode of LOAD_MODES) expect(parseLoadMode(mode)).toBe(mode)
+ })
+
+ it('rejects anything else, including near misses', () => {
+ for (const bad of ['', 'MMAP', ' mmap', 'mmap+', 'direct', 1, true, null, undefined]) {
+ expect(parseLoadMode(bad), String(bad)).toBeNull()
+ }
+ })
+})
+
+describe('legacyLoadMode', () => {
+ // The mapping the preset used to derive from the two checkboxes.
+ it.each([
+ [false, false, 'auto'],
+ [false, true, 'none'],
+ [true, false, 'mmap+mlock'],
+ [true, true, 'mlock'],
+ ] as const)('mlock=%s no_mmap=%s -> %s', (mlock, noMmap, expected) => {
+ expect(legacyLoadMode(mlock, noMmap)).toBe(expected)
+ })
+})
+
+describe('shipped load_mode setting', () => {
+ it('is a dropdown of the six upstream values defaulting to auto', () => {
+ const setting = shipped().find((s) => s.key === 'load_mode')
+ expect(setting?.controllerType).toBe('dropdown')
+ const props = setting?.controllerProps as {
+ value: string
+ options: { value: string; name: string }[]
+ }
+ expect(props.value).toBe('auto')
+ expect(props.options.map((o) => o.value)).toEqual([...LOAD_MODES])
+ })
+
+ it('no longer ships the two checkboxes it replaced', () => {
+ const keys = shipped().map((s) => s.key)
+ expect(keys).not.toContain('no_mmap')
+ expect(keys).not.toContain('mlock')
+ })
+})
+
+describe('applyLegacyLoadMode', () => {
+ it.each([
+ [false, false, 'auto'],
+ [false, true, 'none'],
+ [true, false, 'mmap+mlock'],
+ [true, true, 'mlock'],
+ ] as const)(
+ 'carries mlock=%s no_mmap=%s over as %s',
+ (mlock, noMmap, expected) => {
+ const settings = shipped()
+ applyLegacyLoadMode(settings, [
+ entry('no_mmap', noMmap),
+ entry('mlock', mlock),
+ ])
+ expect(loadModeOf(settings)).toBe(expected)
+ }
+ )
+
+ it('treats a missing half as off', () => {
+ const settings = shipped()
+ applyLegacyLoadMode(settings, [entry('mlock', true)])
+ expect(loadModeOf(settings)).toBe('mmap+mlock')
+ })
+
+ it('leaves the default alone when the old file had neither key', () => {
+ const settings = shipped()
+ applyLegacyLoadMode(settings, [entry('fit', true)])
+ expect(loadModeOf(settings)).toBe('auto')
+ })
+
+ // A user who already picked a load mode must not be overwritten by stale
+ // booleans that happen to still sit in the file.
+ it('never overrides a load_mode the user already stored', () => {
+ const settings = shipped()
+ applyLegacyLoadMode(settings, [
+ entry('no_mmap', true),
+ entry('mlock', true),
+ entry('load_mode', 'dio'),
+ ])
+ expect(loadModeOf(settings)).toBe('auto')
+ })
+
+ it('is idempotent once the old keys are gone', () => {
+ const settings = shipped()
+ applyLegacyLoadMode(settings, [entry('no_mmap', true)])
+ expect(loadModeOf(settings)).toBe('none')
+ // What registerSettings writes back has no legacy keys, so a rerun is a no-op.
+ applyLegacyLoadMode(settings, [entry('load_mode', 'none')])
+ expect(loadModeOf(settings)).toBe('none')
+ })
+})
diff --git a/extensions/llamacpp-extension/src/load-mode.ts b/extensions/llamacpp-extension/src/load-mode.ts
new file mode 100644
index 000000000..69a876b89
--- /dev/null
+++ b/extensions/llamacpp-extension/src/load-mode.ts
@@ -0,0 +1,66 @@
+import type { SettingComponentProps } from '@janhq/core'
+
+/**
+ * The values `--load-mode` / the INI key `load-mode` accept
+ * (common/arg.cpp). Anything else makes llama.cpp throw "invalid value" and the
+ * whole router fail to start, so every value is checked against this list
+ * before it reaches the preset.
+ */
+export const LOAD_MODES = [
+ 'auto',
+ 'none',
+ 'mmap',
+ 'mlock',
+ 'mmap+mlock',
+ 'dio',
+] as const
+
+export type LoadMode = (typeof LOAD_MODES)[number]
+
+/** The value when the user has chosen nothing: upstream's own default. */
+export const DEFAULT_LOAD_MODE: LoadMode = 'auto'
+
+/** Narrows a persisted value to a load mode, or null when it is not one. */
+export function parseLoadMode(value: unknown): LoadMode | null {
+ return LOAD_MODES.find((mode) => mode === value) ?? null
+}
+
+/**
+ * The load mode the two removed checkboxes (`mlock`, `no_mmap`) used to derive
+ * in the preset. Kept identical so an upgrade changes nothing about how a
+ * model loads.
+ */
+export function legacyLoadMode(mlock: boolean, noMmap: boolean): LoadMode {
+ if (mlock) return noMmap ? 'mlock' : 'mmap+mlock'
+ return noMmap ? 'none' : DEFAULT_LOAD_MODE
+}
+
+const settingValue = (
+ settings: SettingComponentProps[],
+ key: string
+): unknown =>
+ settings.find((s) => s.key === key)?.controllerProps?.value
+
+/**
+ * Carries the stored `mlock` / `no_mmap` checkboxes over into `load_mode`, in
+ * place, before the stored values are merged into the shipped settings.
+ *
+ * Runs against the previous settings file, so it needs no version flag of its
+ * own: the file written afterwards no longer has the legacy keys and a second
+ * run finds nothing to convert. A `load_mode` that is already stored is the
+ * user's choice and is never replaced by stale booleans.
+ */
+export function applyLegacyLoadMode(
+ shipped: SettingComponentProps[],
+ stored: SettingComponentProps[]
+): void {
+ if (stored.some((s) => s.key === 'load_mode')) return
+ const hasLegacy = stored.some((s) => s.key === 'mlock' || s.key === 'no_mmap')
+ if (!hasLegacy) return
+ const target = shipped.find((s) => s.key === 'load_mode')
+ if (!target) return
+ target.controllerProps.value = legacyLoadMode(
+ settingValue(stored, 'mlock') === true,
+ settingValue(stored, 'no_mmap') === true
+ )
+}
diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.ts
index 5e4cb2023..657ebc60c 100644
--- a/extensions/llamacpp-extension/src/preset.test.ts
+++ b/extensions/llamacpp-extension/src/preset.test.ts
@@ -739,22 +739,56 @@ describe('generatePreset upstream-default skipping', () => {
expect(modelSection('c')).not.toContain('n-gpu-layers')
})
- // mlock and no_mmap were two aliases for one upstream field and are gone as of
- // 0.4.1; load-mode is the only key llama.cpp still accepts.
- it('derives a single load-mode and never emits mlock or no-mmap', async () => {
- const cases: Array<[boolean, boolean, string | null]> = [
- [false, false, null],
- [false, true, 'load-mode = none'],
- [true, false, 'load-mode = mmap+mlock'],
- [true, true, 'load-mode = mlock'],
- ]
- for (const [mlock, no_mmap, expected] of cases) {
- await generatePreset('/p', '/jan', { mlock, no_mmap } as any)
- const g = globalSection()
- expect(g, `mlock=${mlock} no_mmap=${no_mmap}`).not.toMatch(/^mlock = /m)
- expect(g).not.toMatch(/^no-mmap = /m)
- if (expected) expect(g).toContain(expected)
- else expect(g).not.toContain('load-mode')
+ // mlock and no_mmap were aliases for the one upstream load-mode field and are
+ // gone as of 0.4.1; load-mode is the only key llama.cpp still accepts. `auto`
+ // is upstream's own default, so naming it would pin a value meant to track the
+ // engine.
+ it('emits the global load-mode for every value but auto', async () => {
+ for (const mode of ['none', 'mmap', 'mlock', 'mmap+mlock', 'dio']) {
+ await generatePreset('/p', '/jan', { load_mode: mode } as any)
+ expect(globalSection(), mode).toContain(`load-mode = ${mode}`)
+ }
+ await generatePreset('/p', '/jan', { load_mode: 'auto' } as any)
+ expect(globalSection()).not.toContain('load-mode')
+ })
+
+ it('ignores the removed mlock and no_mmap booleans', async () => {
+ await generatePreset('/p', '/jan', { mlock: true, no_mmap: true } as any)
+ const g = globalSection()
+ expect(g).not.toMatch(/^mlock = /m)
+ expect(g).not.toMatch(/^no-mmap = /m)
+ expect(g).not.toContain('load-mode')
+ })
+
+ it('drops an unknown global load-mode instead of emitting it', async () => {
+ for (const bad of ['bogus', '', 'MMAP', 7, null, true]) {
+ await generatePreset('/p', '/jan', { load_mode: bad } as any)
+ expect(globalSection(), String(bad)).not.toContain('load-mode')
+ }
+ })
+
+ // A model value must override the global one, and `auto` is a real override
+ // when the global is not auto, so unlike [*] it is emitted.
+ it('emits an explicit per-model load-mode, including auto', async () => {
+ for (const mode of ['auto', 'none', 'mmap', 'mlock', 'mmap+mlock', 'dio']) {
+ setupModel('m', { load_mode: mode })
+ await generatePreset('/p', '/jan', { load_mode: 'mlock' } as any)
+ expect(modelSection('m'), mode).toContain(`load-mode = ${mode}`)
+ }
+ })
+
+ it('emits nothing per model when load_mode is unset so the global applies', async () => {
+ setupModel('m', {})
+ await generatePreset('/p', '/jan', { load_mode: 'mlock' } as any)
+ expect(globalSection()).toContain('load-mode = mlock')
+ expect(modelSection('m')).not.toContain('load-mode')
+ })
+
+ it('drops an invalid per-model load-mode', async () => {
+ for (const bad of ['bogus', '', 'MMAP', 7, true]) {
+ setupModel('m', { load_mode: bad })
+ await generatePreset('/p', '/jan', {} as any)
+ expect(modelSection('m'), String(bad)).not.toContain('load-mode')
}
})
diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.ts
index 1418a1814..76c1929b1 100644
--- a/extensions/llamacpp-extension/src/preset.ts
+++ b/extensions/llamacpp-extension/src/preset.ts
@@ -15,6 +15,7 @@
import { fs, joinPath } from '@janhq/core'
import { findModelEntries } from './model-tree'
+import { parseLoadMode } from './load-mode'
import type { LlamacppConfig, ModelConfig } from '@janhq/tauri-plugin-llamacpp-api'
// ModelConfig is intentionally widened — model.yml may carry extra fields like
@@ -27,6 +28,7 @@ type ModelYaml = ModelConfig & {
flash_attn?: string
cache_type_k?: string
cache_type_v?: string
+ load_mode?: string
parallel?: number
cont_batching?: boolean
pooling?: 'none' | 'mean' | 'cls' | 'last' | 'rank'
@@ -335,7 +337,7 @@ export async function generatePreset(
lines.push(`n-cpu-ffn = ${Math.floor(config.n_cpu_ffn)}`)
}
// no-kv-offload default = false (the cache is offloaded). Spelled negatively
- // to match llama.cpp's own flag and the existing no_mmap setting.
+ // to match llama.cpp's own flag.
// common_preset's parse_bool_arg recognises `no-kv-offload` as the negated
// half of the kv-offload pair (arg.cpp:2417-2424) and inverts it, so `true`
// here does disable offloading.
@@ -392,16 +394,11 @@ export async function generatePreset(
}
// `--mlock`, `--mmap`/`--no-mmap` and `--direct-io` were deprecated aliases of
// the single params.load_mode field and were deleted outright in 0.4.1, so
- // `load-mode` is now the only spelling llama.cpp understands. Jan keeps the two
- // familiar toggles in its settings and derives that one key from them.
- const wantsMlock = config.mlock === true
- const wantsNoMmap = config.no_mmap === true
- if (wantsMlock || wantsNoMmap) {
- const loadMode = wantsMlock
- ? wantsNoMmap
- ? 'mlock'
- : 'mmap+mlock'
- : 'none'
+ // `load-mode` is the only spelling llama.cpp understands. default = auto, so
+ // only a non-auto value is named here; a model section can still name `auto`
+ // to opt out of a non-auto global.
+ const loadMode = parseLoadMode(config.load_mode)
+ if (loadMode !== null && loadMode !== 'auto') {
lines.push(`load-mode = ${loadMode}`)
}
// rope-scaling default is UNSPECIFIED (let the model decide), not 'none'.
@@ -445,8 +442,8 @@ export async function generatePreset(
lines.push(`cache-ram = ${Math.floor(config.cache_ram)}`)
}
// lazy-mode default = auto (on for arch-marked tensors above 4 GiB). Needs
- // mmap, so it is silently inert with `no_mmap` on; `off` is the pre-0.4.0
- // behaviour of always keeping those tensors resident.
+ // mmap, so it is silently inert under a load-mode that does not map the file;
+ // `off` is the pre-0.4.0 behaviour of always keeping those tensors resident.
if (config.lazy_mode === 'on' || config.lazy_mode === 'off') {
lines.push(`lazy-mode = ${config.lazy_mode}`)
}
@@ -645,6 +642,12 @@ export async function generatePreset(
lines.push('parallel = 1')
if (kvUnifiedIsAuto) lines.push('kv-unified = true')
}
+ // Unlike [*], `auto` is emitted: it is a real override of a non-auto
+ // global. Unset (empty in the UI) means inherit, so nothing is written.
+ const modelLoadMode = parseLoadMode(mc.load_mode)
+ if (modelLoadMode !== null) {
+ lines.push(`load-mode = ${modelLoadMode}`)
+ }
if (mc.cont_batching === false) {
lines.push('cont-batching = false')
}
diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.ts
index a4bf61c23..f4ffd4eb1 100644
--- a/extensions/llamacpp-extension/src/test/index.test.ts
+++ b/extensions/llamacpp-extension/src/test/index.test.ts
@@ -358,8 +358,7 @@ describe('llamacpp_extension', () => {
main_gpu: 0,
flash_attn: false,
cont_batching: false,
- no_mmap: false,
- mlock: false,
+ load_mode: 'auto',
no_kv_offload: false,
cache_type_k: 'f16',
cache_type_v: 'f16',
@@ -692,6 +691,75 @@ describe('llamacpp_extension', () => {
})
})
+ describe('registerSettings load_mode migration', () => {
+ const stored = (key: string, value: unknown) => ({
+ key,
+ title: key,
+ description: '',
+ controllerType: 'checkbox' as const,
+ controllerProps: { value },
+ })
+
+ // Drives the real merge so the legacy keys are shown to be consumed, then
+ // written back without them (which is what makes a rerun a no-op).
+ const register = async (previous: ReturnType<typeof stored>[]) => {
+ let written: { key: string; controllerProps: { value?: unknown } }[] = []
+ vi.spyOn(store, 'readSettingsFile').mockResolvedValue(
+ previous as never
+ )
+ vi.spyOn(store, 'writeSettingsFile').mockImplementation(async (s) => {
+ written = s as typeof written
+ })
+ const shipped = [
+ {
+ key: 'load_mode',
+ title: 'Load Mode',
+ description: '',
+ controllerType: 'dropdown' as const,
+ controllerProps: {
+ value: 'auto',
+ options: ['auto', 'none', 'mmap', 'mlock', 'mmap+mlock', 'dio'].map(
+ (value) => ({ value, name: value })
+ ),
+ },
+ },
+ ]
+ await (extension as any).registerSettings(shipped)
+ return written
+ }
+ const loadMode = (w: Awaited<ReturnType<typeof register>>) =>
+ w.find((s) => s.key === 'load_mode')?.controllerProps.value
+
+ it.each([
+ [false, false, 'auto'],
+ [false, true, 'none'],
+ [true, false, 'mmap+mlock'],
+ [true, true, 'mlock'],
+ ])('converts mlock=%s no_mmap=%s to %s', async (mlock, noMmap, expected) => {
+ const written = await register([
+ stored('no_mmap', noMmap),
+ stored('mlock', mlock),
+ ])
+ expect(loadMode(written)).toBe(expected)
+ expect(written.map((s) => s.key)).toEqual(['load_mode'])
+ })
+
+ it('is idempotent: its own output converts to itself', async () => {
+ const first = await register([stored('no_mmap', true)])
+ const second = await register(first as never)
+ expect(loadMode(second)).toBe('none')
+ })
+
+ it('does not clobber a load_mode the user already chose', async () => {
+ const written = await register([
+ stored('no_mmap', true),
+ stored('mlock', true),
+ stored('load_mode', 'dio'),
+ ])
+ expect(loadMode(written)).toBe('dio')
+ })
+ })
+
describe('getLoadedModels', () => {
it('should return list of loaded models', async () => {
const { invoke } = await import('@tauri-apps/api/core')
@@ -801,6 +869,46 @@ describe('llamacpp_extension', () => {
expect((await extension.getSettings())[0].controllerProps.value).toBe(true)
})
+ describe('per-model load_mode', () => {
+ let savedModel: Record<string, unknown>
+ const persist = (value: unknown) =>
+ extension.updateModelSettings('model', {
+ load_mode: value as string,
+ })
+
+ beforeEach(() => {
+ savedModel = { ctx_size: 4096 }
+ vi.mocked(fs.existsSync).mockResolvedValue(true)
+ vi.mocked(fs.readYaml).mockImplementation(async () =>
+ structuredClone(savedModel)
+ )
+ vi.mocked(fs.writeYaml).mockImplementation(async (_path, data) => {
+ savedModel = structuredClone(data as Record<string, unknown>)
+ })
+ })
+
+ it.each(['auto', 'none', 'mmap', 'mlock', 'mmap+mlock', 'dio'])(
+ 'persists %s to model.yml',
+ async (mode) => {
+ await persist(mode)
+ expect(savedModel.load_mode).toBe(mode)
+ }
+ )
+
+ // The empty option is "inherit global": no key, so no line in the preset.
+ it('removes the key when the user goes back to inheriting', async () => {
+ savedModel = { ctx_size: 4096, load_mode: 'mlock' }
+ await persist('')
+ expect(savedModel).toEqual({ ctx_size: 4096 })
+ })
+
+ it('does not persist a value llama.cpp would reject', async () => {
+ await persist('bogus')
+ expect(savedModel).toEqual({ ctx_size: 4096 })
+ expect(fs.writeYaml).not.toHaveBeenCalled()
+ })
+ })
+
it('rejects a failed context application and restores model.yml', async () => {
let savedModel: Record<string, unknown> = { ctx_size: 4096 }
vi.mocked(fs.existsSync).mockResolvedValue(true)
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
index 67d31e719..5f682d164 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -105,8 +105,8 @@ export type LlamacppConfig = {
flash_attn: string
parallel: number
cont_batching: boolean
- no_mmap: boolean
- mlock: boolean
+ /** How weights are read: `auto` | `none` | `mmap` | `mlock` | `mmap+mlock` | `dio`. */
+ load_mode: string
cache_type_k: string
cache_type_v: string
rope_scaling: string