Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(llamacpp): upgrade the engine to 0.7.0 (b11669) (#9399)
Akarshan Biswas35a1bc5f4084
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.jsonindex 4b7c07f3f..72d5fe4d0 100644--- a/extensions/llamacpp-extension/settings.json+++ b/extensions/llamacpp-extension/settings.json@@ -476,7 +476,7 @@{"key": "cache_ram","title": "Prompt Cache RAM (MiB)",- "description": "Prompt cache size in MiB (default: 8192). -1 is unlimited, 0 disables it.",+ "description": "Prompt cache size in MiB (default: 8192, or off for decision models unless changed). -1 is unlimited, 0 disables it.","controllerType": "input","controllerProps": {"value": 8192,diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex cb44bbca1..d2c949422 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -42,6 +42,7 @@ import {mergeEmbedResponses,detectEmbeddingFromGgufMeta,detectMtpLayersFromGgufMeta,+ detectExpertCountFromGgufMeta,resolveSpecDraftKind,detectTemplateKwargsFromChatTemplate,getDefaultEmbeddingModelId,@@ -97,6 +98,7 @@ import { getSystemUsage, getSystemInfo } from '@janhq/tauri-plugin-hardware-api'const EMBEDDING_CHECK_VERSION = 3const MTP_CHECK_VERSION = 1+const EXPERT_CHECK_VERSION = 1// The tensor that marks a DSpark draft: it is a DFlash one plus this Markov// head (common/speculative.cpp, llama-arch.cpp LLM_TENSOR_DSPARK_MARKOV_W1).@@ -325,6 +327,14 @@ const MODEL_SETTINGS_YAML_MAPPING: Record<return Number.isFinite(n) && n > 0 ? Math.floor(n) : null},},+ moe_cache_mib: {+ yamlKey: 'moe_cache_mib',+ coerce: (v) => {+ if (v === '' || v == null) return null+ const n = typeof v === 'number' ? v : Number(v)+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : null+ },+ },no_kv_offload: {yamlKey: 'no_kv_offload',coerce: (v) => (v === true ? true : null),@@ -1386,6 +1396,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst isEmbedding = await this.resolveEmbeddingConfig(modelId, modelConfig)await this.resolveMtpLayersConfig(modelId, modelConfig)+ await this.resolveExpertCountConfig(modelId, modelConfig)const templateKwargs = await this.resolveTemplateKwargsConfig(modelId,modelConfig@@ -1482,6 +1493,63 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngreturn isEmbedding}+ /**+ * Record the GGUF's MoE expert count in model.yml, which the preset reads to+ * decide whether `moe-cache-mib` may be emitted: llama.cpp refuses to load a+ * model without experts when it is set. Backfilled lazily, like mtp_layers,+ * for models imported before the count was recorded.+ */+ private async resolveExpertCountConfig(+ modelId: string,+ modelConfig: ModelConfig+ ): Promise<number> {+ const cfg = modelConfig as ModelConfig & {+ expert_count?: number+ expert_check_v?: number+ }+ if (+ typeof cfg.expert_count === 'number' &&+ cfg.expert_check_v === EXPERT_CHECK_VERSION+ ) {+ return cfg.expert_count+ }++ let expertCount = 0+ try {+ const janDataFolderPath = await getJanDataFolderPath()+ const fullModelPath = await joinPath([+ janDataFolderPath,+ modelConfig.model_path,+ ])+ if (await fs.existsSync(fullModelPath)) {+ const metadata = await readGgufMetadata(fullModelPath)+ expertCount = detectExpertCountFromGgufMeta(metadata.metadata)+ }+ } catch (e) {+ logger.warn(`Failed to check expert count for ${modelId}`, e)+ return cfg.expert_count ?? 0+ }++ try {+ const configPath = await joinPath([+ await this.getProviderPath(),+ 'models',+ modelId,+ 'model.yml',+ ])+ cfg.expert_count = expertCount+ cfg.expert_check_v = EXPERT_CHECK_VERSION+ await invoke<void>('write_yaml', {+ data: cfg,+ savePath: configPath,+ })+ } catch (e) {+ logger.warn(`Failed to persist expert count for ${modelId}`, e)+ }++ return expertCount+ }+private async resolveMtpLayersConfig(modelId: string,modelConfig: ModelConfig@@ -2031,6 +2099,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngconst fullModelPath = await joinPath([janDataFolderPath, modelPath])let isEmbedding = falselet mtpLayers = 0+ let expertCount = 0let specKind: SpecDraftKind = 'mtp'let templateKwargs: TemplateKwarg[] = []let resolvedName: string | undefined@@ -2046,6 +2115,7 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngisEmbedding = true}mtpLayers = detectMtpLayersFromGgufMeta(modelMetadata.metadata)+ expertCount = detectExpertCountFromGgufMeta(modelMetadata.metadata)templateKwargs = detectTemplateKwargsFromChatTemplate(modelMetadata.metadata?.['tokenizer.chat_template'])@@ -2128,6 +2198,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngembedding_check_v: EMBEDDING_CHECK_VERSION,mtp_layers: mtpLayers,mtp_check_v: MTP_CHECK_VERSION,+ expert_count: expertCount,+ expert_check_v: EXPERT_CHECK_VERSION,template_kwargs: templateKwargs,template_kwargs_check_v: TEMPLATE_KWARGS_CHECK_VERSION,// A separate draft gguf is downloaded only to be used, so enable it by@@ -2616,6 +2688,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngspec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}> {const path = await joinPath([await this.getProviderPath(),@@ -2632,6 +2706,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngspec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}return {mtp_layers: typeof cfg.mtp_layers === 'number' ? cfg.mtp_layers : 0,@@ -2639,6 +2715,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngspec_draft_n_max: cfg.spec_draft_n_max,spec_draft_n_min: cfg.spec_draft_n_min,spec_draft_p_min: cfg.spec_draft_p_min,+ spec_draft_sampling: cfg.spec_draft_sampling,+ spec_draft_n_ubatch: cfg.spec_draft_n_ubatch,}}@@ -2649,6 +2727,8 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngspec_draft_n_max?: number | nullspec_draft_n_min?: number | nullspec_draft_p_min?: number | null+ spec_draft_sampling?: string | null+ spec_draft_n_ubatch?: number | null}): Promise<void> {const configPath = await joinPath([@@ -2665,11 +2745,17 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngspec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}if (typeof patch.mtp === 'boolean') cfg.mtp = patch.mtpconst assignNumeric = (- key: 'spec_draft_n_max' | 'spec_draft_n_min' | 'spec_draft_p_min',+ key:+ | 'spec_draft_n_max'+ | 'spec_draft_n_min'+ | 'spec_draft_p_min'+ | 'spec_draft_n_ubatch',value: number | null | undefined) => {if (value === null) {@@ -2681,6 +2767,13 @@ export default class llamacpp_extension extends AIEngine implements EmbeddingEngif ('spec_draft_n_max' in patch) assignNumeric('spec_draft_n_max', patch.spec_draft_n_max)if ('spec_draft_n_min' in patch) assignNumeric('spec_draft_n_min', patch.spec_draft_n_min)if ('spec_draft_p_min' in patch) assignNumeric('spec_draft_p_min', patch.spec_draft_p_min)+ if ('spec_draft_n_ubatch' in patch)+ assignNumeric('spec_draft_n_ubatch', patch.spec_draft_n_ubatch)+ if (patch.spec_draft_sampling === null) {+ delete cfg.spec_draft_sampling+ } else if (typeof patch.spec_draft_sampling === 'string') {+ cfg.spec_draft_sampling = patch.spec_draft_sampling+ }await invoke<void>('write_yaml', { data: cfg, savePath: configPath })diff --git a/extensions/llamacpp-extension/src/preset.test.ts b/extensions/llamacpp-extension/src/preset.test.tsindex 04b7311d5..659c05a06 100644--- a/extensions/llamacpp-extension/src/preset.test.ts+++ b/extensions/llamacpp-extension/src/preset.test.ts@@ -275,6 +275,105 @@ describe('generatePreset 0.4.0 keys', () => {})})+describe('generatePreset 0.7.0 keys', () => {+ // b11669 throws "MoE cache requires a MoE model" for any model without+ // experts, so an engine-wide key would break every dense and embedding model+ // the moment it was set. It is per-model only.+ it('never emits moe-cache-mib engine-wide', async () => {+ setupModel('llama', {})+ await generatePreset('/p', '/jan', { moe_cache_mib: 4096 } as any)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')+ })++ it('emits moe-cache-mib only in the section of the model that set it', async () => {+ setupModel('dense', {})+ setupModel('moe', { moe_cache_mib: 4096, expert_count: 128 })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ const section = (id: string) =>+ ini.split(`[${id}]`)[1].split('load-on-startup')[0]+ expect(section('moe')).toContain('moe-cache-mib = 4096')+ expect(section('dense')).not.toContain('moe-cache-mib')+ })++ // The other two load-time throws in llama-moe-cache.cpp depend on engine-wide+ // settings the preset can see: tensor split mode, and no GPU at all.+ it('drops moe-cache-mib under configurations llama.cpp refuses it in', async () => {+ setupModel('moe', { moe_cache_mib: 4096, expert_count: 128 })+ await generatePreset('/p', '/jan', { split_mode: 'tensor' } as any)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')++ await generatePreset('/p', '/jan', { device: 'none' } as any)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')++ await generatePreset('/p', '/jan', { split_mode: 'row', device: 'CUDA0' } as any)+ expect(writtenFiles['/p/router.preset.ini']).toContain('moe-cache-mib = 4096')+ })++ // A per-model value can still be set on a dense model by mistake, and+ // llama.cpp then refuses to load it. Only a model whose GGUF declares+ // experts gets the key; an unknown count (not yet detected) is treated as+ // dense, since a false negative only loses the cache.+ it('omits moe-cache-mib for a model without experts, or with an unknown count', async () => {+ setupModel('dense', { moe_cache_mib: 4096, expert_count: 0 })+ setupModel('unknown', { moe_cache_mib: 4096 })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')+ })++ it('omits a per-model moe-cache-mib of 0 or below', async () => {+ setupModel('moe', { moe_cache_mib: 0, expert_count: 128 })+ setupModel('moe2', { moe_cache_mib: -5, expert_count: 128 })+ await generatePreset('/p', '/jan', CONFIG)+ expect(writtenFiles['/p/router.preset.ini']).not.toContain('moe-cache-mib')+ })++ it('emits the draft sampling mode and ubatch with speculative decoding', async () => {+ setupModel('glm', {+ mtp: true,+ mtp_layers: 1,+ spec_draft_sampling: 'probabilistic',+ spec_draft_n_ubatch: 128,+ })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).toContain('spec-draft-sampling = probabilistic')+ expect(ini).toContain('spec-draft-n-ubatch = 128')+ })++ // greedy and 0 (follow ubatch-size) are upstream's defaults.+ it('omits the draft keys at their defaults or when an unknown mode is recorded', async () => {+ setupModel('glm', {+ mtp: true,+ mtp_layers: 1,+ spec_draft_sampling: 'greedy',+ spec_draft_n_ubatch: 0,+ })+ await generatePreset('/p', '/jan', CONFIG)+ let ini = writtenFiles['/p/router.preset.ini']+ expect(ini).not.toContain('spec-draft-sampling')+ expect(ini).not.toContain('spec-draft-n-ubatch')++ setupModel('glm', { mtp: true, mtp_layers: 1, spec_draft_sampling: 'bogus' })+ await generatePreset('/p', '/jan', CONFIG)+ ini = writtenFiles['/p/router.preset.ini']+ expect(ini).not.toContain('spec-draft-sampling')+ })++ it('omits the draft keys when speculative decoding is off', async () => {+ setupModel('glm', {+ mtp: false,+ mtp_layers: 1,+ spec_draft_sampling: 'probabilistic',+ spec_draft_n_ubatch: 128,+ })+ await generatePreset('/p', '/jan', CONFIG)+ const ini = writtenFiles['/p/router.preset.ini']+ expect(ini).not.toContain('spec-draft-sampling')+ expect(ini).not.toContain('spec-draft-n-ubatch')+ })+})+// A slot of a hybrid model with speculative decoding holds (1 + n_max) rows// of recurrent state, so auto's 4 slots overflowed a 12 GB card in 0.8.5.describe('generatePreset parallel with speculative decoding', () => {diff --git a/extensions/llamacpp-extension/src/preset.ts b/extensions/llamacpp-extension/src/preset.tsindex 579eb702d..69949f8ed 100644--- a/extensions/llamacpp-extension/src/preset.ts+++ b/extensions/llamacpp-extension/src/preset.ts@@ -47,9 +47,13 @@ type ModelYaml = ModelConfig & {spec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: numbercpu_moe?: booleann_cpu_moe?: numbern_cpu_ffn?: number+ moe_cache_mib?: number+ expert_count?: numberno_kv_offload?: booleanoverride_tensor?: stringmmproj_offload?: boolean@@ -110,6 +114,13 @@ const SPEC_TYPES = new Set([])const DEFAULT_SPEC_TYPE = 'draft-mtp'+/**+ * The non-default `--spec-draft-sampling` mode (common/arg.cpp, added in+ * 0.7.0). `greedy` is upstream's default and is never written, so a model+ * keeps tracking it.+ */+const NON_DEFAULT_DRAFT_SAMPLING = 'probabilistic'+/*** A built-in template name (`chatml`, `llama3`, ...) as opposed to a template* body. `--chat-template` takes either, but `--chat-template-file` reads its@@ -353,7 +364,7 @@ export async function generatePreset(// no-kv-offload default = false (the cache is offloaded). Spelled negatively// to match llama.cpp's own flag and the existing no_mmap setting.// common_preset's parse_bool_arg recognises `no-kv-offload` as the negated- // half of the kv-offload pair (arg.cpp:2403-2410) and inverts it, so `true`+ // half of the kv-offload pair (arg.cpp:2417-2424) and inverts it, so `true`// here does disable offloading.if (config.no_kv_offload === true) {lines.push('no-kv-offload = true')@@ -519,6 +530,12 @@ export async function generatePreset(lines.push('')// ---------- per-model sections ----------+ const moeCacheAllowed =+ config.split_mode !== 'tensor' &&+ !(+ typeof config.device === 'string' &&+ config.device.trim().toLowerCase() === 'none'+ )let embeddingCount = 0for (const { modelId, configPath } of modelEntries) {let mc: ModelYaml@@ -681,6 +698,27 @@ export async function generatePreset(if (typeof mc.n_cpu_ffn === 'number' && mc.n_cpu_ffn > 0) {lines.push(`n-cpu-ffn = ${Math.floor(mc.n_cpu_ffn)}`)}+ // moe-cache-mib default = 0 (off): a GPU cache for the experts that+ // cpu-moe / n-cpu-moe keep in host memory, added in 0.7.0. Per-model only,+ // never in [*]: llama.cpp refuses to load a model without experts when it+ // is set ("MoE cache requires a MoE model", llama-moe-cache.cpp), so an+ // engine-wide value would break every dense and embedding model. For the+ // same reason it is emitted only when the GGUF declares experts+ // (`expert_count`, recorded at import); a model whose count is not yet+ // known is treated as dense, since that only skips the cache. The same+ // file also throws under tensor split mode and with no GPU backend, so the+ // key is dropped where the preset can see either: it would only turn a+ // working CPU-offloaded load into a failed one.+ if (+ moeCacheAllowed &&+ typeof mc.expert_count === 'number' &&+ mc.expert_count > 0 &&+ typeof mc.moe_cache_mib === 'number' &&+ Number.isFinite(mc.moe_cache_mib) &&+ mc.moe_cache_mib > 0+ ) {+ lines.push(`moe-cache-mib = ${Math.floor(mc.moe_cache_mib)}`)+ }if (mc.no_kv_offload === true) {// INI key is the negated form; parse_bool_arg flips it server-side.// Writing `no-kv-offload = true` => kv-offload disabled.@@ -723,6 +761,19 @@ export async function generatePreset() {lines.push(`spec-draft-p-min = ${mc.spec_draft_p_min}`)}+ // Both added in 0.7.0. Upstream throws on an unknown sampling mode or a+ // negative ubatch, which would abort the load, so anything else is+ // dropped; 0 means "same as ubatch-size".+ if (mc.spec_draft_sampling === NON_DEFAULT_DRAFT_SAMPLING) {+ lines.push(`spec-draft-sampling = ${NON_DEFAULT_DRAFT_SAMPLING}`)+ }+ if (+ typeof mc.spec_draft_n_ubatch === 'number' &&+ Number.isFinite(mc.spec_draft_n_ubatch) &&+ mc.spec_draft_n_ubatch > 0+ ) {+ lines.push(`spec-draft-n-ubatch = ${Math.floor(mc.spec_draft_n_ubatch)}`)+ }}// Per-model sampling defaults. llama-server applies these as server-sidediff --git a/extensions/llamacpp-extension/src/util.test.ts b/extensions/llamacpp-extension/src/util.test.tsindex 82890653b..5f7aa6649 100644--- a/extensions/llamacpp-extension/src/util.test.ts+++ b/extensions/llamacpp-extension/src/util.test.ts@@ -3,6 +3,7 @@ import { logger } from '@janhq/core'import {buildEmbedBatches,detectMtpLayersFromGgufMeta,+ detectExpertCountFromGgufMeta,resolveSpecDraftKind,detectTemplateKwargsFromChatTemplate,estimateTokensFromText,@@ -566,6 +567,41 @@ describe('buildEmbedBatches', () => {})})+describe('detectExpertCountFromGgufMeta', () => {+ it('returns 0 for missing meta or a dense model', () => {+ expect(detectExpertCountFromGgufMeta(undefined)).toBe(0)+ expect(+ detectExpertCountFromGgufMeta({ 'general.architecture': 'llama' })+ ).toBe(0)+ })++ it('reads {arch}.expert_count, as a number or a string', () => {+ expect(+ detectExpertCountFromGgufMeta({+ 'general.architecture': 'qwen3moe',+ 'qwen3moe.expert_count': 128,+ })+ ).toBe(128)+ expect(+ detectExpertCountFromGgufMeta({+ 'general.architecture': 'gpt-oss',+ 'gpt-oss.expert_count': '32',+ })+ ).toBe(32)+ })++ // An arch-less key is not trusted: a draft or projector gguf can carry+ // another architecture's metadata, and a false positive breaks the load.+ it('ignores an expert_count under a different architecture', () => {+ expect(+ detectExpertCountFromGgufMeta({+ 'general.architecture': 'llama',+ 'other.expert_count': 8,+ })+ ).toBe(0)+ })+})+describe('detectMtpLayersFromGgufMeta', () => {it('returns 0 for undefined or empty meta', () => {expect(detectMtpLayersFromGgufMeta(undefined)).toBe(0)diff --git a/extensions/llamacpp-extension/src/util.ts b/extensions/llamacpp-extension/src/util.tsindex 37a12ef11..7242a95eb 100644--- a/extensions/llamacpp-extension/src/util.ts+++ b/extensions/llamacpp-extension/src/util.ts@@ -204,6 +204,28 @@ export function resolveSpecDraftKind(return 'mtp'}+/**+ * The number of MoE experts a GGUF declares (`<arch>.expert_count`), or 0 for+ * a dense model. Only the model's own architecture is read: unlike the MTP+ * suffix scan, a false positive here makes llama.cpp refuse the load when the+ * MoE cache is set, while a false negative only skips the cache.+ */+export function detectExpertCountFromGgufMeta(+ meta: Record<string, unknown> | undefined+): number {+ if (!meta) return 0+ const arch = meta['general.architecture']+ if (typeof arch !== 'string' || arch.length === 0) return 0+ const raw = meta[`${arch}.expert_count`]+ const n =+ typeof raw === 'number'+ ? raw+ : typeof raw === 'string' && raw.length > 0+ ? Number(raw)+ : NaN+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0+}+export function detectMtpLayersFromGgufMeta(meta: Record<string, unknown> | undefined): number {diff --git a/flatpak/ai.jan.Jan.yml b/flatpak/ai.jan.Jan.ymlindex 88d973855..0bad204d0 100644--- a/flatpak/ai.jan.Jan.yml+++ b/flatpak/ai.jan.Jan.yml@@ -116,8 +116,8 @@ modules:# (PINNED_TAG / PINNED_COMMIT), where build.rs looks for it by default;# this replaces the network clone in fetch-engine-source.sh- type: archive- url: https://github.com/ggml-org/llama.cpp/archive/refs/tags/b11146.tar.gz- sha256: 25eb89e300a0600bfdfadaac2acc7ec3a93cd23b992b7eff3c0eeae7987e4474+ url: https://github.com/ggml-org/llama.cpp/archive/refs/tags/b11669.tar.gz+ sha256: e06ba4fa263e30fdb9f0e65f00a8965202ddaa0c51f548a67e1f9b2164d04efcdest: src-tauri/plugins/tauri-plugin-llamacpp/vendor/llama.cpp- type: fileurl: https://repo.yarnpkg.com/4.5.3/packages/yarnpkg-cli/bin/yarn.jsdiff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 439106a0c..7bb17e250 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -7935,7 +7935,7 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.5.0"+version = "0.7.0"dependencies = ["base64 0.22.1","byteorder",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lockindex 2db46ceaf..cff5a9dfd 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.lock@@ -3421,7 +3421,7 @@ dependencies = [[[package]]name = "tauri-plugin-llamacpp"-version = "0.5.0"+version = "0.7.0"dependencies = ["base64 0.22.1","byteorder",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.tomlindex 8af7bebd5..607691981 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml+++ b/src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml@@ -1,6 +1,6 @@[package]name = "tauri-plugin-llamacpp"-version = "0.5.0"+version = "0.7.0"authors = ["Jan <[email protected]>"]description = "Tauri plugin for managing Jan LlamaCpp server processes and model loading"license = "Apache-2.0"diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rsindex 84e7cac66..6aafc0f9e 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs@@ -13,10 +13,10 @@// vendor/llama.cpp and with engine::PINNED_* on the Rust side; the shim// re-exports llama_version()/llama_build_number() so a mismatch is caught at// runtime instead of producing a silently wrong engine.-pub const LLAMA_CPP_TAG: &str = "b11146";-pub const LLAMA_CPP_BUILD_NUMBER: u32 = 11146;-pub const LLAMA_CPP_COMMIT: &str = "7fe450e19305b828c199d602c23a8337aaa1f03b";-pub const LLAMA_CPP_VERSION: &str = "0.5.0";+pub const LLAMA_CPP_TAG: &str = "b11669";+pub const LLAMA_CPP_BUILD_NUMBER: u32 = 11669;+pub const LLAMA_CPP_COMMIT: &str = "620d2225cc436ab0b001e3200e590e3b286ef9ab";+pub const LLAMA_CPP_VERSION: &str = "0.7.0";const COMMANDS: &[&str] = &[// Cleanup command@@ -398,7 +398,7 @@ mod engine {////// Separate from stage 2 because `GGML_CPU_ALL_VARIANTS` requires/// `GGML_BACKEND_DL`, which requires `BUILD_SHARED_LIBS`- /// (ggml/src/CMakeLists.txt:188-190 and :485-487, both hard errors) --+ /// (ggml/src/CMakeLists.txt:188-190 and :490-492, both hard errors) --/// while we still want a *static* libllama/libcommon/server-context. Two/// configures is the only way to have both.///@@ -554,7 +554,7 @@ mod engine {} else if feature_enabled("engine-cuda")&& env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default() == "x86_64"{- // A foreign JAN_LLAMA_CPP_DIR tree is not the b11146 the list was+ // A foreign JAN_LLAMA_CPP_DIR tree is not the b11669 the list was// copied from, so only the vendored pin is held to it.if env::var_os("JAN_LLAMA_CPP_DIR").is_none() {check_upstream_cuda_archs(src);@@ -622,7 +622,7 @@ mod engine {if feature_enabled("engine-cuda") {// NCCL is multi-GPU collective communication for distributed// inference. It is found opportunistically and defaults ON- // (ggml/CMakeLists.txt:210), which would make the shipped+ // (ggml/CMakeLists.txt:211), which would make the shipped// ggml-cuda module depend on whatever libnccl the build host// happened to have.cfg.arg("-DGGML_CUDA_NCCL=OFF");@@ -665,7 +665,7 @@ mod engine {// follow this flag."-DBUILD_SHARED_LIBS=OFF",// Use stage 1's ggml instead of building a second, static one- // (CMakeLists.txt:204-208 -> find_package(ggml REQUIRED)).+ // (CMakeLists.txt:214-216 -> find_package(ggml REQUIRED))."-DLLAMA_USE_SYSTEM_GGML=ON","-DLLAMA_BUILD_TESTS=OFF","-DLLAMA_BUILD_EXAMPLES=OFF",@@ -926,7 +926,7 @@ mod engine {words}- /// ggml/src/ggml-cuda/CMakeLists.txt's non-native default as of b11146,+ /// ggml/src/ggml-cuda/CMakeLists.txt's non-native default as of b11669,/// with 75-virtual changed to 75-real (see the call site)./// check_upstream_cuda_archs fails the build if a tag bump changes it.fn default_cuda_archs(v: (u32, u32)) -> String {@@ -986,7 +986,7 @@ mod engine {assert!(upstream == ours,"{} names CUDA archs {upstream:?}, but default_cuda_archs (copied from \- b11146) covers {ours:?}. Update default_cuda_archs to the new list, \+ b11669) covers {ours:?}. Update default_cuda_archs to the new list, \keeping 75 as -real (#9185), or set JAN_ENGINE_CUDA_ARCHS.",cml.display());@@ -1001,7 +1001,7 @@ mod engine {}/// `GGML_CPU_ALL_VARIANTS` hard-errors on architectures it has no variant- /// table for (ggml/src/CMakeLists.txt:581), so it is opt-in per arch rather+ /// table for (ggml/src/CMakeLists.txt:593), so it is opt-in per arch rather/// than unconditional.////// The table is keyed on (arch, OS), not arch alone: the ARM branch coversdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex 92ff0e948..5e43374a2 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -23,9 +23,9 @@ export interface EngineInfo {/** Mirrors `engine::commands::EngineVersion`. */export interface EngineVersion {- /** llama.cpp's own version, e.g. "0.5.0". */+ /** llama.cpp's own version, e.g. "0.7.0". */version: string- /** Upstream build tag the source was taken from, e.g. "b11146". */+ /** Upstream build tag the source was taken from, e.g. "b11669". */tag: string/** The tag's build number, as a string. */build_number: stringdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/package.json b/src-tauri/plugins/tauri-plugin-llamacpp/package.jsonindex 6ce5faefb..d3087d5a3 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/package.json+++ b/src-tauri/plugins/tauri-plugin-llamacpp/package.json@@ -1,6 +1,6 @@{"name": "@janhq/tauri-plugin-llamacpp-api",- "version": "0.5.0",+ "version": "0.7.0","private": true,"description": "","type": "module",diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cppindex e63708735..f10c815eb 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp@@ -35,7 +35,7 @@ namespace {/// Mirrors upstream's `ex_wrapper` (tools/server/server.cpp), which every route/// is registered behind. `build_table` captures the *unwrapped* handler members,/// so the two things that wrapper does have to be done here instead: map-/// `std::invalid_argument` to 400 rather than 500, and build the body with the+/// `std::invalid_argument` and `common_json_error` to 400 rather than 500, and build the body with the/// JSON library. Upstream's own messages quote the offending field/// (`response_format type must be one of "text" or "json_object"`), and a/// nlohmann parse error echoes the caller's bytes, so concatenating `e.what()`@@ -263,7 +263,7 @@ struct jan_llama_engine {}};-// server-context.cpp:4188 does `res->set_req(&req)`, and server_res_spipe keeps+// server-context.cpp:4897 does `res->set_req(&req)`, and server_res_spipe keeps// that pointer for the life of the stream -- so the request, and the// std::function its `should_stop` member references, must outlive the response.// Declaration order here is the destruction order that guarantees it.@@ -368,7 +368,7 @@ jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_patglobal.apply_to_params(engine->params);it->second.apply_to_params(engine->params);- // common_params_parse does this at arg.cpp:892-896; apply_to_params does+ // common_params_parse does this at arg.cpp:886-890; apply_to_params does// not. Without it n_threads stays 0 and ggml_threadpool_new_impl// memsets a zero-length array -> SIGSEGV. The router never hits this// because it forwards keys to a child that re-parses them.@@ -379,7 +379,7 @@ jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_patpostprocess_cpu_params(engine->params.speculative.draft.cpuparams_batch,&engine->params.cpuparams_batch);- // arg.cpp:886-890, added in 0.4.1: an unset `-mmdev` follows `--device`+ // arg.cpp:892-896, added in 0.4.1: an unset `-mmdev` follows `--device`// rather than falling back to auto-placement. Without it a preset that// pins the model to one GPU would still let the projector land wherever// ggml chose, which is the split the setting exists to prevent.@@ -409,7 +409,7 @@ jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_patengine->params.kv_overrides.back().key[0] = 0;}- // arg.cpp:963-966, at the end of common_params_parse_ex. Since 0.4.0 the+ // arg.cpp:964-967, at the end of common_params_parse_ex. Since 0.4.0 the// kwarg defaults to on when the user did not name it, and a template// with `supports_preserve_reasoning` reads it -- so omitting this here// would have the preset path preserve less reasoning than the argv path@@ -433,7 +433,7 @@ namespace {jan_llama_engine * finish_start(std::unique_ptr<jan_llama_engine> engine,char * err, size_t err_len) {try {- // server.cpp:156-161, in llama-server's main() -- which neither entry+ // server.cpp:168-173, in llama-server's main() -- which neither entry// point here goes through. n_parallel = -1 is the SERVER default, and// server_context loops `for (i = 0; i < n_parallel; i++)` to build its// slots, so leaving the sentinel unresolved yields an engine with no@@ -443,7 +443,7 @@ jan_llama_engine * finish_start(std::unique_ptr<jan_llama_engine> engine,engine->params.kv_unified = true;}- // server.cpp:164-174, immediately after the block above and dependent on+ // server.cpp:176-186, immediately after the block above and dependent on// it: the pool is n_parallel wide, so it can only be sized once the// sentinel is resolved. Only `-c 0` (size to the model's trained// context) leaves n_ctx at 0 for this to act on; any explicit ctx-size@@ -592,11 +592,17 @@ jan_llama_response * jan_llama_engine_request(jan_llama_engine * engine,return out;} catch (const std::invalid_argument & e) {// Upstream's own mapping: a malformed request is the client's to fix, so- // it must not look retryable. server-common.cpp throws this from 16+ // it must not look retryable. server-common.cpp throws this from 23// sites (missing `messages`, bad `content` type, `top_logprobs` without// `logprobs`, ...), all of which reached Jan's API as 500 before.out->res = error_response(e.what(), ERROR_TYPE_INVALID_REQUEST);return out;+ } catch (const common_json_error & e) {+ // Since 0.7.0 upstream maps JSON parse and type errors to 400 too+ // (server.cpp ex_wrapper); it derives from std::runtime_error, so it+ // must be caught before the std::exception arm below.+ out->res = error_response(e.what(), ERROR_TYPE_INVALID_REQUEST);+ return out;} catch (const std::exception & e) {out->res = error_response(e.what(), ERROR_TYPE_SERVER);return out;@@ -676,7 +682,7 @@ void jan_llama_load_backends(const char * dir) {}}-// Mirrors common_print_available_devices (common/arg.cpp:1139-1161): load every+// Mirrors common_print_available_devices (common/arg.cpp:1144-1167): load every// backend, then report the non-CPU devices with memory in MiB. The CPU device// is excluded there too -- "offload to CPU" is not a choice the setting offers.char * jan_llama_devices_json(void) {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.hindex 0190e7bba..4454a9035 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.h@@ -96,8 +96,8 @@ void jan_llama_string_free(char * s);// The llama.cpp the shim was compiled against, for the pin assertion in// build.rs / engine::assert_pinned_version.-const char * jan_llama_version(void); // e.g. "0.5.0"-int jan_llama_build_number(void); // e.g. 11146+const char * jan_llama_version(void); // e.g. "0.7.0"+int jan_llama_build_number(void); // e.g. 11669const char * jan_llama_commit(void);#ifdef __cplusplusdiff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rsindex 307dd0840..5b641657e 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs@@ -576,9 +576,9 @@ pub async fn get_engine_info(/// therefore no use to a settings screen that wants to name the engine.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct EngineVersion {- /// llama.cpp's own version, e.g. `0.5.0`.+ /// llama.cpp's own version, e.g. `0.7.0`.pub version: String,- /// The upstream build tag the source was taken from, e.g. `b11146`.+ /// The upstream build tag the source was taken from, e.g. `b11669`.pub tag: String,/// The same tag's build number, which is what the shim reports back over/// the FFI and what a version mismatch is checked against.diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rsindex f0b54093f..92706b8a2 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/mod.rs@@ -213,9 +213,9 @@ mod tests {#[test]fn pin_constants_are_populated_from_build_rs() {- assert_eq!(PINNED_TAG, "b11146");- assert_eq!(PINNED_BUILD_NUMBER, "11146");- assert_eq!(PINNED_VERSION, "0.5.0");+ assert_eq!(PINNED_TAG, "b11669");+ assert_eq!(PINNED_BUILD_NUMBER, "11669");+ assert_eq!(PINNED_VERSION, "0.7.0");assert_eq!(PINNED_COMMIT.len(), 40, "commit should be a full sha");}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rsindex 56232675c..98c4e6e84 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/preset.rs@@ -46,7 +46,7 @@ fn section_bodies(ini: &str) -> HashMap<String, Vec<String>> {/// Read on the Rust side as well as by the C++ loader because the worker has to/// act on two of them before any model is loaded: `slot-save-path` names a/// directory llama.cpp *throws* on if it does not exist-/// (`common/arg.cpp:3580`), and the KV state store has to agree with llama.cpp+/// (`common/arg.cpp:3635`), and the KV state store has to agree with llama.cpp/// on where files land.pub fn shared_value(ini: &str, key: &str) -> Option<String> {let mut in_shared = false;diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rsindex 6121d5391..5bacf95cb 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/registry.rs@@ -1,11 +1,11 @@//! In-process replacement for llama.cpp's router mode.//!//! Upstream's router is a process supervisor plus a reverse proxy: it spawns a-//! child `llama-server` per model (`server-models.cpp:1020-1046`). Linking+//! child `llama-server` per model (`server_models::load` in server-models.cpp). Linking//! `server_context` directly means there are no children, so what survives is//! only the bookkeeping -- a model registry with `models_max` and LRU eviction.-//! The two invariants are taken from upstream (`server-models.cpp:92-95` and-//! `:103-210`): never evict a model with requests in flight, and make a caller+//! The two invariants are taken from upstream (`server_lru_sched::pick_victim`+//! and its queue in server-models.cpp): never evict a model with requests in flight, and make a caller//! that arrives while the registry is full wait rather than fail.use std::collections::{HashMap, HashSet};@@ -683,7 +683,7 @@ mod tests {#[test]fn a_busy_model_is_never_evicted_even_if_it_is_oldest() {- // Upstream's rule (server-models.cpp:92-95): evicting a model with a+ // Upstream's rule (server_lru_sched::pick_victim): evicting a model with a// request in flight would cancel a live generation.let entries = [("old-but-busy", 3usize, 1u64), ("idle", 0, 9)];assert_eq!(diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rsindex fe569d380..288082538 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/slots.rs@@ -1,7 +1,7 @@//! Persistence of a thread's KV cache across sessions.//!//! llama.cpp can already write a slot's KV cache to disk-//! (`POST /slots/{id}?action=save`, `server-context.cpp:2475`), but the file it+//! (`POST /slots/{id}?action=save`, `server-context.cpp:2992`), but the file it//! writes carries no identity: `llama_state_seq_load_file` checks a magic and a//! version, and the restore path checks that the tokens fit the context and are//! in the vocab. None of that notices that the file was written by a *different@@ -281,7 +281,7 @@ impl StateStore {}/// Creates the directory. llama.cpp's `--slot-save-path` handler *throws*- /// when the path is not a directory (`common/arg.cpp:3580`), and that+ /// when the path is not a directory (`common/arg.cpp:3635`), and that/// unwinds out of engine startup, so a missing cache directory would take/// the whole engine down rather than disabling one feature.pub fn ensure_dir(&self) -> std::io::Result<()> {diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsxindex 82de0a756..ee5e93711 100644--- a/web-app/src/containers/ModelSetting.tsx+++ b/web-app/src/containers/ModelSetting.tsx@@ -175,7 +175,8 @@ function useModelSettingControls(model: Model, provider: ProviderObject) {key === 'batch_size' ||key === 'cpu_moe' ||key === 'n_cpu_moe' ||- key === 'n_cpu_ffn'+ key === 'n_cpu_ffn' ||+ key === 'moe_cache_mib') {// Check if model is running before stopping itserviceHub@@ -412,6 +413,8 @@ type SpecDraftInfo = {spec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}export function SpecDraftPanel({ modelId }: { modelId: string }) {@@ -441,6 +444,8 @@ export function SpecDraftPanel({ modelId }: { modelId: string }) {spec_draft_n_max?: number | nullspec_draft_n_min?: number | nullspec_draft_p_min?: number | null+ spec_draft_sampling?: string | null+ spec_draft_n_ubatch?: number | null}) => {try {await serviceHub.models().updateMtpSettings(modelId, patch)@@ -456,7 +461,11 @@ export function SpecDraftPanel({ modelId }: { modelId: string }) {const enabled = info.mtp === trueconst updateNumber = (- key: 'spec_draft_n_max' | 'spec_draft_n_min' | 'spec_draft_p_min',+ key:+ | 'spec_draft_n_max'+ | 'spec_draft_n_min'+ | 'spec_draft_p_min'+ | 'spec_draft_n_ubatch',raw: string) => {const trimmed = raw.trim()@@ -485,6 +494,7 @@ export function SpecDraftPanel({ modelId }: { modelId: string }) {</span></div><Switch+ aria-label={t('common:modelSettings.specDraft.enable')}checked={enabled}onCheckedChange={(v) => {setInfo({ ...info, mtp: v })@@ -527,6 +537,44 @@ export function SpecDraftPanel({ modelId }: { modelId: string }) {step={0.05}onChange={(raw) => updateNumber('spec_draft_p_min', raw)}/>+ <div className="space-y-2">+ <div className="flex items-start justify-between gap-8">+ <div className="mb-1 truncate">+ <span className="font-medium">+ {t('common:modelSettings.specDraft.probabilistic')}+ </span>+ </div>+ <Switch+ aria-label={t('common:modelSettings.specDraft.probabilistic')}+ checked={info.spec_draft_sampling === 'probabilistic'}+ onCheckedChange={(v) => {+ // Off clears the key so the model tracks upstream's greedy+ // default rather than pinning it.+ setInfo({+ ...info,+ spec_draft_sampling: v ? 'probabilistic' : undefined,+ })+ void persist({+ spec_draft_sampling: v ? 'probabilistic' : null,+ })+ }}+ />+ </div>+ <p className="text-muted-foreground leading-normal text-xs">+ {t('common:modelSettings.specDraft.probabilisticDescription')}+ </p>+ </div>+ <NumberRow+ label={t('common:modelSettings.specDraft.nUbatch')}+ description={t(+ 'common:modelSettings.specDraft.nUbatchDescription'+ )}+ placeholder="0"+ value={info.spec_draft_n_ubatch}+ min={0}+ step={1}+ onChange={(raw) => updateNumber('spec_draft_n_ubatch', raw)}+ /></>)}</div>diff --git a/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsx b/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsxindex 8dc0ead5d..f85378602 100644--- a/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsx+++ b/web-app/src/containers/__tests__/ModelSetting.specDraft.test.tsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest'-import { render, screen, waitFor } from '@testing-library/react'+import { render, screen, waitFor, fireEvent } from '@testing-library/react'import '@testing-library/jest-dom'const hoisted = vi.hoisted(() => ({@@ -17,8 +17,15 @@ vi.mock('@/hooks/useServiceHub', () => {return { useServiceHub: () => hub, getServiceHub: () => hub }})+vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (k: string) => k }),+}))+import { SpecDraftPanel } from '../ModelSetting'+const ENABLE = 'common:modelSettings.specDraft.enable'+const PROBABILISTIC = 'common:modelSettings.specDraft.probabilistic'+// llama.cpp is linked into the worker at a pinned version, so there is no// backend build number left to gate MTP on.describe('SpecDraftPanel', () => {@@ -31,16 +38,46 @@ describe('SpecDraftPanel', () => {hoisted.getMtpInfo.mockResolvedValue({ mtp_layers: 2, mtp: false })render(<SpecDraftPanel modelId="glm" />)- const toggle = await screen.findByRole('switch')+ const toggle = await screen.findByRole('switch', { name: ENABLE })expect(toggle).toBeEnabled()+ // The draft tunables only appear once speculative decoding is on.+ expect(+ screen.queryByRole('switch', { name: PROBABILISTIC })+ ).not.toBeInTheDocument()})it('reports a model whose MTP is already on as on', async () => {hoisted.getMtpInfo.mockResolvedValue({ mtp_layers: 2, mtp: true })render(<SpecDraftPanel modelId="glm" />)- const toggle = await screen.findByRole('switch')+ const toggle = await screen.findByRole('switch', { name: ENABLE })+ expect(toggle).toBeChecked()+ })++ // greedy is upstream's default, so turning probabilistic off clears the key+ // rather than writing `greedy`.+ it('persists probabilistic draft sampling and clears it when turned off', async () => {+ hoisted.getMtpInfo.mockResolvedValue({+ mtp_layers: 2,+ mtp: true,+ spec_draft_sampling: 'probabilistic',+ })+ render(<SpecDraftPanel modelId="glm" />)++ const toggle = await screen.findByRole('switch', { name: PROBABILISTIC })expect(toggle).toBeChecked()+ fireEvent.click(toggle)+ await waitFor(() =>+ expect(hoisted.updateMtpSettings).toHaveBeenCalledWith('glm', {+ spec_draft_sampling: null,+ })+ )+ fireEvent.click(toggle)+ await waitFor(() =>+ expect(hoisted.updateMtpSettings).toHaveBeenLastCalledWith('glm', {+ spec_draft_sampling: 'probabilistic',+ })+ )})it('renders nothing for a model with no MTP heads', async () => {diff --git a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.tsindex 8a993f136..1dde851b4 100644--- a/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts+++ b/web-app/src/hooks/__tests__/useModelProvider.coverage.test.ts@@ -372,6 +372,12 @@ describe('useModelProvider - coverage', () => {}, (migrated: any) => {expect(migrated.providers[0].models[0].settings.batch_size).toBeDefined()}],+ [19, 'adding the per-model moe_cache_mib control (llama.cpp 0.7.0)', {+ providers: [{ provider: 'llamacpp', models: [{ id: 'm1', settings: {} }], settings: [] }],+ deletedModels: [],+ }, (migrated: any) => {+ expect(migrated.providers[0].models[0].settings.moe_cache_mib).toBeDefined()+ }],[4, 'adding cpu_moe and n_cpu_moe', {providers: [{ provider: 'llamacpp', models: [{ id: 'm1', settings: {} }], settings: [] }],deletedModels: [],diff --git a/web-app/src/hooks/useModelProvider.ts b/web-app/src/hooks/useModelProvider.tsindex 9bc50355f..6ceb92490 100644--- a/web-app/src/hooks/useModelProvider.ts+++ b/web-app/src/hooks/useModelProvider.ts@@ -795,9 +795,29 @@ export const useModelProvider = create<ModelProviderState>()(})}+ if (version <= 19 && state?.providers) {+ // llama.cpp 0.7.0 added --moe-cache-mib. It is per-model because+ // llama.cpp refuses to load a dense model with it set; add the+ // control to persisted llamacpp models so the sidebar renders it.+ state.providers.forEach((provider) => {+ if (provider.provider !== 'llamacpp' || !provider.models) return+ provider.models.forEach((model) => {+ if (!model.settings) model.settings = {}+ if (!model.settings.moe_cache_mib) {+ model.settings.moe_cache_mib = {+ ...modelSettings.moe_cache_mib,+ controller_props: {+ ...modelSettings.moe_cache_mib.controller_props,+ },+ }+ }+ })+ })+ }+return state},- version: 19,+ version: 20,}))diff --git a/web-app/src/lib/predefined.ts b/web-app/src/lib/predefined.tsindex 7aaa8e5f4..274b56896 100644--- a/web-app/src/lib/predefined.ts+++ b/web-app/src/lib/predefined.ts@@ -185,6 +185,18 @@ export const modelSettings = {type: 'number',},},+ moe_cache_mib: {+ key: 'moe_cache_mib',+ title: 'MoE expert GPU cache (MiB)',+ description:+ 'Experimental. GPU memory for caching the MoE experts kept in the CPU by the settings above, which speeds those models up. Applies to MoE models only and is ignored for any other model. Needs a single GPU. Leave empty to disable.',+ controller_type: 'input',+ controller_props: {+ value: '',+ placeholder: '4096',+ type: 'number',+ },+ },override_tensor_buffer_t: {key: 'override_tensor_buffer_t',title: 'Override Tensor Buffer Type',diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 15f05f554..6e183e6da 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -356,7 +356,11 @@"nMin": "Min draft tokens","nMinDescription": "Minimum number of tokens to draft per step. Default 0.","pMin": "Min draft probability",- "pMinDescription": "Minimum probability for greedy drafting (0–1). Default 0.75."+ "pMinDescription": "Minimum probability for greedy drafting (0–1). Default 0.75.",+ "probabilistic": "Probabilistic draft sampling",+ "probabilisticDescription": "Sample the draft instead of taking its most likely token, and have the model verify it by rejection sampling. Off uses greedy drafting (the default).",+ "nUbatch": "Draft batch size",+ "nUbatchDescription": "Physical batch size of the draft context. Lower it to save VRAM. 0 uses the model's batch size (the default)."},"templateKwargs": {"section": "Chat template options",diff --git a/web-app/src/locales/it/common.json b/web-app/src/locales/it/common.jsonindex b83ac6de9..3158a63b7 100644--- a/web-app/src/locales/it/common.json+++ b/web-app/src/locales/it/common.json@@ -245,7 +245,11 @@"nMin": "Numero minimo token bozza","nMinDescription": "Numero minimo di token da abbozzare per passaggio. Predefinito: 0.","pMin": "Probabilità minima bozza",- "pMinDescription": "Probabilità minima per l'elaborazione greedy (0–1). Predefinito: 0.75."+ "pMinDescription": "Probabilità minima per l'elaborazione greedy (0–1). Predefinito: 0.75.",+ "probabilistic": "Campionamento probabilistico della bozza",+ "probabilisticDescription": "Campiona la bozza invece di prendere il token più probabile; il modello la verifica con il campionamento a rifiuto. Se disattivato usa la bozza greedy (predefinito).",+ "nUbatch": "Dimensione batch della bozza",+ "nUbatchDescription": "Dimensione fisica del batch del contesto della bozza. Riducila per risparmiare VRAM. 0 usa la dimensione batch del modello (predefinito)."}},"dialogs": {diff --git a/web-app/src/locales/ja/common.json b/web-app/src/locales/ja/common.jsonindex f5128f991..50aaff293 100644--- a/web-app/src/locales/ja/common.json+++ b/web-app/src/locales/ja/common.json@@ -257,7 +257,11 @@"nMin": "最小下書きトークン数","nMinDescription": "ステップごとに下書きするトークンの最小数。デフォルトは0です。","pMin": "最小下書き確率",- "pMinDescription": "貪欲な下書きの最小確率(0〜1)。デフォルトは0.75です。"+ "pMinDescription": "貪欲な下書きの最小確率(0〜1)。デフォルトは0.75です。",+ "probabilistic": "確率的な下書きサンプリング",+ "probabilisticDescription": "最も確率の高いトークンを取る代わりに下書きをサンプリングし、モデルが棄却サンプリングで検証します。オフの場合は貪欲な下書き(デフォルト)を使います。",+ "nUbatch": "下書きのバッチサイズ",+ "nUbatchDescription": "下書きコンテキストの物理バッチサイズ。VRAMを節約するには小さくします。0はモデルのバッチサイズを使います(デフォルト)。"}},"dialogs": {diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.tsindex 3d5a28dd5..3e17ad00c 100644--- a/web-app/src/services/models/default.ts+++ b/web-app/src/services/models/default.ts@@ -602,6 +602,8 @@ export class DefaultModelsService implements ModelsService {spec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}> {try {const engine = this.getEngine('llamacpp') as AIEngine & {@@ -611,6 +613,8 @@ export class DefaultModelsService implements ModelsService {spec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}>}if (engine && typeof engine.getMtpInfo === 'function') {@@ -629,6 +633,8 @@ export class DefaultModelsService implements ModelsService {spec_draft_n_max?: number | nullspec_draft_n_min?: number | nullspec_draft_p_min?: number | null+ spec_draft_sampling?: string | null+ spec_draft_n_ubatch?: number | null}): Promise<void> {const engine = this.getEngine('llamacpp') as AIEngine & {@@ -639,6 +645,8 @@ export class DefaultModelsService implements ModelsService {spec_draft_n_max?: number | nullspec_draft_n_min?: number | nullspec_draft_p_min?: number | null+ spec_draft_sampling?: string | null+ spec_draft_n_ubatch?: number | null}) => Promise<void>}diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.tsindex 6bbb63016..3c0951ed3 100644--- a/web-app/src/services/models/types.ts+++ b/web-app/src/services/models/types.ts@@ -169,6 +169,8 @@ export interface ModelsService {spec_draft_n_max?: numberspec_draft_n_min?: numberspec_draft_p_min?: number+ spec_draft_sampling?: string+ spec_draft_n_ubatch?: number}>updateMtpSettings(modelId: string,@@ -177,6 +179,8 @@ export interface ModelsService {spec_draft_n_max?: number | nullspec_draft_n_min?: number | nullspec_draft_p_min?: number | null+ spec_draft_sampling?: string | null+ spec_draft_n_ubatch?: number | null}): Promise<void>updateModelSettings(@@ -201,9 +205,9 @@ export interface ModelsService {* extension, not to the plugin.*/export interface EngineVersionInfo {- /** llama.cpp's own version, e.g. "0.5.0". */+ /** llama.cpp's own version, e.g. "0.7.0". */version: string- /** Upstream build tag, e.g. "b11146". */+ /** Upstream build tag, e.g. "b11669". */tag: stringbuildNumber: string/** Full commit sha the build is pinned to. */