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.

refactor: remove model planner since now use auto fit setting

Louisd4614a232306
diff --git a/extensions/llamacpp-extension/package.json b/extensions/llamacpp-extension/package.json
index b6b7b01cd..5e976bd77 100644
--- a/extensions/llamacpp-extension/package.json
+++ b/extensions/llamacpp-extension/package.json
@@ -1,7 +1,7 @@
{
"name": "@janhq/llamacpp-extension",
"productName": "llama.cpp Inference Engine",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "This extension enables llama.cpp chat completion API calls",
"main": "dist/index.js",
"module": "dist/module.js",
diff --git a/extensions/llamacpp-extension/settings.json b/extensions/llamacpp-extension/settings.json
index 2a7408500..fcb24e464 100644
--- a/extensions/llamacpp-extension/settings.json
+++ b/extensions/llamacpp-extension/settings.json
@@ -52,14 +52,9 @@
"key": "fit",
"title": "Fit (auto-adjust to device memory)",
"description": "Whether to adjust unset arguments to fit in device memory ('on' or 'off'). (env: LLAMA_ARG_FIT)",
- "controllerType": "dropdown",
+ "controllerType": "checkbox",
"controllerProps": {
- "value": "on",
- "options": [
- { "value": "on", "name": "On" },
- { "value": "off", "name": "Off" }
- ],
- "recommended": "on"
+ "value": true
}
},
{
@@ -86,21 +81,6 @@
"textAlign": "right"
}
},
- {
- "key": "memory_util",
- "title": "Smart Memory utilization",
- "description": "Smart memory utilization mode for running local GGUF models",
- "controllerType": "dropdown",
- "controllerProps": {
- "value": "high",
- "options": [
- { "value": "high", "name": "High" },
- { "value": "medium", "name": "Medium" },
- { "value": "low", "name": "Low" }
- ],
- "recommended": "high"
- }
- },
{
"key": "threads",
"title": "Threads",
diff --git a/extensions/llamacpp-extension/src/index.ts b/extensions/llamacpp-extension/src/index.ts
index 12482806f..87fa9eb79 100644
--- a/extensions/llamacpp-extension/src/index.ts
+++ b/extensions/llamacpp-extension/src/index.ts
@@ -46,10 +46,8 @@ import {
readGgufMetadata,
getModelSize,
isModelSupported,
- planModelLoadInternal,
unloadLlamaModel,
LlamacppConfig,
- ModelPlan,
DownloadItem,
ModelConfig,
EmbeddingResponse,
@@ -112,7 +110,6 @@ export default class llamacpp_extension extends AIEngine {
autoUnload: boolean = true
timeout: number = 600
llamacpp_env: string = ''
- memoryMode: string = ''
readonly providerId: string = 'llamacpp'
private config: LlamacppConfig
@@ -145,7 +142,6 @@ export default class llamacpp_extension extends AIEngine {
this.autoUnload = this.config.auto_unload
this.timeout = this.config.timeout
this.llamacpp_env = this.config.llamacpp_env
- this.memoryMode = this.config.memory_util || 'high'
// This sets the base directory where model files for this provider are stored.
this.getProviderPath()
@@ -722,8 +718,6 @@ export default class llamacpp_extension extends AIEngine {
this.autoUnload = value as boolean
} else if (key === 'llamacpp_env') {
this.llamacpp_env = value as string
- } else if (key === 'memory_util') {
- this.memoryMode = value as string
} else if (key === 'timeout') {
this.timeout = value as number
}
@@ -1538,6 +1532,9 @@ export default class llamacpp_extension extends AIEngine {
mmprojPath = await joinPath([janDataFolderPath, modelConfig.mmproj_path])
}
+ // Migrate old env vars
+ if(typeof cfg.fit === 'string') cfg.fit = true
+
logger.info(
'Calling Tauri command load_llama_model with config:',
JSON.stringify(cfg)
@@ -2067,85 +2064,6 @@ export default class llamacpp_extension extends AIEngine {
'tokenizer.chat_template'
]?.includes('tools')
}
- /**
- * Get total system memory including both VRAM and RAM
- */
- private async getTotalSystemMemory(): Promise<SystemMemory> {
- const devices = await this.getDevices()
- let totalVRAM = 0
-
- if (devices.length > 0) {
- // Sum total VRAM across all GPUs
- totalVRAM = devices
- .map((d) => d.mem * 1024 * 1024)
- .reduce((a, b) => a + b, 0)
- }
-
- // Get system RAM
- const sys = await getSystemUsage()
- const totalRAM = sys.used_memory * 1024 * 1024
-
- const totalMemory = totalVRAM + totalRAM
-
- logger.info(
- `Total VRAM: ${totalVRAM} bytes, Total RAM: ${totalRAM} bytes, Total Memory: ${totalMemory} bytes`
- )
-
- return {
- totalVRAM,
- totalRAM,
- totalMemory,
- }
- }
-
- private async getLayerSize(
- path: string,
- meta: Record<string, string>
- ): Promise<{ layerSize: number; totalLayers: number }> {
- const modelSize = await getModelSize(path)
- const arch = meta['general.architecture']
- const totalLayers = Number(meta[`${arch}.block_count`]) + 2 // 1 for lm_head layer and 1 for embedding layer
- if (!totalLayers) throw new Error('Invalid metadata: block_count not found')
- return { layerSize: modelSize / totalLayers, totalLayers }
- }
-
- private isAbsolutePath(p: string): boolean {
- // Normalize back‑slashes to forward‑slashes first.
- const norm = p.replace(/\\/g, '/')
- return (
- norm.startsWith('/') || // POSIX absolute
- /^[a-zA-Z]:/.test(norm) || // Drive‑letter Windows (C: or D:)
- /^\/\/[^/]+/.test(norm) // UNC path //server/share
- )
- }
- /*
- * if (!this.isAbsolutePath(path))
- path = await joinPath([await getJanDataFolderPath(), path])
- if (mmprojPath && !this.isAbsolutePath(mmprojPath))
- mmprojPath = await joinPath([await getJanDataFolderPath(), path])
- */
- async planModelLoad(
- path: string,
- mmprojPath?: string,
- requestedCtx?: number
- ): Promise<ModelPlan> {
- if (!this.isAbsolutePath(path)) {
- path = await joinPath([await getJanDataFolderPath(), path])
- }
- if (mmprojPath && !this.isAbsolutePath(mmprojPath))
- mmprojPath = await joinPath([await getJanDataFolderPath(), path])
- try {
- const result = await planModelLoadInternal(
- path,
- this.memoryMode,
- mmprojPath,
- requestedCtx
- )
- return result
- } catch (e) {
- throw new Error(String(e))
- }
- }
/**
* Check the support status of a model by its path (local/remote)
diff --git a/extensions/llamacpp-extension/tsconfig.json b/extensions/llamacpp-extension/tsconfig.json
index 34d31fe4a..0f1145508 100644
--- a/extensions/llamacpp-extension/tsconfig.json
+++ b/extensions/llamacpp-extension/tsconfig.json
@@ -2,7 +2,6 @@
"compilerOptions": {
"target": "es2018",
"module": "ES6",
- "moduleResolution": "node",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 30433d7cb..b9e0027fc 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -17,7 +17,6 @@ const COMMANDS: &[&str] = &[
"estimate_kv_cache_size",
"get_model_size",
"is_model_supported",
- "plan_model_load",
// backend management
"map_old_backend_to_new",
"get_local_installed_backends",
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
index 7e771ad04..5848e1e73 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/index.ts
@@ -39,10 +39,9 @@ export function normalizeLlamacppConfig(config: any): LlamacppConfig {
timeout: asNumber(config.timeout, 600),
llamacpp_env: asString(config.llamacpp_env),
- fit: asString(config.fit),
+ fit: asBool(config.fit),
fit_target: asString(config.fit_target),
fit_ctx: asString(config.fit_ctx),
- memory_util: asString(config.memory_util),
chat_template: asString(config.chat_template),
n_gpu_layers: asNumber(config.n_gpu_layers),
@@ -191,27 +190,6 @@ export async function isModelSupported(
})
}
-export async function planModelLoadInternal(
- path: string,
- memoryMode: string,
- mmprojPath?: string,
- requestedContext?: number
-): Promise<{
- gpuLayers: number
- maxContextLength: number
- noOffloadKVCache: boolean
- offloadMmproj?: boolean
- batchSize: number
- mode: 'GPU' | 'Hybrid' | 'CPU' | 'Unsupported'
-}> {
- return await invoke('plugin:llamacpp|plan_model_load', {
- path,
- memoryMode,
- mmprojPath,
- requestedContext,
- })
-}
-
// Cleanup commands
export async function cleanupLlamaProcesses(): Promise<void> {
return await invoke('plugin:llamacpp|cleanup_llama_processes')
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 ca4b35e44..e4f4da082 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/guest-js/types.ts
@@ -33,10 +33,9 @@ export type LlamacppConfig = {
auto_unload: boolean
timeout: number
llamacpp_env: string
- fit: string
+ fit: boolean
fit_target: string
fit_ctx: string
- memory_util: string
chat_template: string
n_gpu_layers: number
offload_mmproj: boolean
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs
index de6d3b3e5..0ccc83ad9 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/args.rs
@@ -7,10 +7,9 @@ pub struct LlamacppConfig {
pub auto_unload: bool,
pub timeout: i32,
pub llamacpp_env: String,
- pub fit: String,
+ pub fit: bool,
pub fit_target: String,
pub fit_ctx: String,
- pub memory_util: String, // TODO: Remove after fit implementation
pub chat_template: String,
pub n_gpu_layers: i32,
pub offload_mmproj: bool,
@@ -262,7 +261,7 @@ impl ArgumentBuilder {
}
fn add_text_generation_args(&mut self) {
- if self.config.ctx_size > 0 && self.config.ctx_size != 8192 {
+ if self.config.ctx_size > 0 && self.config.ctx_size != 8192 && !self.config.fit {
// set only when default values change
self.args.push("--ctx-size".to_string());
self.args.push(self.config.ctx_size.to_string());
@@ -320,14 +319,14 @@ impl ArgumentBuilder {
fn add_fit_settings(&mut self) {
// Handle fit on/off
- if self.config.fit == "off" {
+ if !self.config.fit {
self.args.push("--fit".to_string());
self.args.push("off".to_string());
- } else if self.config.fit == "on" {
+ } else if self.config.fit {
self.args.push("--fit".to_string());
self.args.push("on".to_string());
}
- if self.config.fit == "on" {
+ if self.config.fit {
if !self.config.fit_ctx.is_empty() && self.config.fit_ctx != "4096" {
self.args.push("--fit-ctx".to_string());
self.args.push(self.config.fit_ctx.clone());
@@ -352,10 +351,9 @@ mod tests {
auto_unload: false,
timeout: 120,
llamacpp_env: String::new(),
- fit: String::new(),
+ fit: false,
fit_ctx: String::new(),
fit_target: String::new(),
- memory_util: String::new(),
chat_template: String::new(),
n_gpu_layers: 100,
offload_mmproj: true,
@@ -910,7 +908,7 @@ mod tests {
#[test]
fn test_fit_off() {
let mut config = default_config();
- config.fit = "off".to_string();
+ config.fit = false;
let builder = ArgumentBuilder::new(config, false).unwrap();
let args = builder.build("test", "/path", 8080, None);
@@ -923,7 +921,7 @@ mod tests {
#[test]
fn test_fit_on_with_defaults() {
let mut config = default_config();
- config.fit = "on".to_string();
+ config.fit = true;
config.fit_ctx = "4096".to_string();
config.fit_target = "1024".to_string();
@@ -938,7 +936,7 @@ mod tests {
#[test]
fn test_fit_on_with_custom_values() {
let mut config = default_config();
- config.fit = "on".to_string();
+ config.fit = true;
config.fit_ctx = "8192".to_string();
config.fit_target = "2048".to_string();
@@ -954,7 +952,7 @@ mod tests {
fn test_fit_not_added_for_ik_backend() {
let mut config = default_config();
config.version_backend = "v1.0/ik-backend".to_string();
- config.fit = "on".to_string();
+ config.fit = true;
let builder = ArgumentBuilder::new(config, false).unwrap();
let args = builder.build("test", "/path", 8080, None);
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/mod.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/mod.rs
index 935b17b83..a8fc6a15a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/mod.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/mod.rs
@@ -2,4 +2,3 @@ pub mod commands;
pub mod helpers;
pub mod types;
pub mod utils;
-pub mod model_planner;
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/model_planner.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/model_planner.rs
deleted file mode 100644
index aad9dfe16..000000000
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/gguf/model_planner.rs
+++ /dev/null
@@ -1,316 +0,0 @@
-use crate::gguf::commands::get_model_size;
-use crate::gguf::utils::estimate_kv_cache_internal;
-use crate::gguf::utils::read_gguf_metadata_internal;
-use serde::{Deserialize, Serialize};
-use std::collections::HashMap;
-use tauri_plugin_hardware::get_system_info;
-
-#[derive(Serialize, Deserialize, Clone, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct ModelPlan {
- pub gpu_layers: u64,
- pub max_context_length: u64,
- pub no_offload_kv_cache: bool,
- pub offload_mmproj: bool,
- pub batch_size: u64,
- pub mode: ModelMode,
-}
-
-#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
-#[serde(rename_all = "UPPERCASE")]
-pub enum ModelMode {
- GPU,
- Hybrid,
- CPU,
- Unsupported,
-}
-
-#[tauri::command]
-pub async fn plan_model_load(
- path: String,
- memory_mode: String,
- mmproj_path: Option<String>,
- requested_ctx: Option<u64>,
-) -> Result<ModelPlan, String> {
- let model_size = get_model_size(path.clone()).await?;
- let sys_info = get_system_info();
- let gguf = read_gguf_metadata_internal(path.clone()).await?;
-
- let mut mmproj_size: u64 = 0;
- if let Some(ref mmproj) = mmproj_path {
- mmproj_size = get_model_size(mmproj.clone()).await?;
- }
-
- let arch = gguf
- .metadata
- .get("general.architecture")
- .ok_or("Missing architecture")?;
- let repeating_layers: u64 = gguf
- .metadata
- .get(&format!("{arch}.block_count"))
- .ok_or("Missing block_count")?
- .parse()
- .map_err(|_| "Invalid block_count")?;
- let total_layers = repeating_layers + 1;
- let layer_size = model_size / total_layers;
-
- let kv_cache = estimate_kv_cache_internal(gguf.metadata.clone(), None)
- .await
- .map_err(|e| e.to_string())?;
- let kv_cache_per_token = kv_cache.per_token_size;
-
- if model_size == 0 || layer_size == 0 || kv_cache_per_token == 0 {
- return Err("Invalid model/layer/cache sizes".into());
- }
-
- const RESERVE_BYTES: u64 = 2288490189;
- const MIN_CONTEXT_LENGTH: u64 = 2048;
-
- let model_max_ctx: u64 = gguf
- .metadata
- .get(&format!("{arch}.context_length"))
- .and_then(|s| s.parse().ok())
- .unwrap_or(8192);
-
- let memory_percentages = HashMap::from([("high", 0.7), ("medium", 0.5), ("low", 0.4)]);
-
- let multiplier = *memory_percentages
- .get(memory_mode.as_str())
- .ok_or("Invalid memory mode")?;
-
- log::info!("Got GPUs:\n{:?}", &sys_info.gpus);
-
- let total_ram: u64 = match sys_info.gpus.is_empty() {
- // Consider RAM as 0 for unified memory
- true => 0,
- false => sys_info.total_memory * 1024 * 1024,
- };
-
- // Calculate total VRAM from all GPUs
- let total_vram: u64 = match sys_info.gpus.is_empty() {
- true => {
- log::info!("No GPUs detected (likely unified memory system), using total RAM as VRAM");
- sys_info.total_memory * 1024 * 1024
- }
- false => sys_info
- .gpus
- .iter()
- .map(|g| g.total_memory * 1024 * 1024)
- .sum::<u64>(),
- };
- log::info!("Total RAM reported/calculated (in bytes): {}", &total_ram);
- log::info!("Total VRAM reported/calculated (in bytes): {}", &total_vram);
- let usable_vram: u64 = if total_vram > RESERVE_BYTES {
- (((total_vram - RESERVE_BYTES) as f64) * multiplier) as u64
- } else {
- 0
- };
- log::info!("Usable vram calculated: {}", &usable_vram);
-
- let usable_ram: u64 = if total_ram > RESERVE_BYTES {
- (((total_ram - RESERVE_BYTES) as f64) * multiplier).max(0.0) as u64
- } else {
- 0
- };
- log::info!("Usable ram calculated (in bytes): {}", &usable_ram);
-
- let mut gpu_layers = 0;
- let mut max_ctx_len = 0;
- let mut no_offload_kv_cache = false;
- let mut mode = ModelMode::Unsupported;
- let mut offload_mmproj = false;
- let mut batch_size = 2048;
-
- let total_available_mem = usable_vram.saturating_add(usable_ram);
- if model_size + mmproj_size > total_available_mem {
- log::info!("Model not supported in this system!");
- return Ok(ModelPlan {
- gpu_layers: 0,
- max_context_length: 0,
- no_offload_kv_cache: true,
- batch_size: 64,
- mode: ModelMode::Unsupported,
- offload_mmproj: false,
- });
- }
- if mmproj_size > 0 {
- offload_mmproj = true;
- }
-
- let kv_min_size = estimate_kv_cache_internal(gguf.metadata.clone(), Some(MIN_CONTEXT_LENGTH))
- .await
- .map_err(|e| e.to_string())?
- .size;
-
- if model_size + kv_min_size + mmproj_size <= usable_vram {
- log::info!("Planning mode: Full GPU offload is possible.");
- mode = ModelMode::GPU;
- gpu_layers = total_layers;
- let vram_left_for_ctx = usable_vram.saturating_sub(model_size);
- let max_ctx_by_vram = (vram_left_for_ctx / kv_cache_per_token) as u64;
- let requested_target = requested_ctx.unwrap_or(model_max_ctx).min(model_max_ctx);
- max_ctx_len = requested_target.min(max_ctx_by_vram);
- no_offload_kv_cache = false;
- offload_mmproj = true;
- } else {
- let mut found_plan = false;
-
- log::info!("Attempting VRAM-Maximized Hybrid plan (KV cache in VRAM only).");
- for candidate_gpu_layers in (0..=total_layers).rev() {
- let vram_used_by_layers = candidate_gpu_layers.saturating_mul(layer_size);
- if vram_used_by_layers > usable_vram {
- continue;
- }
-
- let ram_used_by_cpu_layers =
- (total_layers.saturating_sub(candidate_gpu_layers)).saturating_mul(layer_size);
- let ram_used_by_mmproj = if offload_mmproj { 0 } else { mmproj_size };
- let required_ram_for_model = ram_used_by_cpu_layers.saturating_add(ram_used_by_mmproj);
-
- if required_ram_for_model > usable_ram {
- continue;
- }
-
- let vram_left_for_kv = usable_vram.saturating_sub(vram_used_by_layers);
- let ctx_in_vram_only = (vram_left_for_kv / kv_cache_per_token) as u64;
-
- if ctx_in_vram_only >= MIN_CONTEXT_LENGTH {
- log::info!(
- "Found VRAM-Maximized Hybrid plan with {} GPU layers.",
- candidate_gpu_layers
- );
- mode = ModelMode::Hybrid;
- gpu_layers = candidate_gpu_layers;
- let requested_target = requested_ctx.unwrap_or(model_max_ctx).min(model_max_ctx);
- max_ctx_len = requested_target.min(ctx_in_vram_only);
- no_offload_kv_cache = false;
- found_plan = true;
- break;
- }
- }
-
- if !found_plan {
- log::info!("VRAM-Maximized plan not feasible. Falling back to Standard Hybrid (KV cache in VRAM+RAM).");
- for candidate_gpu_layers in (0..=total_layers).rev() {
- let vram_used_by_layers = candidate_gpu_layers.saturating_mul(layer_size);
- if vram_used_by_layers > usable_vram {
- continue;
- }
- let vram_left_for_kv = usable_vram.saturating_sub(vram_used_by_layers);
- let kv_in_vram = (vram_left_for_kv / kv_cache_per_token) as u64;
-
- let ram_used_by_cpu_layers =
- (total_layers.saturating_sub(candidate_gpu_layers)).saturating_mul(layer_size);
- let ram_used_by_mmproj = if offload_mmproj { 0 } else { mmproj_size };
- let required_ram_for_model =
- ram_used_by_cpu_layers.saturating_add(ram_used_by_mmproj);
-
- if required_ram_for_model > usable_ram {
- continue;
- }
-
- let available_ram_for_kv = usable_ram.saturating_sub(required_ram_for_model);
- let kv_in_ram = (available_ram_for_kv / kv_cache_per_token) as u64;
-
- let total_kv_tokens = kv_in_vram.saturating_add(kv_in_ram);
-
- if total_kv_tokens >= MIN_CONTEXT_LENGTH {
- log::info!(
- "Found Standard Hybrid plan with {} GPU layers.",
- candidate_gpu_layers
- );
- mode = if candidate_gpu_layers > 0 {
- ModelMode::Hybrid
- } else {
- ModelMode::CPU
- };
- gpu_layers = candidate_gpu_layers;
- let requested_target =
- requested_ctx.unwrap_or(model_max_ctx).min(model_max_ctx);
- let max_possible_ctx = total_kv_tokens.min(model_max_ctx);
- max_ctx_len = requested_target.min(max_possible_ctx);
- no_offload_kv_cache = kv_in_ram > 0 && kv_in_vram == 0;
- found_plan = true;
- break;
- }
- }
- }
-
- if !found_plan {
- log::info!("No hybrid plan found. Attempting CPU-only plan.");
- if model_size + mmproj_size <= usable_ram {
- let available_ram_for_kv = usable_ram.saturating_sub(model_size + mmproj_size);
- let kv_tokens = (available_ram_for_kv / kv_cache_per_token) as u64;
- if kv_tokens >= MIN_CONTEXT_LENGTH {
- mode = ModelMode::CPU;
- gpu_layers = 0;
- max_ctx_len = kv_tokens
- .min(requested_ctx.unwrap_or(model_max_ctx))
- .min(model_max_ctx);
- no_offload_kv_cache = true;
- offload_mmproj = false;
- }
- }
- }
- }
-
- if let Some(req) = requested_ctx {
- if req > 0 {
- max_ctx_len = max_ctx_len.min(req);
- }
- }
- max_ctx_len = max_ctx_len.min(model_max_ctx);
-
- if max_ctx_len > 0 {
- log::info!("Max context before power-of-2 adjustment: {}", max_ctx_len);
- max_ctx_len = 1u64 << (63 - max_ctx_len.leading_zeros());
- log::info!("Adjusted max context to power of 2: {}", max_ctx_len);
- }
-
- if mode == ModelMode::Unsupported {
- if max_ctx_len >= MIN_CONTEXT_LENGTH {
- // do nothing, plan is viable but wasn't assigned a mode
- } else {
- gpu_layers = 0;
- max_ctx_len = 0;
- offload_mmproj = false;
- }
- } else if max_ctx_len < MIN_CONTEXT_LENGTH {
- log::info!(
- "Final context length {} is less than minimum required {}. Marking as unsupported.",
- max_ctx_len,
- MIN_CONTEXT_LENGTH
- );
- mode = ModelMode::Unsupported;
- gpu_layers = 0;
- max_ctx_len = 0;
- offload_mmproj = false;
- }
-
- if mode == ModelMode::Hybrid {
- batch_size = 256;
- } else if mode == ModelMode::CPU || no_offload_kv_cache || mode == ModelMode::Unsupported {
- batch_size = 64;
- }
-
- if max_ctx_len > 0 {
- batch_size = batch_size.min(max_ctx_len);
- } else {
- batch_size = 64;
- }
-
- if mode == ModelMode::CPU || no_offload_kv_cache {
- offload_mmproj = false;
- }
-
- log::info!("Planned model load params: GPU Layers: {}, max_ctx_len: {}, kv_cache offload: {}, offload mmproj: {}, batch_size: {}",
- gpu_layers, max_ctx_len, !no_offload_kv_cache, offload_mmproj, batch_size);
- Ok(ModelPlan {
- gpu_layers,
- max_context_length: max_ctx_len,
- no_offload_kv_cache,
- offload_mmproj,
- batch_size,
- mode,
- })
-}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index ce9866cf0..8242591a3 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -38,7 +38,6 @@ pub fn init<R: Runtime>() -> TauriPlugin<R> {
gguf::commands::estimate_kv_cache_size,
gguf::commands::get_model_size,
gguf::commands::is_model_supported,
- gguf::model_planner::plan_model_load,
// Backend management
backend::map_old_backend_to_new,
backend::get_local_installed_backends,
diff --git a/web-app/src/containers/ModelSetting.tsx b/web-app/src/containers/ModelSetting.tsx
index 7a02ebecd..5b93b8dba 100644
--- a/web-app/src/containers/ModelSetting.tsx
+++ b/web-app/src/containers/ModelSetting.tsx
@@ -1,6 +1,5 @@
-import { IconSettings, IconLoader } from '@tabler/icons-react'
+import { IconSettings } from '@tabler/icons-react'
import debounce from 'lodash.debounce'
-import { useState } from 'react'
import {
Sheet,
@@ -32,8 +31,6 @@ export function ModelSetting({
const serviceHub = useServiceHub()
const setActiveModels = useAppState((state) => state.setActiveModels)
- const [isPlanning, setIsPlanning] = useState(false)
-
// Create a debounced version of stopModel that waits 500ms after the last call
const debouncedStopModel = debounce((modelId: string) => {
serviceHub
@@ -48,157 +45,6 @@ export function ModelSetting({
})
}, 500)
- const handlePlanModelLoad = async () => {
- if (provider.provider !== 'llamacpp') {
- console.warn('planModelLoad is only available for llamacpp provider')
- return
- }
- setIsPlanning(true)
- try {
- // Read the model config to get the actual model path and mmproj path
- const modelConfig = await serviceHub.app().readYaml<{
- model_path: string
- mmproj_path?: string
- }>(`llamacpp/models/${model.id}/model.yml`)
-
- if (modelConfig && modelConfig.model_path) {
- const result = await serviceHub
- .models()
- .planModelLoad(modelConfig.model_path, modelConfig.mmproj_path)
-
- // Apply the recommended settings to the model sequentially to avoid race conditions
- const settingsToUpdate: Array<{
- key: string
- value: number | boolean
- }> = []
-
- if (model.settings?.ngl && result.gpuLayers !== undefined) {
- settingsToUpdate.push({ key: 'ngl', value: result.gpuLayers })
- }
-
- if (model.settings?.ctx_len && result.maxContextLength !== undefined) {
- settingsToUpdate.push({
- key: 'ctx_len',
- value: result.maxContextLength,
- })
- }
-
- if (
- model.settings?.no_kv_offload &&
- result.noOffloadKVCache !== undefined
- ) {
- settingsToUpdate.push({
- key: 'no_kv_offload',
- value: result.noOffloadKVCache,
- })
- }
- if (
- model.settings?.no_kv_offload &&
- result.noOffloadKVCache !== undefined
- ) {
- settingsToUpdate.push({
- key: 'no_kv_offload',
- value: result.noOffloadKVCache,
- })
- }
-
- if (
- model.settings?.mmproj_offload &&
- result.offloadMmproj !== undefined
- ) {
- settingsToUpdate.push({
- key: 'mmproj_offload',
- value: result.offloadMmproj,
- })
- }
-
- if (model.settings?.batch_size && result.batchSize !== undefined) {
- settingsToUpdate.push({
- key: 'batch_size',
- value: result.batchSize,
- })
- }
-
- // Apply all settings in a single update to avoid race conditions
- if (settingsToUpdate.length > 0) {
- handleMultipleSettingsChange(settingsToUpdate)
- }
- } else {
- console.warn('No model_path found in config for', model.id)
- }
- } catch (error) {
- console.error('Error calling planModelLoad:', error)
- } finally {
- setIsPlanning(false)
- }
- }
-
- const handleMultipleSettingsChange = (
- settingsToUpdate: Array<{ key: string; value: number | boolean }>
- ) => {
- if (!provider) return
-
- // Create a copy of the model with ALL updated settings at once
- let updatedModel = { ...model }
-
- settingsToUpdate.forEach(({ key, value }) => {
- const existingSetting = updatedModel.settings?.[key] as ProviderSetting
- updatedModel = {
- ...updatedModel,
- settings: {
- ...updatedModel.settings,
- [key]: {
- ...existingSetting,
- controller_props: {
- ...existingSetting?.controller_props,
- value: value,
- },
- } as ProviderSetting,
- },
- }
- })
-
- // Find the model index in the provider's models array
- const modelIndex = provider.models.findIndex((m) => m.id === model.id)
-
- if (modelIndex !== -1) {
- // Create a copy of the provider's models array
- const updatedModels = [...provider.models]
-
- // Update the specific model in the array
- updatedModels[modelIndex] = updatedModel as Model
-
- // Update the provider with the new models array
- updateProvider(provider.provider, {
- models: updatedModels,
- })
-
- // Check if any of the updated settings require a model restart
- const requiresRestart = settingsToUpdate.some(
- ({ key }) =>
- key === 'ctx_len' ||
- key === 'ngl' ||
- key === 'chat_template' ||
- key === 'offload_mmproj' ||
- key === 'batch_size' ||
- key === 'cpu_moe' ||
- key === 'n_cpu_moe'
- )
-
- if (requiresRestart) {
- // Check if model is running before stopping it
- serviceHub
- .models()
- .getActiveModels()
- .then((activeModels) => {
- if (activeModels.includes(model.id)) {
- debouncedStopModel(model.id)
- }
- })
- }
- }
- }
-
const handleSettingChange = (
key: string,
value: string | boolean | number
@@ -276,41 +122,6 @@ export function ModelSetting({
<SheetDescription className='text-xs leading-normal'>
{t('common:modelSettings.description')}
</SheetDescription>
-
- {/* Model Load Planning Section - Only show for llamacpp provider */}
- {provider.provider === 'llamacpp' && (
- <div className="pb-4 border-b mt-4">
- <div>
- <div>
- <div className="flex items-center gap-2 mb-1">
- <h3 className="font-medium">Optimize Settings</h3>
- <div className="text-xs bg-secondary border text-muted-foreground rounded-full py-0.5 px-2">
- <span>{t('mcp-servers:experimental')}</span>
- </div>
- </div>
- <p className="text-muted-foreground leading-normal text-xs mb-3">
- Analyze your system and model, then apply optimal loading
- settings automatically
- </p>
- </div>
- <Button
- onClick={handlePlanModelLoad}
- disabled={isPlanning}
- variant="default"
- className="w-full"
- >
- {isPlanning ? (
- <>
- <IconLoader size={16} className="mr-2 animate-spin" />
- Optimizing...
- </>
- ) : (
- <>Auto-Optimize Settings</>
- )}
- </Button>
- </div>
- </div>
- )}
</SheetHeader>
<div className="px-4 space-y-8 pb-4">
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index ef588eb58..6f2f67f6e 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -738,8 +738,6 @@ function ThreadDetail() {
const threadModel = useMemo(() => thread?.model, [thread])
- if (!threadModel) return null
-
return (
<div className="flex flex-col h-[calc(100dvh-(env(safe-area-inset-bottom)+env(safe-area-inset-top)))]">
<HeaderPage>
diff --git a/web-app/src/services/models/default.ts b/web-app/src/services/models/default.ts
index b774b7097..2b86c1dc8 100644
--- a/web-app/src/services/models/default.ts
+++ b/web-app/src/services/models/default.ts
@@ -22,7 +22,6 @@ import type {
HuggingFaceRepo,
CatalogModel,
ModelValidationResult,
- ModelPlan,
} from './types'
// TODO: Replace this with the actual provider later
@@ -562,60 +561,6 @@ export class DefaultModelsService implements ModelsService {
}
}
- async planModelLoad(
- modelPath: string,
- mmprojPath?: string,
- requestedCtx?: number
- ): Promise<ModelPlan> {
- try {
- const engine = this.getEngine('llamacpp') as AIEngine & {
- planModelLoad?: (
- path: string,
- mmprojPath?: string,
- requestedCtx?: number
- ) => Promise<ModelPlan>
- }
-
- if (engine && typeof engine.planModelLoad === 'function') {
- // Get the full absolute path to the model file
- const janDataFolderPath = await import('@janhq/core').then((core) =>
- core.getJanDataFolderPath()
- )
- const joinPath = await import('@janhq/core').then(
- (core) => core.joinPath
- )
- const fullModelPath = await joinPath([janDataFolderPath, modelPath])
- // mmprojPath is currently unused, but included for compatibility
- return await engine.planModelLoad(
- fullModelPath,
- mmprojPath,
- requestedCtx
- )
- }
-
- // Fallback if method is not available
- console.warn('planModelLoad method not available in llamacpp engine')
- return {
- gpuLayers: 100,
- maxContextLength: 2048,
- noOffloadKVCache: false,
- offloadMmproj: false,
- batchSize: 2048,
- mode: 'Unsupported',
- }
- } catch (error) {
- console.error(`Error planning model load for path ${modelPath}:`, error)
- return {
- gpuLayers: 100,
- maxContextLength: 2048,
- noOffloadKVCache: false,
- offloadMmproj: false,
- batchSize: 2048,
- mode: 'Unsupported',
- }
- }
- }
-
async getTokensCount(
modelId: string,
messages: ThreadMessage[]
diff --git a/web-app/src/services/models/types.ts b/web-app/src/services/models/types.ts
index 96fb23e1b..1a46e5bfd 100644
--- a/web-app/src/services/models/types.ts
+++ b/web-app/src/services/models/types.ts
@@ -91,14 +91,6 @@ export interface ModelValidationResult {
metadata?: GgufMetadata
}
-export interface ModelPlan {
- gpuLayers: number
- maxContextLength: number
- noOffloadKVCache: boolean
- offloadMmproj: boolean
- batchSize: number
- mode: 'GPU' | 'Hybrid' | 'CPU' | 'Unsupported'
-}
export type PreflightReason =
| 'AUTH_REQUIRED'
@@ -159,10 +151,5 @@ export interface ModelsService {
ctxSize?: number
): Promise<'RED' | 'YELLOW' | 'GREEN' | 'GREY'>
validateGgufFile(filePath: string): Promise<ModelValidationResult>
- planModelLoad(
- modelPath: string,
- mmprojPath?: string,
- requestedCtx?: number
- ): Promise<ModelPlan>
getTokensCount(modelId: string, messages: ThreadMessage[]): Promise<number>
}