feat: Quantisierung und Vision-Projektor aus der Datei, Passungsblock mit Abstand, Browserprüfung (#1233, #1234)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 14:01:37 +01:00
parent 4c7301e7db
commit d7d1352a2b
10 changed files with 160 additions and 26 deletions

View File

@ -50,6 +50,32 @@ impl GgufKopf {
} }
} }
/// Ist die Datei ein Vision-Projektor? Er heißt `mmproj-…` oder `<Modell>-mmproj-…`.
pub fn ist_mmproj(stem: &str) -> bool {
stem.to_lowercase().contains("mmproj")
}
/// Wählt aus den Projektoren eines Ordners den passendsten für ein Modell: den mit dem längsten
/// gemeinsamen Namensanfang, bei Gleichstand den ersten nach Name.
pub fn bester_mmproj<'a>(
modell_stem: &str,
kandidaten: impl IntoIterator<Item = &'a std::path::PathBuf>,
) -> Option<&'a std::path::PathBuf> {
let m = modell_stem.to_lowercase();
let gemeinsam = |p: &std::path::PathBuf| {
let n = p
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_lowercase();
m.chars().zip(n.chars()).take_while(|(a, b)| a == b).count()
};
let mut alle: Vec<&std::path::PathBuf> = kandidaten.into_iter().collect();
alle.sort();
// `max_by_key` liefert bei Gleichstand das letzte Element, daher von hinten.
alle.into_iter().rev().max_by_key(|p| gemeinsam(p))
}
/// Name der Quantisierung zu `general.file_type` (llama.cpp `llama_ftype`). /// Name der Quantisierung zu `general.file_type` (llama.cpp `llama_ftype`).
pub fn dateityp_name(zahl: u32) -> Option<&'static str> { pub fn dateityp_name(zahl: u32) -> Option<&'static str> {
Some(match zahl { Some(match zahl {
@ -544,6 +570,21 @@ mod tests {
b.extend(u64::MAX.to_le_bytes()); b.extend(u64::MAX.to_le_bytes());
} }
#[test]
fn mmproj_erkennung_und_auswahl() {
use std::path::PathBuf;
assert!(ist_mmproj("mmproj-F16"));
assert!(ist_mmproj("gemma-3-12b-it-mmproj-f16"));
assert!(!ist_mmproj("gemma-3-12b-it-Q4_K_M"));
let a = PathBuf::from("/m/gemma-3-12b-it-mmproj-f16.gguf");
let b = PathBuf::from("/m/mmproj-qwen.gguf");
let c = PathBuf::from("/m/mmproj-a.gguf");
assert_eq!(bester_mmproj("gemma-3-12b-it-Q4_K_M", [&a, &b]), Some(&a));
// Kein Namensanfang gemeinsam: der erste nach Name.
assert_eq!(bester_mmproj("anders", [&b, &c]), Some(&c));
assert_eq!(bester_mmproj("x", std::iter::empty::<&PathBuf>()), None);
}
#[test] #[test]
fn ohne_architektur_gibt_es_keinen_kopf() { fn ohne_architektur_gibt_es_keinen_kopf() {
let b = bauen(&[("general.name", V::S("x"))]); let b = bauen(&[("general.name", V::S("x"))]);

View File

@ -27,7 +27,7 @@ mod types;
pub mod startparams; pub mod startparams;
pub use engine::Engine; pub use engine::Engine;
pub use llama::{LlamaCppConfig, LlamaCppEngine}; pub use llama::{LlamaCppConfig, LlamaCppEngine, parse_quantization};
pub use maya::{MayaConfig, MayaEngine}; pub use maya::{MayaConfig, MayaEngine};
pub use mock::{MockConfig, MockEngine}; pub use mock::{MockConfig, MockEngine};
pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode}; pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode};

View File

@ -522,20 +522,18 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
let mut singles = Vec::new(); let mut singles = Vec::new();
let mut shards: BTreeMap<(PathBuf, String), ShardGroup> = BTreeMap::new(); let mut shards: BTreeMap<(PathBuf, String), ShardGroup> = BTreeMap::new();
// Vision-Projektoren je Ordner (der erste nach Name), dem Modell dort zugeordnet. // Vision-Projektoren je Ordner, dem passendsten Modell dort zugeordnet.
let mut projektoren: BTreeMap<PathBuf, PathBuf> = BTreeMap::new(); let mut projektoren: BTreeMap<PathBuf, Vec<PathBuf>> = BTreeMap::new();
for (path, _) in &files { for (path, _) in &files {
let mmproj = path let mmproj = path
.file_stem() .file_stem()
.and_then(|s| s.to_str()) .and_then(|s| s.to_str())
.is_some_and(|s| s.to_lowercase().starts_with("mmproj")); .is_some_and(crate::gguf::ist_mmproj);
if mmproj && let Some(dir) = path.parent() { if mmproj && let Some(dir) = path.parent() {
let e = projektoren projektoren
.entry(dir.to_path_buf()) .entry(dir.to_path_buf())
.or_insert_with(|| path.clone()); .or_default()
if path < e { .push(path.clone());
*e = path.clone();
}
} }
} }
@ -544,7 +542,7 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
continue; continue;
}; };
let lower = stem.to_lowercase(); let lower = stem.to_lowercase();
if lower.starts_with("mmproj") || lower.contains("vocab") || lower.starts_with("mtp") { if crate::gguf::ist_mmproj(stem) || lower.contains("vocab") || lower.starts_with("mtp") {
continue; continue;
} }
match split_shard(stem) { match split_shard(stem) {
@ -583,7 +581,12 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec<DiscoveredArtifact> {
} }
} }
for a in &mut found { for a in &mut found {
a.mmproj = a.path.parent().and_then(|d| projektoren.get(d)).cloned(); a.mmproj = a
.path
.parent()
.and_then(|d| projektoren.get(d))
.and_then(|liste| crate::gguf::bester_mmproj(&a.name, liste))
.cloned();
} }
found.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.path.cmp(&b.path))); found.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.path.cmp(&b.path)));
found found
@ -634,7 +637,7 @@ fn split_shard(stem: &str) -> Option<(&str, u32, u32)> {
/// Erkennt die Quantisierung im Dateinamen (zum Beispiel `Q4_K_XL`, `IQ1_S`, /// Erkennt die Quantisierung im Dateinamen (zum Beispiel `Q4_K_XL`, `IQ1_S`,
/// `BF16`). Liefert `None`, wenn der Name keine erkennbare Angabe enthält. /// `BF16`). Liefert `None`, wenn der Name keine erkennbare Angabe enthält.
pub(crate) fn parse_quantization(name: &str) -> Option<String> { pub fn parse_quantization(name: &str) -> Option<String> {
name.split(['-', '.']).find_map(|token| { name.split(['-', '.']).find_map(|token| {
let upper = token.to_uppercase(); let upper = token.to_uppercase();
let digit_after = |prefix: &str| { let digit_after = |prefix: &str| {

View File

@ -57,9 +57,9 @@ fn jetzt() -> i64 {
.unwrap_or(0) .unwrap_or(0)
} }
/// Sucht den Vision-Projektor im Ordner der Modelldatei (der erste nach Name). /// Sucht den Vision-Projektor im Ordner der Modelldatei (der passendste nach Name).
fn mmproj_neben(pfad: &std::path::Path) -> Option<std::path::PathBuf> { fn mmproj_neben(pfad: &std::path::Path) -> Option<std::path::PathBuf> {
let mut gefunden: Vec<std::path::PathBuf> = std::fs::read_dir(pfad.parent()?) let kandidaten: Vec<std::path::PathBuf> = std::fs::read_dir(pfad.parent()?)
.ok()? .ok()?
.flatten() .flatten()
.map(|e| e.path()) .map(|e| e.path())
@ -67,11 +67,11 @@ fn mmproj_neben(pfad: &std::path::Path) -> Option<std::path::PathBuf> {
p.extension().is_some_and(|e| e == "gguf") p.extension().is_some_and(|e| e == "gguf")
&& p.file_stem() && p.file_stem()
.and_then(|s| s.to_str()) .and_then(|s| s.to_str())
.is_some_and(|s| s.to_lowercase().starts_with("mmproj")) .is_some_and(nexus_adapter::gguf::ist_mmproj)
}) })
.collect(); .collect();
gefunden.sort(); let stem = pfad.file_stem()?.to_str()?;
gefunden.into_iter().next() nexus_adapter::gguf::bester_mmproj(stem, &kandidaten).cloned()
} }
/// Liest beim Start den Kopf aller llama.cpp-Modelle, die noch keinen haben, und speichert ihn. /// Liest beim Start den Kopf aller llama.cpp-Modelle, die noch keinen haben, und speichert ihn.
@ -99,6 +99,19 @@ pub async fn kopf_nachlesen(state: &AppState) -> usize {
} }
Err(e) => aus_fehler(&e, jetzt()), Err(e) => aus_fehler(&e, jetzt()),
}; };
// Fehlt die Quantisierung in der Registry, gilt die Datei, sonst der Dateiname.
let quant = k
.dateityp
.and_then(nexus_adapter::gguf::dateityp_name)
.map(str::to_string)
.or_else(|| {
pfad.file_stem()
.and_then(|s| s.to_str())
.and_then(nexus_adapter::parse_quantization)
});
if let Some(q) = quant {
let _ = state.store().set_quantisierung_wenn_leer(&modell, &q);
}
if state if state
.store() .store()
.set_artifact_kopf(&modell, &k) .set_artifact_kopf(&modell, &k)
@ -317,6 +330,7 @@ pub fn block_html(
gpus: &[u32], gpus: &[u32],
gesamt: &[(u32, u64)], gesamt: &[(u32, u64)],
gemessen_mb: Option<i64>, gemessen_mb: Option<i64>,
quantisierung_name: Option<&str>,
) -> String { ) -> String {
use crate::ui::esc; use crate::ui::esc;
if let Some(f) = &k.fehler { if let Some(f) = &k.fehler {
@ -330,10 +344,15 @@ pub fn block_html(
.to_string(); .to_string();
} }
let zahl = |v: Option<u32>| v.map_or("–".to_string(), |v| v.to_string()); let zahl = |v: Option<u32>| v.map_or("–".to_string(), |v| v.to_string());
let quant = k // Die Datei hat Vorrang; fehlt `general.file_type` (bei neu quantisierten Dateien häufig), gilt der Name.
.dateityp let quant = match (
.and_then(nexus_adapter::gguf::dateityp_name) k.dateityp.and_then(nexus_adapter::gguf::dateityp_name),
.map_or("–".to_string(), str::to_string); quantisierung_name,
) {
(Some(q), _) => format!("{q} (aus der Datei)"),
(None, Some(q)) => format!("{q} (aus dem Dateinamen, die Datei nennt keine)"),
(None, None) => "–".to_string(),
};
let mut feld = String::new(); let mut feld = String::new();
let mut f = |titel: &str, wert: String| { let mut f = |titel: &str, wert: String| {
feld.push_str(&format!( feld.push_str(&format!(
@ -345,7 +364,7 @@ pub fn block_html(
"Architektur", "Architektur",
k.architektur.clone().unwrap_or_else(|| "–".into()), k.architektur.clone().unwrap_or_else(|| "–".into()),
); );
f("Quantisierung (aus der Datei)", quant); f("Quantisierung", quant);
f( f(
"Trainierter Kontext", "Trainierter Kontext",
k.kontext.map_or("–".into(), |c| format!("{c} Tokens")), k.kontext.map_or("–".into(), |c| format!("{c} Tokens")),
@ -379,7 +398,7 @@ pub fn block_html(
None => "noch nicht gemessen".to_string(), None => "noch nicht gemessen".to_string(),
}; };
format!( format!(
"<div class=\"modellkopf\"><h3>Aus der Modelldatei</h3><dl class=\"daten dlg-daten\">{feld}</dl>\ "<div class=\"modellkopf\"><h3>Aus der Modelldatei</h3><dl class=\"daten\">{feld}</dl>\
<p class=\"passung\">{zeile}{chip}</p><p class=\"hilfe\">{messung}</p>\ <p class=\"passung\">{zeile}{chip}</p><p class=\"hilfe\">{messung}</p>\
<ul class=\"hilfe passung-hinweise\">{hinweise}</ul></div>", <ul class=\"hilfe passung-hinweise\">{hinweise}</ul></div>",
zeile = esc(&a.zeile), zeile = esc(&a.zeile),

View File

@ -1373,6 +1373,7 @@ button.icon{display:inline-flex;align-items:center;justify-content:center;paddin
.dlg-kopf{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1rem 1.3rem .4rem}.dlg-kopf h2{margin:0;font-size:1.15rem;overflow-wrap:anywhere} .dlg-kopf{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:1rem 1.3rem .4rem}.dlg-kopf h2{margin:0;font-size:1.15rem;overflow-wrap:anywhere}
.dlg-kopf button{font-size:1.1rem;line-height:1;padding:.2rem .6rem} .dlg-kopf button{font-size:1.1rem;line-height:1;padding:.2rem .6rem}
.dlg-daten{padding:.4rem 1.3rem .9rem;border-bottom:1px solid var(--border)} .dlg-daten{padding:.4rem 1.3rem .9rem;border-bottom:1px solid var(--border)}
.modellkopf{padding:.2rem 1.3rem .6rem;border-bottom:1px solid var(--border)}.modellkopf h3{font-size:.95rem;margin:.6rem 0 .5rem}.modellkopf dl.daten{padding:0 0 .6rem}.modellkopf p{margin:.3rem 0}.passung-hinweise{margin:.2rem 0 .4rem;padding-left:1.2rem}
.dlg-form{display:flex;flex-direction:column;gap:1rem;padding:1rem 1.3rem} .dlg-form{display:flex;flex-direction:column;gap:1rem;padding:1rem 1.3rem}
.feld{display:flex;flex-direction:column;gap:.3rem}.feld .titel{font-weight:600;font-size:.9rem}.feld input{width:100%} .feld{display:flex;flex-direction:column;gap:.3rem}.feld .titel{font-weight:600;font-size:.9rem}.feld input{width:100%}
.hilfe{color:var(--muted);font-size:.8rem;line-height:1.4} .hilfe{color:var(--muted);font-size:.8rem;line-height:1.4}

View File

@ -101,7 +101,15 @@ fn register_dialog(
Some(k) => { Some(k) => {
let mut k = crate::modellkopf::aus_kopf(k, a.mmproj.as_deref(), 1); let mut k = crate::modellkopf::aus_kopf(k, a.mmproj.as_deref(), 1);
k.stand = Some(1); k.stand = Some(1);
crate::modellkopf::block_html(&k, a.size_bytes, None, &[0], gesamt, None) crate::modellkopf::block_html(
&k,
a.size_bytes,
None,
&[0],
gesamt,
None,
a.quantization.as_deref(),
)
} }
None => String::new(), None => String::new(),
}; };

View File

@ -486,6 +486,7 @@ fn modellkopf_block(state: &AppState, m: &ModelRow) -> String {
&gpus, &gpus,
&gesamt, &gesamt,
m.measured_mb, m.measured_mb,
m.quantization.as_deref(),
) )
} }

View File

@ -7139,7 +7139,7 @@ async fn modellkopf_wird_nachgelesen_und_mit_passung_auf_der_modellseite_gezeigt
name: name.to_string(), name: name.to_string(),
engine: "llama.cpp".to_string(), engine: "llama.cpp".to_string(),
path: dir.join(datei), path: dir.join(datei),
quantization: Some("Q8_0".to_string()), quantization: (name != "kopf-gross").then(|| "Q8_0".to_string()),
size_bytes: Some(groesse), size_bytes: Some(groesse),
gpus: vec![0], gpus: vec![0],
context: None, context: None,
@ -7187,7 +7187,7 @@ async fn modellkopf_wird_nachgelesen_und_mit_passung_auf_der_modellseite_gezeigt
for erwartet in [ for erwartet in [
"Aus der Modelldatei", "Aus der Modelldatei",
"<dt>Architektur</dt><dd>llama</dd>", "<dt>Architektur</dt><dd>llama</dd>",
"<dt>Quantisierung (aus der Datei)</dt><dd>Q4_K_M</dd>", "<dt>Quantisierung</dt><dd>Q4_K_M (aus der Datei)</dd>",
"<dt>Trainierter Kontext</dt><dd>8192 Tokens</dd>", "<dt>Trainierter Kontext</dt><dd>8192 Tokens</dd>",
"<dt>Vision-Projektor</dt><dd>mmproj-F16.gguf</dd>", "<dt>Vision-Projektor</dt><dd>mmproj-F16.gguf</dd>",
"geschätzt: Gewichte 2,0 GB + KV-Cache 0,4 GB bei 8192 Tokens (trainierter Kontext, weil keiner eingestellt ist) = 2,4 GB", "geschätzt: Gewichte 2,0 GB + KV-Cache 0,4 GB bei 8192 Tokens (trainierter Kontext, weil keiner eingestellt ist) = 2,4 GB",

View File

@ -472,6 +472,19 @@ impl Store {
Ok(n > 0) Ok(n > 0)
} }
/// Trägt die Quantisierung ein, wenn bisher keine steht (zum Beispiel bei Modellen, die per
/// Befehlszeile ohne `--quant` registriert wurden). Eine vorhandene Angabe bleibt.
pub fn set_quantisierung_wenn_leer(&self, model: &str, quantisierung: &str) -> Result<()> {
self.connection()
.execute(
"UPDATE artifact SET quantisierung = ?2 WHERE quantisierung IS NULL
AND model_id = (SELECT id FROM model WHERE name = ?1)",
[model, quantisierung],
)
.map_err(db)?;
Ok(())
}
/// Modellkopf des ersten Artifacts; `None`, wenn es das Modell nicht gibt. /// Modellkopf des ersten Artifacts; `None`, wenn es das Modell nicht gibt.
pub fn artifact_kopf(&self, model: &str) -> Result<Option<ArtifactKopf>> { pub fn artifact_kopf(&self, model: &str) -> Result<Option<ArtifactKopf>> {
let row = self.connection().query_row( let row = self.connection().query_row(

View File

@ -0,0 +1,48 @@
// admin2modellkopf.1 und .2 (Sichtprüfung, #1233, #1234): Modellseite und Registrieren-Dialog zeigen die Werte aus der
// Modelldatei und die Passung; Breiten 1280/768/390/320, hell und dunkel, kein Überlauf, Dialog und Texte.
// Aufruf: node modellkopf.mjs <Testpasswort> (Benutzer `claude`, `NEXUS_BASE`, Standard http://127.0.0.1:18127; Testinstanz
// mit echten GGUF-Dateien, einer `nvidia-smi`-Attrappe mit GPU 0 = 12 GB und GPU 1 = 24 GB). Nicht gegen die Produktion.
import * as cdp from './lib.mjs';
const BASE = process.env.NEXUS_BASE || 'http://127.0.0.1:18127', pw = process.argv[2];
const AUS = process.env.NEXUS_AUS || '/tmp';
const b = await cdp.start({ port: 9378 });
const ergebnisse = [];
const pruefe = (name, ok, extra = '') => { ergebnisse.push(ok); console.log(ok ? 'OK ' : 'FEHL', name, extra); };
const warte = ms => new Promise(r => setTimeout(r, ms));
try {
await b.login(BASE, 'claude', pw);
await b.goto(BASE + '/ui/modelle');
await b.eval(`document.querySelectorAll('dialog').forEach(d=>d.setAttribute('open',''))`);
const text = await b.eval('document.body.innerText');
const paare = (await b.eval(`[...document.querySelectorAll('.modellkopf dl div')].map(d=>d.querySelector('dt').textContent+'='+d.querySelector('dd').textContent).join('|')`));
pruefe('Modellseite: Werte aus der Datei', /Aus der Modelldatei/.test(text) && /Architektur=qwen2\|/.test(paare) && /Architektur=gemma3\|/.test(paare) && /Architektur=qwen35\|/.test(paare) && /Trainierter Kontext=262144 Tokens/.test(paare));
pruefe('Quantisierung: aus der Datei, wenn sie sie nennt, sonst aus dem Dateinamen mit Herkunft', /Quantisierung=Q4_K_M \(aus der Datei\)/.test(paare) && /Quantisierung=IQ4_XS \(aus dem Dateinamen/.test(paare));
pruefe('Schätzung mit Gewichten, KV-Cache und Kontext', /geschätzt: Gewichte [\d,]+ GB \+ KV-Cache [\d,]+ GB bei \d+ Tokens/.test(text));
pruefe('Urteil als Text (nicht nur Farbe)', /\b(passt|knapp|passt nicht)\b/.test(text));
pruefe('Messung getrennt: „noch nicht gemessen“', /noch nicht gemessen/.test(text));
pruefe('Hybridmodell nennt den Vorbehalt', /Hybridmodell: nur jede n-te Schicht zählt/.test(text));
pruefe('Gleitfenster nennt den Vorbehalt', /Gleitfenster nicht berücksichtigt/.test(text));
pruefe('Zwei GPUs: Hinweis zur Aufteilung', /mehrere GPUs: die Aufteilung ist ungenau/.test(text));
pruefe('Vision-Projektor gefunden (Gemma 12b)', /Vision-Projektor=gemma-3-12b-it-mmproj-f16\.gguf/.test(paare));
// Registrieren-Dialog aus der Suche
await b.goto(BASE + '/ui/engines?suche=llama.cpp');
const such = await b.eval(`(()=>{const d=[...document.querySelectorAll('dialog')].find(x=>/modell-Q8_0/.test(x.textContent));return d?d.innerText:''})()`);
pruefe('Registrieren-Dialog zeigt Kopf und Passung', /Aus der Modelldatei/.test(such) && /geschätzt:/.test(such), such ? '' : '(Dialog fehlt)');
pruefe('Umbenannte Datei: Quantisierung steht in der Tabelle der Datei (Q4_K_M statt Q8_0)', await b.eval(`[...document.querySelectorAll('tr')].some(r=>/modell-Q8_0/.test(r.textContent)&&/Q4_K_M/.test(r.textContent))`));
// Breiten, hell und dunkel, Überlauf
for (const thema of ['light', 'dark']) {
for (const [w, hgt] of [[1280, 900], [768, 900], [390, 844], [320, 568]]) {
await b.viewport(w, hgt, { mobile: w < 700 });
await b.eval(`localStorage.setItem('styleguide-theme','${thema}')`);
await b.goto(BASE + '/ui/modelle');
await b.eval(`(()=>{const d=[...document.querySelectorAll('dialog')].find(x=>/Aus der Modelldatei/.test(x.textContent)); if(d) d.showModal?.()})()`);
await warte(300);
const ue = await b.eval(`Math.max(document.documentElement.scrollWidth - document.documentElement.clientWidth, ...[...document.querySelectorAll('dialog[open]')].map(d=>d.scrollWidth-d.clientWidth))`);
pruefe(`${thema} ${w}px Dialog ohne Überlauf nach rechts`, ue <= 1, `(${ue})`);
if (w === 1280 || w === 390) await b.shot(`${AUS}/modellkopf-${thema}-${w}.png`, { full: false });
}
}
} finally { b.close(); }
const fehl = ergebnisse.filter(x => !x).length;
console.log(fehl ? `${fehl} Prüfung(en) fehlgeschlagen` : `Alle ${ergebnisse.length} Prüfungen bestanden`);
process.exit(fehl ? 1 : 0);