Engine::start_info meldet das Startkommando mit Platzhaltern. Die Karten "Planung ändern" weichen einem Dialog je Modell. Lokal mit Attrappen im Browser gesehen, auf srv04 nicht geprüft. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GmHhg3osejhFSpUz472iQ1
709 lines
25 KiB
Rust
709 lines
25 KiB
Rust
//! Adapter für `llama-server` (llama.cpp) im Modus Managed.
|
|
//!
|
|
//! Gemessen auf srv04 (09.11.2026, Bonsai-1.7B): `llama-server` antwortet auf
|
|
//! `GET /health` zuerst mit 503, solange das Modell lädt, danach mit 200 und
|
|
//! `{"status":"ok"}`; er spricht OpenAI-HTTP (`/v1/models`,
|
|
//! `/v1/chat/completions`); `SIGTERM` beendet ihn sauber und gibt den
|
|
//! GPU-Speicher frei. Der VRAM-Verbrauch ist über `nvidia-smi` pro PID messbar.
|
|
|
|
use std::collections::{BTreeMap, HashMap};
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
use std::time::{Duration, Instant};
|
|
|
|
use async_trait::async_trait;
|
|
use serde::Deserialize;
|
|
use tokio::process::{Child, Command};
|
|
|
|
use crate::engine::Engine;
|
|
use crate::process::{PortPool, http_status, log_tail, rotate_log, sigterm};
|
|
use crate::types::{
|
|
AdapterError, Capabilities, DiscoveredArtifact, Endpoint, EngineInfo, Health, InstanceHandle,
|
|
Mode, ProfileSpec, Protocol, Result, StartInfo, Usage,
|
|
};
|
|
|
|
/// Konfiguration des llama.cpp-Adapters. Enthält keine Geheimnisse.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
|
#[serde(default, deny_unknown_fields)]
|
|
pub struct LlamaCppConfig {
|
|
/// Pfad zu `llama-server`.
|
|
pub binary: PathBuf,
|
|
/// Ordner, in denen `discover` nach `.gguf`-Dateien sucht.
|
|
pub model_roots: Vec<PathBuf>,
|
|
/// Port-Bereich für die Instanzen (nur `127.0.0.1`).
|
|
pub port_from: u16,
|
|
pub port_to: u16,
|
|
/// Wie lange das Laden eines Modells höchstens dauern darf.
|
|
pub ready_timeout_secs: u64,
|
|
/// Ordner für stdout und stderr der Instanzen.
|
|
pub log_dir: PathBuf,
|
|
/// Anzahl der Schichten auf der GPU (`-ngl`).
|
|
pub gpu_layers: i32,
|
|
/// Wie viele aufgehobene Logs älterer Läufe erhalten bleiben.
|
|
pub log_keep: usize,
|
|
/// Zusätzliche Argumente für jeden Start.
|
|
pub extra_args: Vec<String>,
|
|
/// Zusätzliche Umgebungsvariablen (keine Geheimnisse).
|
|
pub env: BTreeMap<String, String>,
|
|
/// Programm zur VRAM-Messung.
|
|
pub nvidia_smi: PathBuf,
|
|
}
|
|
|
|
impl Default for LlamaCppConfig {
|
|
fn default() -> Self {
|
|
Self {
|
|
binary: PathBuf::from("/srv/apps/llama.cpp/build/bin/llama-server"),
|
|
model_roots: vec![PathBuf::from("/srv/models/gguf")],
|
|
port_from: 18080,
|
|
port_to: 18180,
|
|
ready_timeout_secs: 120,
|
|
log_dir: PathBuf::from("data/logs"),
|
|
gpu_layers: 99,
|
|
log_keep: 10,
|
|
extra_args: Vec::new(),
|
|
env: BTreeMap::new(),
|
|
nvidia_smi: PathBuf::from("nvidia-smi"),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Kommandozeile und Umgebung für einen Start.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub(crate) struct CommandLine {
|
|
pub args: Vec<String>,
|
|
pub env: Vec<(String, String)>,
|
|
}
|
|
|
|
struct Managed {
|
|
child: Child,
|
|
port: u16,
|
|
}
|
|
|
|
pub struct LlamaCppEngine {
|
|
config: LlamaCppConfig,
|
|
ports: PortPool,
|
|
next_id: AtomicU64,
|
|
children: tokio::sync::Mutex<HashMap<u64, Managed>>,
|
|
}
|
|
|
|
impl LlamaCppEngine {
|
|
pub fn new(config: LlamaCppConfig) -> Self {
|
|
let ports = PortPool::new(config.port_from, config.port_to);
|
|
Self {
|
|
config,
|
|
ports,
|
|
next_id: AtomicU64::new(1),
|
|
children: tokio::sync::Mutex::new(HashMap::new()),
|
|
}
|
|
}
|
|
|
|
/// Baut Argumente und Umgebung für ein Profil. Der Server lauscht nur auf
|
|
/// `127.0.0.1`; die GPU-Auswahl läuft über `CUDA_VISIBLE_DEVICES`.
|
|
pub(crate) fn build_command(&self, profile: &ProfileSpec, port: u16) -> CommandLine {
|
|
let mut args = vec![
|
|
"-m".to_string(),
|
|
profile.model_path.display().to_string(),
|
|
"--host".to_string(),
|
|
"127.0.0.1".to_string(),
|
|
"--port".to_string(),
|
|
port.to_string(),
|
|
"-ngl".to_string(),
|
|
self.config.gpu_layers.to_string(),
|
|
"--alias".to_string(),
|
|
profile.model_alias.clone(),
|
|
];
|
|
if let Some(context) = profile.context {
|
|
args.push("-c".to_string());
|
|
args.push(context.to_string());
|
|
}
|
|
args.extend(self.config.extra_args.iter().cloned());
|
|
args.extend(profile.extra_args.iter().cloned());
|
|
|
|
let mut env: Vec<(String, String)> = self
|
|
.config
|
|
.env
|
|
.iter()
|
|
.map(|(k, v)| (k.clone(), v.clone()))
|
|
.collect();
|
|
let gpus: Vec<String> = profile.gpus.iter().map(u32::to_string).collect();
|
|
env.push(("CUDA_VISIBLE_DEVICES".to_string(), gpus.join(",")));
|
|
CommandLine { args, env }
|
|
}
|
|
|
|
fn validate(profile: &ProfileSpec) -> Result<()> {
|
|
if profile.gpus.is_empty() {
|
|
return Err(AdapterError::InvalidProfile(
|
|
"keine GPU angegeben".to_string(),
|
|
));
|
|
}
|
|
if profile.model_alias.trim().is_empty() {
|
|
return Err(AdapterError::InvalidProfile(
|
|
"model_alias ist leer".to_string(),
|
|
));
|
|
}
|
|
if !profile.model_path.is_file() {
|
|
return Err(AdapterError::InvalidProfile(format!(
|
|
"Modelldatei {} existiert nicht",
|
|
profile.model_path.display()
|
|
)));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
async fn spawn_and_wait(
|
|
&self,
|
|
id: u64,
|
|
port: u16,
|
|
profile: &ProfileSpec,
|
|
) -> Result<InstanceHandle> {
|
|
std::fs::create_dir_all(&self.config.log_dir).map_err(|source| AdapterError::Io {
|
|
path: self.config.log_dir.clone(),
|
|
source,
|
|
})?;
|
|
let log_path = self.config.log_dir.join(format!("instance-{id}.log"));
|
|
let io_err = |source| AdapterError::Io {
|
|
path: log_path.clone(),
|
|
source,
|
|
};
|
|
// Ein Neustart überschreibt keine alten Logs: Sie werden aufgehoben,
|
|
// die ältesten über `log_keep` hinaus gelöscht.
|
|
rotate_log(&log_path, self.config.log_keep).map_err(io_err)?;
|
|
// Im Anhängemodus: Wird das Log im Betrieb gekürzt (Größenbegrenzung),
|
|
// schreibt der Prozess danach am neuen Ende weiter statt hinter einer Lücke.
|
|
let log = std::fs::OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(&log_path)
|
|
.map_err(io_err)?;
|
|
let log_err = log.try_clone().map_err(io_err)?;
|
|
|
|
let command_line = self.build_command(profile, port);
|
|
let mut child = Command::new(&self.config.binary)
|
|
.args(&command_line.args)
|
|
.envs(command_line.env.iter().map(|(k, v)| (k, v)))
|
|
.stdin(std::process::Stdio::null())
|
|
.stdout(log)
|
|
.stderr(log_err)
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.map_err(|e| AdapterError::Spawn(format!("{}: {e}", self.config.binary.display())))?;
|
|
|
|
let timeout = Duration::from_secs(self.config.ready_timeout_secs);
|
|
let started = Instant::now();
|
|
loop {
|
|
if let Ok(Some(status)) = child.try_wait() {
|
|
tracing::warn!(
|
|
instance_id = id,
|
|
exit_code = status.code(),
|
|
"llama-server endete beim Start"
|
|
);
|
|
return Err(AdapterError::ExitedEarly {
|
|
code: status.code(),
|
|
log_tail: log_tail(&log_path, 20),
|
|
});
|
|
}
|
|
if http_status(port, "/health", Duration::from_secs(1)).await == Some(200) {
|
|
break;
|
|
}
|
|
if started.elapsed() >= timeout {
|
|
tracing::warn!(
|
|
instance_id = id,
|
|
seconds = self.config.ready_timeout_secs,
|
|
"llama-server wurde nicht rechtzeitig bereit"
|
|
);
|
|
let _ = child.start_kill();
|
|
let _ = child.wait().await;
|
|
return Err(AdapterError::NotReady {
|
|
seconds: self.config.ready_timeout_secs,
|
|
log_tail: log_tail(&log_path, 20),
|
|
});
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(200)).await;
|
|
}
|
|
|
|
let pid = child.id();
|
|
self.children
|
|
.lock()
|
|
.await
|
|
.insert(id, Managed { child, port });
|
|
Ok(InstanceHandle { id, pid, port })
|
|
}
|
|
|
|
async fn vram_mb(&self, pid: u32) -> Option<u64> {
|
|
let output = tokio::time::timeout(
|
|
Duration::from_secs(5),
|
|
Command::new(&self.config.nvidia_smi)
|
|
.args([
|
|
"--query-compute-apps=pid,used_memory",
|
|
"--format=csv,noheader,nounits",
|
|
])
|
|
.output(),
|
|
)
|
|
.await
|
|
.ok()?
|
|
.ok()?;
|
|
if !output.status.success() {
|
|
return None;
|
|
}
|
|
parse_vram_mb(&String::from_utf8_lossy(&output.stdout), pid)
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl Engine for LlamaCppEngine {
|
|
fn start_info(&self) -> StartInfo {
|
|
let c = &self.config;
|
|
let mut command = format!(
|
|
"{} -m <Modelldatei> --host 127.0.0.1 --port <Port> -ngl {} --alias <Modellname> [-c <Kontext>]",
|
|
c.binary.display(),
|
|
c.gpu_layers
|
|
);
|
|
for a in &c.extra_args {
|
|
command.push(' ');
|
|
command.push_str(a);
|
|
}
|
|
let mut env = vec![(
|
|
"CUDA_VISIBLE_DEVICES".to_string(),
|
|
"<GPUs des Modells>".to_string(),
|
|
)];
|
|
env.extend(c.env.iter().map(|(k, v)| (k.clone(), v.clone())));
|
|
StartInfo {
|
|
executable: Some(c.binary.clone()),
|
|
command,
|
|
env,
|
|
details: vec![
|
|
(
|
|
"Modellordner".to_string(),
|
|
c.model_roots
|
|
.iter()
|
|
.map(|p| p.display().to_string())
|
|
.collect::<Vec<_>>()
|
|
.join(", "),
|
|
),
|
|
(
|
|
"Ports".to_string(),
|
|
format!("{} bis {}", c.port_from, c.port_to),
|
|
),
|
|
(
|
|
"Zeitlimit Start".to_string(),
|
|
format!("{} s", c.ready_timeout_secs),
|
|
),
|
|
],
|
|
}
|
|
}
|
|
|
|
fn describe(&self) -> EngineInfo {
|
|
EngineInfo {
|
|
name: "llama.cpp".to_string(),
|
|
mode: Mode::Managed,
|
|
// Gemessen: Chat und Streaming laufen. Embeddings und Tool Calling
|
|
// hängen vom Modell und von den Startargumenten ab und sind noch
|
|
// nicht geprüft.
|
|
capabilities: Capabilities {
|
|
chat: true,
|
|
completions: true,
|
|
embeddings: false,
|
|
streaming: true,
|
|
tool_calling: false,
|
|
images: false,
|
|
},
|
|
}
|
|
}
|
|
|
|
async fn discover(&self) -> Result<Vec<DiscoveredArtifact>> {
|
|
let roots = self.config.model_roots.clone();
|
|
tokio::task::spawn_blocking(move || scan_models(&roots))
|
|
.await
|
|
.map_err(|e| AdapterError::Spawn(format!("Suche abgebrochen: {e}")))
|
|
}
|
|
|
|
async fn start(&self, profile: &ProfileSpec) -> Result<InstanceHandle> {
|
|
Self::validate(profile)?;
|
|
let port = self.ports.acquire()?;
|
|
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
|
|
match self.spawn_and_wait(id, port, profile).await {
|
|
Ok(handle) => Ok(handle),
|
|
Err(e) => {
|
|
self.ports.release(port);
|
|
Err(e)
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn stop(&self, instance: &InstanceHandle, grace: Duration) -> Result<()> {
|
|
let managed = self.children.lock().await.remove(&instance.id);
|
|
let Some(mut managed) = managed else {
|
|
return Ok(());
|
|
};
|
|
if let Some(pid) = managed.child.id() {
|
|
sigterm(pid);
|
|
}
|
|
let exited = tokio::time::timeout(grace, managed.child.wait()).await;
|
|
if exited.is_err() {
|
|
tracing::warn!(
|
|
instance_id = instance.id,
|
|
"llama-server reagierte nicht auf SIGTERM, wird beendet"
|
|
);
|
|
managed
|
|
.child
|
|
.kill()
|
|
.await
|
|
.map_err(|e| AdapterError::Stop(e.to_string()))?;
|
|
}
|
|
self.ports.release(managed.port);
|
|
Ok(())
|
|
}
|
|
|
|
async fn health(&self, instance: &InstanceHandle) -> Health {
|
|
let port = {
|
|
let mut children = self.children.lock().await;
|
|
let Some(managed) = children.get_mut(&instance.id) else {
|
|
return Health::Gone;
|
|
};
|
|
match managed.child.try_wait() {
|
|
Ok(Some(status)) => {
|
|
tracing::warn!(
|
|
instance_id = instance.id,
|
|
exit_code = status.code(),
|
|
"llama-server ist von selbst beendet"
|
|
);
|
|
let port = managed.port;
|
|
children.remove(&instance.id);
|
|
self.ports.release(port);
|
|
return Health::Gone;
|
|
}
|
|
Ok(None) => managed.port,
|
|
Err(e) => return Health::Unhealthy(e.to_string()),
|
|
}
|
|
};
|
|
match http_status(port, "/health", Duration::from_secs(2)).await {
|
|
Some(200) => Health::Ready,
|
|
Some(503) => Health::Starting,
|
|
Some(code) => Health::Unhealthy(format!("HTTP {code}")),
|
|
None => Health::Unhealthy("keine Antwort".to_string()),
|
|
}
|
|
}
|
|
|
|
fn endpoint(&self, instance: &InstanceHandle) -> Endpoint {
|
|
Endpoint {
|
|
base_url: format!("http://127.0.0.1:{}", instance.port),
|
|
protocol: Protocol::OpenAi,
|
|
upstream_model: None,
|
|
}
|
|
}
|
|
|
|
async fn measure(&self, instance: &InstanceHandle) -> Usage {
|
|
let Some(pid) = instance.pid else {
|
|
return Usage::default();
|
|
};
|
|
Usage {
|
|
vram_mb: self.vram_mb(pid).await,
|
|
ram_mb: std::fs::read_to_string(format!("/proc/{pid}/status"))
|
|
.ok()
|
|
.and_then(|text| parse_rss_mb(&text)),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Liest aus der Ausgabe von `nvidia-smi --query-compute-apps=pid,used_memory
|
|
/// --format=csv,noheader,nounits` den VRAM (MiB) eines Prozesses; mehrere
|
|
/// Zeilen (mehrere GPUs) werden addiert.
|
|
pub(crate) fn parse_vram_mb(output: &str, pid: u32) -> Option<u64> {
|
|
let mut total = None;
|
|
for line in output.lines() {
|
|
let mut fields = line.split(',').map(str::trim);
|
|
let (Some(p), Some(mb)) = (fields.next(), fields.next()) else {
|
|
continue;
|
|
};
|
|
if p.parse::<u32>().ok() == Some(pid)
|
|
&& let Ok(mb) = mb.parse::<u64>()
|
|
{
|
|
*total.get_or_insert(0) += mb;
|
|
}
|
|
}
|
|
total
|
|
}
|
|
|
|
/// Liest `VmRSS` (kB) aus `/proc/<pid>/status` und rechnet in MiB um.
|
|
pub(crate) fn parse_rss_mb(status: &str) -> Option<u64> {
|
|
let line = status.lines().find(|l| l.starts_with("VmRSS:"))?;
|
|
let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
|
|
Some(kb / 1024)
|
|
}
|
|
|
|
const MAX_SCAN_DEPTH: usize = 6;
|
|
|
|
/// Teile eines geteilten Modells: erster Teil, Summe der Größen, gefundene
|
|
/// Teile, erwartete Teile.
|
|
type ShardGroup = (Option<PathBuf>, u64, u32, u32);
|
|
|
|
/// Sucht `.gguf`-Modelle. Übersprungen werden Vision-Projektoren (`mmproj*`),
|
|
/// Vokabeldateien (`*vocab*`) und Entwurfsmodelle (`mtp*`), weil sie keine
|
|
/// eigenständigen Modelle sind. Geteilte Modelle (`-00001-of-00002`) zählen
|
|
/// als ein Modell mit der Summe der Größen; fehlt der erste Teil, wird das
|
|
/// Modell ausgelassen.
|
|
pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
|
|
let mut files = Vec::new();
|
|
for root in roots {
|
|
collect_gguf(root, 0, &mut files);
|
|
}
|
|
|
|
let mut singles = Vec::new();
|
|
let mut shards: BTreeMap<(PathBuf, String), ShardGroup> = BTreeMap::new();
|
|
|
|
for (path, size) in files {
|
|
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
|
continue;
|
|
};
|
|
let lower = stem.to_lowercase();
|
|
if lower.starts_with("mmproj") || lower.contains("vocab") || lower.starts_with("mtp") {
|
|
continue;
|
|
}
|
|
match split_shard(stem) {
|
|
Some((base, index, total)) => {
|
|
let key = (
|
|
path.parent().unwrap_or(Path::new("")).to_path_buf(),
|
|
base.to_string(),
|
|
);
|
|
let entry = shards.entry(key).or_insert((None, 0, 0, total));
|
|
entry.1 += size;
|
|
entry.2 += 1;
|
|
if index == 1 {
|
|
entry.0 = Some(path.clone());
|
|
}
|
|
}
|
|
None => singles.push(DiscoveredArtifact {
|
|
name: stem.to_string(),
|
|
quantization: parse_quantization(stem),
|
|
path,
|
|
size_bytes: size,
|
|
}),
|
|
}
|
|
}
|
|
|
|
let mut found = singles;
|
|
for ((_, base), (first, size, parts, expected)) in shards {
|
|
if let (Some(path), true) = (first, parts == expected) {
|
|
found.push(DiscoveredArtifact {
|
|
quantization: parse_quantization(&base),
|
|
name: base,
|
|
path,
|
|
size_bytes: size,
|
|
});
|
|
}
|
|
}
|
|
found.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.path.cmp(&b.path)));
|
|
found
|
|
}
|
|
|
|
fn collect_gguf(dir: &Path, depth: usize, out: &mut Vec<(PathBuf, u64)>) {
|
|
if depth > MAX_SCAN_DEPTH {
|
|
return;
|
|
}
|
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
return;
|
|
};
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
let Ok(meta) = entry.metadata() else { continue };
|
|
let hidden = entry.file_name().to_string_lossy().starts_with('.');
|
|
if meta.is_dir() && !hidden {
|
|
collect_gguf(&path, depth + 1, out);
|
|
} else if meta.is_file() && path.extension().is_some_and(|e| e == "gguf") {
|
|
out.push((path, meta.len()));
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Zerlegt `Name-00001-of-00002` in (`Name`, 1, 2).
|
|
fn split_shard(stem: &str) -> Option<(&str, u32, u32)> {
|
|
let (left, total) = stem.rsplit_once("-of-")?;
|
|
let total: u32 = total.parse().ok()?;
|
|
let (base, index) = left.rsplit_once('-')?;
|
|
let index: u32 = index.parse().ok()?;
|
|
Some((base, index, total))
|
|
}
|
|
|
|
/// Erkennt die Quantisierung im Dateinamen (zum Beispiel `Q4_K_XL`, `IQ1_S`,
|
|
/// `BF16`). Liefert `None`, wenn der Name keine erkennbare Angabe enthält.
|
|
pub(crate) fn parse_quantization(name: &str) -> Option<String> {
|
|
name.split(['-', '.']).find_map(|token| {
|
|
let upper = token.to_uppercase();
|
|
let digit_after = |prefix: &str| {
|
|
upper
|
|
.strip_prefix(prefix)
|
|
.and_then(|rest| rest.chars().next())
|
|
.is_some_and(|c| c.is_ascii_digit())
|
|
};
|
|
let known = matches!(upper.as_str(), "BF16" | "F16" | "F32");
|
|
(known || digit_after("IQ") || digit_after("Q")).then_some(upper)
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn profile() -> ProfileSpec {
|
|
ProfileSpec {
|
|
model_alias: "bonsai".to_string(),
|
|
model_path: PathBuf::from("/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf"),
|
|
gpus: vec![0, 1],
|
|
context: Some(2048),
|
|
extra_args: vec!["--no-webui".to_string()],
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn kommandozeile_bindet_nur_an_localhost_und_waehlt_gpus() {
|
|
let engine = LlamaCppEngine::new(LlamaCppConfig::default());
|
|
let cmd = engine.build_command(&profile(), 18090);
|
|
assert_eq!(
|
|
cmd.args,
|
|
[
|
|
"-m",
|
|
"/srv/models/gguf/Bonsai-1.7B-Q1_0.gguf",
|
|
"--host",
|
|
"127.0.0.1",
|
|
"--port",
|
|
"18090",
|
|
"-ngl",
|
|
"99",
|
|
"--alias",
|
|
"bonsai",
|
|
"-c",
|
|
"2048",
|
|
"--no-webui"
|
|
]
|
|
);
|
|
assert!(
|
|
cmd.env
|
|
.contains(&("CUDA_VISIBLE_DEVICES".to_string(), "0,1".to_string()))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn kontext_ist_optional_und_konfigurierte_argumente_kommen_zuerst() {
|
|
let config = LlamaCppConfig {
|
|
extra_args: vec!["--flash-attn".to_string()],
|
|
env: BTreeMap::from([("LD_LIBRARY_PATH".to_string(), "/x".to_string())]),
|
|
..LlamaCppConfig::default()
|
|
};
|
|
let engine = LlamaCppEngine::new(config);
|
|
let mut p = profile();
|
|
p.context = None;
|
|
let cmd = engine.build_command(&p, 1);
|
|
assert!(!cmd.args.contains(&"-c".to_string()));
|
|
let flash = cmd.args.iter().position(|a| a == "--flash-attn").unwrap();
|
|
let profil = cmd.args.iter().position(|a| a == "--no-webui").unwrap();
|
|
assert!(flash < profil);
|
|
assert!(
|
|
cmd.env
|
|
.contains(&("LD_LIBRARY_PATH".to_string(), "/x".to_string()))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn konfiguration_aus_toml_mit_standardwerten_und_ablehnung_unbekannter_felder() {
|
|
let config: LlamaCppConfig = toml::from_str("ready_timeout_secs = 300").unwrap();
|
|
assert_eq!(config.ready_timeout_secs, 300);
|
|
assert_eq!(config.port_from, 18080);
|
|
assert!(toml::from_str::<LlamaCppConfig>("portt = 1").is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn quantisierung_wird_aus_dem_namen_gelesen() {
|
|
let fall = |n: &str| parse_quantization(n);
|
|
assert_eq!(
|
|
fall("Qwen3.6-35B-A3B-UD-Q4_K_XL").as_deref(),
|
|
Some("Q4_K_XL")
|
|
);
|
|
assert_eq!(
|
|
fall("GLM-5.3-Flash-Maya-XS-IQ1_S").as_deref(),
|
|
Some("IQ1_S")
|
|
);
|
|
assert_eq!(fall("Bonsai-1.7B-Q1_0").as_deref(), Some("Q1_0"));
|
|
assert_eq!(
|
|
fall("Qwen3.8-Flash-Next-GSQ-RCO-Q2_0").as_deref(),
|
|
Some("Q2_0")
|
|
);
|
|
assert_eq!(fall("model-BF16").as_deref(), Some("BF16"));
|
|
assert_eq!(fall("Bonsai-1.7B"), None);
|
|
assert_eq!(fall("Qwen3.8-Flash"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn geteilte_dateien_werden_zerlegt() {
|
|
assert_eq!(
|
|
split_shard("Name-Q2_0-00001-of-00002"),
|
|
Some(("Name-Q2_0", 1, 2))
|
|
);
|
|
assert_eq!(split_shard("Name-Q2_0"), None);
|
|
assert_eq!(split_shard("A-of-B"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn vram_wird_pro_pid_gelesen_und_ueber_gpus_addiert() {
|
|
let out = "123772, 638\n999, 10\n123772, 100\n";
|
|
assert_eq!(parse_vram_mb(out, 123772), Some(738));
|
|
assert_eq!(parse_vram_mb(out, 5), None);
|
|
assert_eq!(parse_vram_mb("", 1), None);
|
|
assert_eq!(parse_vram_mb("Unsinn", 1), None);
|
|
}
|
|
|
|
#[test]
|
|
fn rss_wird_in_mib_umgerechnet() {
|
|
let status = "Name:\tllama-server\nVmRSS:\t 511668 kB\nThreads:\t4\n";
|
|
assert_eq!(parse_rss_mb(status), Some(499));
|
|
assert_eq!(parse_rss_mb("Name: x"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn suche_findet_modelle_und_ueberspringt_hilfsdateien() {
|
|
let root = std::env::temp_dir().join(format!("nexus-adapter-scan-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
let schreibe = |rel: &str, bytes: usize| {
|
|
let p = root.join(rel);
|
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
|
std::fs::write(p, vec![0u8; bytes]).unwrap();
|
|
};
|
|
schreibe("a/Qwen-Q4_K_XL.gguf", 10);
|
|
schreibe("a/mmproj-F16.gguf", 3);
|
|
schreibe("a/ggml-vocab-llama.gguf", 1);
|
|
schreibe("mtp/mtp-q2_0.gguf", 2);
|
|
schreibe("b/Big-IQ1_S-00001-of-00002.gguf", 5);
|
|
schreibe("b/Big-IQ1_S-00002-of-00002.gguf", 7);
|
|
schreibe("c/Unvollstaendig-Q2_0-00002-of-00002.gguf", 4);
|
|
schreibe("a/notizen.txt", 9);
|
|
schreibe(".versteckt/Geheim-Q4_0.gguf", 8);
|
|
|
|
let found = scan_models(std::slice::from_ref(&root));
|
|
let namen: Vec<_> = found.iter().map(|a| a.name.as_str()).collect();
|
|
assert_eq!(namen, ["Big-IQ1_S", "Qwen-Q4_K_XL"], "{found:?}");
|
|
assert_eq!(found[0].size_bytes, 12);
|
|
assert!(found[0].path.ends_with("Big-IQ1_S-00001-of-00002.gguf"));
|
|
assert_eq!(found[0].quantization.as_deref(), Some("IQ1_S"));
|
|
assert_eq!(found[1].size_bytes, 10);
|
|
let _ = std::fs::remove_dir_all(&root);
|
|
}
|
|
|
|
#[test]
|
|
fn suche_in_fehlendem_ordner_liefert_leere_liste() {
|
|
assert!(scan_models(&[PathBuf::from("/nicht/vorhanden")]).is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn profilpruefung_lehnt_unbrauchbare_profile_ab() {
|
|
let mut p = profile();
|
|
assert!(matches!(
|
|
LlamaCppEngine::validate(&p),
|
|
Err(AdapterError::InvalidProfile(m)) if m.contains("existiert nicht")
|
|
));
|
|
p.gpus.clear();
|
|
assert!(matches!(
|
|
LlamaCppEngine::validate(&p),
|
|
Err(AdapterError::InvalidProfile(m)) if m.contains("GPU")
|
|
));
|
|
}
|
|
}
|