Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix: kv-cache defaults and fit migration (#7751)
Louis2b18fb5ab127
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.jsonindex 25ba7ba45..988f3cb76 100644--- a/extensions/llamacpp-extension/settings.json+++ b/extensions/llamacpp-extension/settings.json@@ -189,6 +189,19 @@]}},+ {+ "key": "parallel",+ "title": "Parallel Sequences",+ "description": "Number of parallel sequences to decode (0 = llama.cpp default of 1). Set to 1 to also enable -kvu for optimized single-request serving.",+ "controllerType": "input",+ "controllerProps": {+ "value": 1,+ "placeholder": "1",+ "type": "number",+ "textAlign": "right",+ "min": 0+ }+ },{"key": "cont_batching","title": "Continuous Batching",diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.tsindex 4267b5e02..624191f82 100644--- a/extensions/llamacpp-extension/src/index.ts+++ b/extensions/llamacpp-extension/src/index.ts@@ -149,6 +149,12 @@ export default class llamacpp_extension extends AIEngine {}this.config = loadedConfig as LlamacppConfig+ // Migration v1: upgrade f16 KV cache defaults to q8_0+ await this.migrateKvCacheDefaults()++ // Migration v2: disable fit by default+ await this.migrateFitDefault()+this.autoUnload = this.config.auto_unloadthis.timeout = this.config.timeoutthis.llamacpp_env = this.config.llamacpp_env@@ -198,6 +204,58 @@ export default class llamacpp_extension extends AIEngine {}}+ private async migrateKvCacheDefaults(): Promise<void> {+ const MIGRATION_KEY = 'llamacpp_kv_cache_migrated_v1'+ if (localStorage.getItem(MIGRATION_KEY)) return++ const keysToMigrate = ['cache_type_k', 'cache_type_v'] as const+ const needsMigration = keysToMigrate.some(+ (k) => this.config[k] === 'f16'+ )++ if (needsMigration) {+ const settings = await this.getSettings()+ await this.updateSettings(+ settings.map((item) => {+ if (+ keysToMigrate.includes(item.key as (typeof keysToMigrate)[number]) &&+ item.controllerProps.value === 'f16'+ ) {+ item.controllerProps.value = 'q8_0'+ }+ return item+ })+ )+ for (const k of keysToMigrate) {+ if (this.config[k] === 'f16') this.config[k] = 'q8_0'+ }+ logger.info('Migrated KV cache types from f16 to q8_0')+ }++ localStorage.setItem(MIGRATION_KEY, '1')+ }++ private async migrateFitDefault(): Promise<void> {+ const MIGRATION_KEY = 'llamacpp_fit_disabled_v1'+ if (localStorage.getItem(MIGRATION_KEY)) return++ if (this.config.fit === true) {+ const settings = await this.getSettings()+ await this.updateSettings(+ settings.map((item) => {+ if (item.key === 'fit') {+ item.controllerProps.value = false+ }+ return item+ })+ )+ this.config.fit = false+ logger.info('Migrated fit setting: disabled by default')+ }++ localStorage.setItem(MIGRATION_KEY, '1')+ }+async configureBackends(): Promise<void> {if (this.isConfiguringBackends) {logger.info(diff --git a/extensions/llamacpp-extension/src/test/index.test.ts b/extensions/llamacpp-extension/src/test/index.test.tsindex e90235f7a..d8148fde4 100644--- a/extensions/llamacpp-extension/src/test/index.test.ts+++ b/extensions/llamacpp-extension/src/test/index.test.ts@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'import llamacpp_extension from '../index'+import { normalizeLlamacppConfig } from '@janhq/tauri-plugin-llamacpp-api'+// Mock fetch globallyglobal.fetch = vi.fn()@@ -394,6 +396,156 @@ describe('llamacpp_extension', () => {})})+ describe('migrateKvCacheDefaults', () => {+ beforeEach(() => {+ vi.mocked(localStorage.getItem).mockReturnValue(null)+ })++ it('should skip migration if already migrated', async () => {+ vi.mocked(localStorage.getItem).mockReturnValue('1')+ extension['config'] = { cache_type_k: 'f16', cache_type_v: 'f16' } as any+ extension['getSettings'] = vi.fn()++ await extension['migrateKvCacheDefaults']()++ expect(extension['getSettings']).not.toHaveBeenCalled()+ })++ it('should set migration key without calling updateSettings when no f16 values', async () => {+ extension['config'] = { cache_type_k: 'q8_0', cache_type_v: 'q8_0' } as any+ extension['getSettings'] = vi.fn()+ extension['updateSettings'] = vi.fn()++ await extension['migrateKvCacheDefaults']()++ expect(extension['getSettings']).not.toHaveBeenCalled()+ expect(extension['updateSettings']).not.toHaveBeenCalled()+ expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_kv_cache_migrated_v1', '1')+ })++ it('should migrate cache_type_k from f16 to q8_0', async () => {+ extension['config'] = { cache_type_k: 'f16', cache_type_v: 'q8_0' } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'cache_type_k', controllerProps: { value: 'f16' } },+ { key: 'cache_type_v', controllerProps: { value: 'q8_0' } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateKvCacheDefaults']()++ const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]+ expect(updatedSettings.find((s: any) => s.key === 'cache_type_k').controllerProps.value).toBe('q8_0')+ expect(updatedSettings.find((s: any) => s.key === 'cache_type_v').controllerProps.value).toBe('q8_0')+ expect(extension['config'].cache_type_k).toBe('q8_0')+ expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_kv_cache_migrated_v1', '1')+ })++ it('should migrate cache_type_v from f16 to q8_0', async () => {+ extension['config'] = { cache_type_k: 'q8_0', cache_type_v: 'f16' } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'cache_type_k', controllerProps: { value: 'q8_0' } },+ { key: 'cache_type_v', controllerProps: { value: 'f16' } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateKvCacheDefaults']()++ const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]+ expect(updatedSettings.find((s: any) => s.key === 'cache_type_v').controllerProps.value).toBe('q8_0')+ expect(extension['config'].cache_type_v).toBe('q8_0')+ })++ it('should migrate both cache types when both are f16', async () => {+ extension['config'] = { cache_type_k: 'f16', cache_type_v: 'f16' } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'cache_type_k', controllerProps: { value: 'f16' } },+ { key: 'cache_type_v', controllerProps: { value: 'f16' } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateKvCacheDefaults']()++ expect(extension['config'].cache_type_k).toBe('q8_0')+ expect(extension['config'].cache_type_v).toBe('q8_0')+ expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_kv_cache_migrated_v1', '1')+ })++ it('should not overwrite non-f16 values in settings during migration', async () => {+ extension['config'] = { cache_type_k: 'f16', cache_type_v: 'q4_0' } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'cache_type_k', controllerProps: { value: 'f16' } },+ { key: 'cache_type_v', controllerProps: { value: 'q4_0' } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateKvCacheDefaults']()++ const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]+ expect(updatedSettings.find((s: any) => s.key === 'cache_type_v').controllerProps.value).toBe('q4_0')+ })+ })++ describe('migrateFitDefault', () => {+ beforeEach(() => {+ vi.mocked(localStorage.getItem).mockReturnValue(null)+ })++ it('should skip migration if already migrated', async () => {+ vi.mocked(localStorage.getItem).mockReturnValue('1')+ extension['config'] = { fit: true } as any+ extension['getSettings'] = vi.fn()++ await extension['migrateFitDefault']()++ expect(extension['getSettings']).not.toHaveBeenCalled()+ })++ it('should set migration key without calling updateSettings when fit is already false', async () => {+ extension['config'] = { fit: false } as any+ extension['getSettings'] = vi.fn()+ extension['updateSettings'] = vi.fn()++ await extension['migrateFitDefault']()++ expect(extension['getSettings']).not.toHaveBeenCalled()+ expect(extension['updateSettings']).not.toHaveBeenCalled()+ expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_fit_disabled_v1', '1')+ })++ it('should disable fit when it is true', async () => {+ extension['config'] = { fit: true } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'fit', controllerProps: { value: true } },+ { key: 'ctx_size', controllerProps: { value: 2048 } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateFitDefault']()++ const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]+ expect(updatedSettings.find((s: any) => s.key === 'fit').controllerProps.value).toBe(false)+ expect(updatedSettings.find((s: any) => s.key === 'ctx_size').controllerProps.value).toBe(2048)+ expect(extension['config'].fit).toBe(false)+ expect(localStorage.setItem).toHaveBeenCalledWith('llamacpp_fit_disabled_v1', '1')+ })++ it('should not modify other settings during fit migration', async () => {+ extension['config'] = { fit: true } as any+ extension['getSettings'] = vi.fn().mockResolvedValue([+ { key: 'fit', controllerProps: { value: true } },+ { key: 'fit_target', controllerProps: { value: '1024' } },+ { key: 'fit_ctx', controllerProps: { value: '' } },+ ])+ extension['updateSettings'] = vi.fn().mockResolvedValue(undefined)++ await extension['migrateFitDefault']()++ const updatedSettings = vi.mocked(extension['updateSettings']).mock.calls[0][0]+ expect(updatedSettings.find((s: any) => s.key === 'fit_target').controllerProps.value).toBe('1024')+ expect(updatedSettings.find((s: any) => s.key === 'fit_ctx').controllerProps.value).toBe('')+ })+ })+describe('getLoadedModels', () => {it('should return list of loaded models', async () => {extension['activeSessions'].set(123, {@@ -587,4 +739,38 @@ describe('llamacpp_extension', () => {})})})+})++describe('normalizeLlamacppConfig', () => {+ describe('parallel field', () => {+ it('should default parallel to 1 when undefined', () => {+ const result = normalizeLlamacppConfig({})+ expect(result.parallel).toBe(1)+ })++ it('should default parallel to 1 when null', () => {+ const result = normalizeLlamacppConfig({ parallel: null })+ expect(result.parallel).toBe(1)+ })++ it('should default parallel to 1 when empty string', () => {+ const result = normalizeLlamacppConfig({ parallel: '' })+ expect(result.parallel).toBe(1)+ })++ it('should parse parallel as a number', () => {+ const result = normalizeLlamacppConfig({ parallel: 4 })+ expect(result.parallel).toBe(4)+ })++ it('should parse parallel from a string number', () => {+ const result = normalizeLlamacppConfig({ parallel: '2' })+ expect(result.parallel).toBe(2)+ })++ it('should allow parallel of 0 (disables the flag)', () => {+ const result = normalizeLlamacppConfig({ parallel: 0 })+ expect(result.parallel).toBe(0)+ })+ })})\ No newline at end of filediff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.tsindex 5848e1e73..a83bdd803 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts@@ -80,6 +80,7 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {rope_freq_scale: asNumber(config.rope_freq_scale, 1.0),ctx_shift: asBool(config.ctx_shift),+ parallel: asNumber(config.parallel, 1),}}diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.tsindex e4f4da082..aa7e9d619 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts@@ -64,6 +64,7 @@ export type LlamacppConfig = {rope_freq_base: numberrope_freq_scale: numberctx_shift: boolean+ parallel: number}export type ModelPlan = {diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rsindex 0f4a19daa..f9d919d80 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs@@ -1,5 +1,8 @@use serde::{Deserialize, Serialize};+fn default_parallel() -> i32 {+ 1+ }#[derive(Debug, Clone, Serialize, Deserialize)]pub struct LlamacppConfig {pub version_backend: String,@@ -38,6 +41,8 @@ pub struct LlamacppConfig {pub rope_freq_base: f32,pub rope_freq_scale: f32,pub ctx_shift: bool,+ #[serde(default = "default_parallel")]+ pub parallel: i32,}/// Minimum llama.cpp build number that changed --flash-attn from a boolean@@ -137,6 +142,9 @@ impl ArgumentBuilder {// Boolean flagsself.add_boolean_flags();+ // Parallel sequences+ self.add_parallel_settings();+// Embedding vs text generation specific argsif self.is_embedding {self.add_embedding_args();@@ -289,6 +297,17 @@ impl ArgumentBuilder {}}+ fn add_parallel_settings(&mut self) {+ if self.config.parallel > 0 {+ self.args.push("--parallel".to_string());+ self.args.push(self.config.parallel.to_string());+ if self.config.parallel == 1 {+ // https://github.com/ggml-org/llama.cpp/issues/17450+ self.args.push("-kvu".to_string());+ }+ }+ }+fn add_embedding_args(&mut self) {self.args.push("--embedding".to_string());self.args.push("--pooling".to_string());@@ -311,8 +330,9 @@ impl ArgumentBuilder {self.args.push(self.config.cache_type_k.clone());}- // cache_type_v only if flash_attn is 'on' and value is not f16/f32- if self.config.flash_attn == "on"+ // cache_type_v only if flash_attn is not 'off' and value is not f16/f32+ // cache_type_v needs divisibility check but since users want to tinker around it, should allow them to do so+ if self.config.flash_attn != "off"&& !self.config.cache_type_v.is_empty()&& self.config.cache_type_v != "f16"&& self.config.cache_type_v != "f32"@@ -416,6 +436,7 @@ mod tests {rope_freq_base: 0.0,rope_freq_scale: 1.0,ctx_shift: false,+ parallel: 1,}}@@ -831,6 +852,18 @@ mod tests {assert_no_flag(&args, "--cache-type-v");}+ #[test]+ fn test_cache_type_v_with_auto_flash_attn() {+ // "auto" != "off", so cache_type_v should be included (changed from requiring "on")+ let mut config = default_config(); // flash_attn defaults to "auto"+ config.cache_type_v = "q8_0".to_string();++ let builder = ArgumentBuilder::new(config, false).unwrap();+ let args = builder.build("test", "/path", 8080, None);++ assert_arg_pair(&args, "--cache-type-v", "q8_0");+ }+#[test]fn test_cache_type_v_f16_not_added() {let mut config = default_config();@@ -1050,4 +1083,38 @@ mod tests {assert_arg_pair(&args, "--rope-scale", "2");assert_arg_pair(&args, "--port", "9000");}-}\ No newline at end of file++ #[test]+ fn test_parallel_not_added_when_zero() {+ let mut config = default_config();+ config.parallel = 0;+ let builder = ArgumentBuilder::new(config, false).unwrap();+ let args = builder.build("test", "/path", 8080, None);++ assert_no_flag(&args, "--parallel");+ assert_no_flag(&args, "-kvu");+ }++ #[test]+ fn test_parallel_1_adds_parallel_and_kvu() {+ let config = default_config(); // default is 1++ let builder = ArgumentBuilder::new(config, false).unwrap();+ let args = builder.build("test", "/path", 8080, None);++ assert_arg_pair(&args, "--parallel", "1");+ assert_has_flag(&args, "-kvu");+ }++ #[test]+ fn test_parallel_greater_than_1_no_kvu() {+ let mut config = default_config();+ config.parallel = 4;++ let builder = ArgumentBuilder::new(config, false).unwrap();+ let args = builder.build("test", "/path", 8080, None);++ assert_arg_pair(&args, "--parallel", "4");+ assert_no_flag(&args, "-kvu");+ }+}diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rsindex 26a1a95a2..a46b414e1 100644--- a/src-tauri/src/bin/jan-cli.rs+++ b/src-tauri/src/bin/jan-cli.rs@@ -1330,13 +1330,14 @@ fn build_llamacpp_config(n_gpu_layers: i32, ctx_size: i32, timeout: i32, fit: bono_mmap: false,mlock: false,no_kv_offload: false,- cache_type_k: String::new(),- cache_type_v: String::new(),+ cache_type_k: "q8_0".to_string(),+ cache_type_v: "q8_0".to_string(),defrag_thold: -1.0,rope_scaling: String::new(),rope_scale: 0.0,rope_freq_base: 0.0,rope_freq_scale: 0.0,ctx_shift: false,+ parallel: 1}}diff --git a/src-tauri/src/core/server/remote_provider_commands.rs b/src-tauri/src/core/server/remote_provider_commands.rsindex c3a24e789..d2722930d 100644--- a/src-tauri/src/core/server/remote_provider_commands.rs+++ b/src-tauri/src/core/server/remote_provider_commands.rs@@ -63,7 +63,6 @@ pub async fn unregister_provider_config(log::info!("Unregistered provider config: {provider}");Ok(())} else {- log::warn!("Provider config not found: {provider}");Ok(())}}