Akarshan Biswas 11b3a60675
fix: refactor, fix and move gguf support utilities to backend (#6584)
* feat: move estimateKVCacheSize to BE

* feat: Migrate model planning to backend

This commit migrates the model load planning logic from the frontend to the Tauri backend. This refactors the `planModelLoad` and `isModelSupported` methods into the `tauri-plugin-llamacpp` plugin, making them directly callable from the Rust core.

The model planning now incorporates a more robust and accurate memory estimation, considering both VRAM and system RAM, and introduces a `batch_size` parameter to the model plan.

**Key changes:**

- **Moved `planModelLoad` to `tauri-plugin-llamacpp`:** The core logic for determining GPU layers, context length, and memory offloading is now in Rust for better performance and accuracy.
- **Moved `isModelSupported` to `tauri-plugin-llamacpp`:** The model support check is also now handled by the backend.
- **Removed `getChatClient` from `AIEngine`:** This optional method was not implemented and has been removed from the abstract class.
- **Improved KV Cache estimation:** The `estimate_kv_cache_internal` function in Rust now accounts for `attention.key_length` and `attention.value_length` if available, and considers sliding window attention for more precise estimates.
- **Introduced `batch_size` in ModelPlan:** The model plan now includes a `batch_size` property, which will be automatically adjusted based on the determined `ModelMode` (e.g., lower for CPU/Hybrid modes).
- **Updated `llamacpp-extension`:** The frontend extension now calls the new Tauri commands for model planning and support checks.
- **Removed `batch_size` from `llamacpp-extension/settings.json`:** The batch size is now dynamically determined by the planning logic and will be set as a model setting directly.
- **Updated `ModelSetting` and `useModelProvider` hooks:** These now handle the new `batch_size` property in model settings.
- **Added new Tauri commands and permissions:** `get_model_size`, `is_model_supported`, and `plan_model_load` are new commands with corresponding permissions.
- **Consolidated `ModelSupportStatus` and `KVCacheEstimate`:** These types are now defined in `src/tauri/plugins/tauri-plugin-llamacpp/src/gguf/types.rs`.

This refactoring centralizes critical model resource management logic, improving consistency and maintainability, and lays the groundwork for more sophisticated model loading strategies.

* feat: refine model planner to handle more memory scenarios

This commit introduces several improvements to the `plan_model_load` function, enhancing its ability to determine a suitable model loading strategy based on system memory constraints. Specifically, it includes:

-   **VRAM calculation improvements:**  Corrects the calculation of total VRAM by iterating over GPUs and multiplying by 1024*1024, improving accuracy.
-   **Hybrid plan optimization:**  Implements a more robust hybrid plan strategy, iterating through GPU layer configurations to find the highest possible GPU usage while remaining within VRAM limits.
-   **Minimum context length enforcement:** Enforces a minimum context length for the model, ensuring that the model can be loaded and used effectively.
-   **Fallback to CPU mode:** If a hybrid plan isn't feasible, it now correctly falls back to a CPU-only mode.
-   **Improved logging:** Enhanced logging to provide more detailed information about the memory planning process, including VRAM, RAM, and GPU layers.
-   **Batch size adjustment:** Updated batch size based on the selected mode, ensuring efficient utilization of available resources.
-   **Error handling and edge cases:**  Improved error handling and edge case management to prevent unexpected failures.
-   **Constants:** Added constants for easier maintenance and understanding.
-   **Power-of-2 adjustment:** Added power of 2 adjustment for max context length to ensure correct sizing for the LLM.

These changes improve the reliability and robustness of the model planning process, allowing it to handle a wider range of hardware configurations and model sizes.

* Add log for raw GPU info from tauri-plugin-hardware

* chore: update linux runner for tauri build

* feat: Improve GPU memory calculation for unified memory

This commit improves the logic for calculating usable VRAM, particularly for systems with **unified memory** like Apple Silicon. Previously, the application would report 0 total VRAM if no dedicated GPUs were found, leading to incorrect calculations and failed model loads.

This change modifies the VRAM calculation to fall back to the total system RAM if no discrete GPUs are detected. This is a common and correct approach for unified memory architectures, where the CPU and GPU share the same memory pool.

Additionally, this commit refactors the logic for calculating usable VRAM and RAM to prevent potential underflow by checking if the total memory is greater than the reserved bytes before subtracting. This ensures the calculation remains safe and correct.

* chore: fix update migration version

* fix: enable unified memory support on model support indicator

* Use total_system_memory in bytes

---------

Co-authored-by: Minh141120 <minh.itptit@gmail.com>
Co-authored-by: Faisal Amir <urmauur@gmail.com>
2025-09-25 12:17:57 +05:30

142 lines
4.6 KiB
Rust

use super::types::GgufMetadata;
use super::utils::{estimate_kv_cache_internal, read_gguf_metadata_internal};
use crate::gguf::types::{KVCacheError, KVCacheEstimate, ModelSupportStatus};
use std::collections::HashMap;
use std::fs;
use tauri::Runtime;
use tauri_plugin_hardware::get_system_info;
/// Read GGUF metadata from a model file
#[tauri::command]
pub async fn read_gguf_metadata(path: String) -> Result<GgufMetadata, String> {
return read_gguf_metadata_internal(path).await;
}
#[tauri::command]
pub async fn estimate_kv_cache_size(
meta: HashMap<String, String>,
ctx_size: Option<u64>,
) -> Result<KVCacheEstimate, KVCacheError> {
estimate_kv_cache_internal(meta, ctx_size).await
}
#[tauri::command]
pub async fn get_model_size(path: String) -> Result<u64, String> {
if path.starts_with("https://") {
// Handle remote URL
let client = reqwest::Client::new();
let response = client
.head(&path)
.send()
.await
.map_err(|e| format!("Failed to fetch HEAD request: {}", e))?;
if let Some(content_length) = response.headers().get("content-length") {
let content_length_str = content_length
.to_str()
.map_err(|e| format!("Invalid content-length header: {}", e))?;
content_length_str
.parse::<u64>()
.map_err(|e| format!("Failed to parse content-length: {}", e))
} else {
Ok(0)
}
} else {
// Handle local file using standard fs
let metadata =
fs::metadata(&path).map_err(|e| format!("Failed to get file metadata: {}", e))?;
Ok(metadata.len())
}
}
#[tauri::command]
pub async fn is_model_supported<R: Runtime>(
path: String,
ctx_size: Option<u32>,
app_handle: tauri::AppHandle<R>,
) -> Result<ModelSupportStatus, String> {
// Get model size
let model_size = get_model_size(path.clone()).await?;
// Get system info
let system_info = get_system_info(app_handle.clone());
log::info!("modelSize: {}", model_size);
// Read GGUF metadata
let gguf = read_gguf_metadata(path.clone()).await?;
// Calculate KV cache size
let kv_cache_size = if let Some(ctx_size) = ctx_size {
log::info!("Using ctx_size: {}", ctx_size);
estimate_kv_cache_internal(gguf.metadata, Some(ctx_size as u64))
.await
.map_err(|e| e.to_string())?
.size
} else {
estimate_kv_cache_internal(gguf.metadata, None)
.await
.map_err(|e| e.to_string())?
.size
};
// Total memory consumption = model weights + kvcache
let total_required = model_size + kv_cache_size;
log::info!(
"isModelSupported: Total memory requirement: {} for {}; Got kvCacheSize: {} from BE",
total_required,
path,
kv_cache_size
);
const RESERVE_BYTES: u64 = 2288490189;
let total_system_memory = system_info.total_memory * 1024 * 1024;
// Calculate total VRAM from all GPUs
let total_vram: u64 = if system_info.gpus.is_empty() {
// On macOS with unified memory, GPU info may be empty
// Use total RAM as VRAM since memory is shared
log::info!("No GPUs detected (likely unified memory system), using total RAM as VRAM");
total_system_memory
} else {
system_info
.gpus
.iter()
.map(|g| g.total_memory * 1024 * 1024)
.sum::<u64>()
};
log::info!("Total VRAM reported/calculated (in bytes): {}", &total_vram);
let usable_vram = if total_vram > RESERVE_BYTES {
total_vram - RESERVE_BYTES
} else {
0
};
let usable_total_memory = if total_system_memory > RESERVE_BYTES {
(total_system_memory - RESERVE_BYTES) + usable_vram
} else {
0
};
log::info!("System RAM: {} bytes", &total_system_memory);
log::info!("Total VRAM: {} bytes", &total_vram);
log::info!("Usable total memory: {} bytes", &usable_total_memory);
log::info!("Usable VRAM: {} bytes", &usable_vram);
log::info!("Required: {} bytes", &total_required);
// Check if model fits in total memory at all (this is the hard limit)
if total_required > usable_total_memory {
return Ok(ModelSupportStatus::Red); // Truly impossible to run
}
// Check if everything fits in VRAM (ideal case)
if total_required <= usable_vram {
return Ok(ModelSupportStatus::Green);
}
// If we get here, it means:
// - Total requirement fits in combined memory
// - But doesn't fit entirely in VRAM
// This is the CPU-GPU hybrid scenario
Ok(ModelSupportStatus::Yellow)
}