From d7d1352a2b253d84a460c81d65d40d4e72fb60e2 Mon Sep 17 00:00:00 2001 From: wlkns-dev Date: Fri, 27 Nov 2026 14:01:37 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20Quantisierung=20und=20Vision-Projektor?= =?UTF-8?q?=20aus=20der=20Datei,=20Passungsblock=20mit=20Abstand,=20Browse?= =?UTF-8?q?rpr=C3=BCfung=20(#1233,=20#1234)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- crates/nexus-adapter/src/gguf.rs | 41 +++++++++++++++++++++++ crates/nexus-adapter/src/lib.rs | 2 +- crates/nexus-adapter/src/llama.rs | 25 ++++++++------ crates/nexus-api/src/modellkopf.rs | 41 +++++++++++++++++------ crates/nexus-api/src/ui.rs | 1 + crates/nexus-api/src/ui/engines.rs | 10 +++++- crates/nexus-api/src/ui/verwaltung.rs | 1 + crates/nexus-api/tests/api.rs | 4 +-- crates/nexus-store/src/registry.rs | 13 ++++++++ scripts/ui-pruefung/modellkopf.mjs | 48 +++++++++++++++++++++++++++ 10 files changed, 160 insertions(+), 26 deletions(-) create mode 100644 scripts/ui-pruefung/modellkopf.mjs diff --git a/crates/nexus-adapter/src/gguf.rs b/crates/nexus-adapter/src/gguf.rs index a28e47b..2ab293d 100644 --- a/crates/nexus-adapter/src/gguf.rs +++ b/crates/nexus-adapter/src/gguf.rs @@ -50,6 +50,32 @@ impl GgufKopf { } } +/// Ist die Datei ein Vision-Projektor? Er heißt `mmproj-…` oder `-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, +) -> 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`). pub fn dateityp_name(zahl: u32) -> Option<&'static str> { Some(match zahl { @@ -544,6 +570,21 @@ mod tests { 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] fn ohne_architektur_gibt_es_keinen_kopf() { let b = bauen(&[("general.name", V::S("x"))]); diff --git a/crates/nexus-adapter/src/lib.rs b/crates/nexus-adapter/src/lib.rs index 9f3cee3..52ee0d5 100644 --- a/crates/nexus-adapter/src/lib.rs +++ b/crates/nexus-adapter/src/lib.rs @@ -27,7 +27,7 @@ mod types; pub mod startparams; pub use engine::Engine; -pub use llama::{LlamaCppConfig, LlamaCppEngine}; +pub use llama::{LlamaCppConfig, LlamaCppEngine, parse_quantization}; pub use maya::{MayaConfig, MayaEngine}; pub use mock::{MockConfig, MockEngine}; pub use ollama::{OllamaConfig, OllamaEngine, OllamaMode}; diff --git a/crates/nexus-adapter/src/llama.rs b/crates/nexus-adapter/src/llama.rs index 0966578..cf770c2 100644 --- a/crates/nexus-adapter/src/llama.rs +++ b/crates/nexus-adapter/src/llama.rs @@ -522,20 +522,18 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec { let mut singles = Vec::new(); let mut shards: BTreeMap<(PathBuf, String), ShardGroup> = BTreeMap::new(); - // Vision-Projektoren je Ordner (der erste nach Name), dem Modell dort zugeordnet. - let mut projektoren: BTreeMap = BTreeMap::new(); + // Vision-Projektoren je Ordner, dem passendsten Modell dort zugeordnet. + let mut projektoren: BTreeMap> = BTreeMap::new(); for (path, _) in &files { let mmproj = path .file_stem() .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() { - let e = projektoren + projektoren .entry(dir.to_path_buf()) - .or_insert_with(|| path.clone()); - if path < e { - *e = path.clone(); - } + .or_default() + .push(path.clone()); } } @@ -544,7 +542,7 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec { continue; }; 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; } match split_shard(stem) { @@ -583,7 +581,12 @@ pub(crate) fn scan_models(roots: &[PathBuf]) -> Vec { } } 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 @@ -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`, /// `BF16`). Liefert `None`, wenn der Name keine erkennbare Angabe enthält. -pub(crate) fn parse_quantization(name: &str) -> Option { +pub fn parse_quantization(name: &str) -> Option { name.split(['-', '.']).find_map(|token| { let upper = token.to_uppercase(); let digit_after = |prefix: &str| { diff --git a/crates/nexus-api/src/modellkopf.rs b/crates/nexus-api/src/modellkopf.rs index 326ed04..a6b1684 100644 --- a/crates/nexus-api/src/modellkopf.rs +++ b/crates/nexus-api/src/modellkopf.rs @@ -57,9 +57,9 @@ fn jetzt() -> i64 { .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 { - let mut gefunden: Vec = std::fs::read_dir(pfad.parent()?) + let kandidaten: Vec = std::fs::read_dir(pfad.parent()?) .ok()? .flatten() .map(|e| e.path()) @@ -67,11 +67,11 @@ fn mmproj_neben(pfad: &std::path::Path) -> Option { p.extension().is_some_and(|e| e == "gguf") && p.file_stem() .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(); - gefunden.sort(); - gefunden.into_iter().next() + let stem = pfad.file_stem()?.to_str()?; + nexus_adapter::gguf::bester_mmproj(stem, &kandidaten).cloned() } /// 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()), }; + // 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 .store() .set_artifact_kopf(&modell, &k) @@ -317,6 +330,7 @@ pub fn block_html( gpus: &[u32], gesamt: &[(u32, u64)], gemessen_mb: Option, + quantisierung_name: Option<&str>, ) -> String { use crate::ui::esc; if let Some(f) = &k.fehler { @@ -330,10 +344,15 @@ pub fn block_html( .to_string(); } let zahl = |v: Option| v.map_or("–".to_string(), |v| v.to_string()); - let quant = k - .dateityp - .and_then(nexus_adapter::gguf::dateityp_name) - .map_or("–".to_string(), str::to_string); + // Die Datei hat Vorrang; fehlt `general.file_type` (bei neu quantisierten Dateien häufig), gilt der Name. + let quant = match ( + k.dateityp.and_then(nexus_adapter::gguf::dateityp_name), + 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 f = |titel: &str, wert: String| { feld.push_str(&format!( @@ -345,7 +364,7 @@ pub fn block_html( "Architektur", k.architektur.clone().unwrap_or_else(|| "–".into()), ); - f("Quantisierung (aus der Datei)", quant); + f("Quantisierung", quant); f( "Trainierter Kontext", k.kontext.map_or("–".into(), |c| format!("{c} Tokens")), @@ -379,7 +398,7 @@ pub fn block_html( None => "noch nicht gemessen".to_string(), }; format!( - "

Aus der Modelldatei

{feld}
\ + "

Aus der Modelldatei

{feld}
\

{zeile}{chip}

{messung}

\
    {hinweise}
", zeile = esc(&a.zeile), diff --git a/crates/nexus-api/src/ui.rs b/crates/nexus-api/src/ui.rs index 70eee54..032f652 100644 --- a/crates/nexus-api/src/ui.rs +++ b/crates/nexus-api/src/ui.rs @@ -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 button{font-size:1.1rem;line-height:1;padding:.2rem .6rem} .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} .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} diff --git a/crates/nexus-api/src/ui/engines.rs b/crates/nexus-api/src/ui/engines.rs index 2d4ad33..80f55dc 100644 --- a/crates/nexus-api/src/ui/engines.rs +++ b/crates/nexus-api/src/ui/engines.rs @@ -101,7 +101,15 @@ fn register_dialog( Some(k) => { let mut k = crate::modellkopf::aus_kopf(k, a.mmproj.as_deref(), 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(), }; diff --git a/crates/nexus-api/src/ui/verwaltung.rs b/crates/nexus-api/src/ui/verwaltung.rs index ed642b6..01843c6 100644 --- a/crates/nexus-api/src/ui/verwaltung.rs +++ b/crates/nexus-api/src/ui/verwaltung.rs @@ -486,6 +486,7 @@ fn modellkopf_block(state: &AppState, m: &ModelRow) -> String { &gpus, &gesamt, m.measured_mb, + m.quantization.as_deref(), ) } diff --git a/crates/nexus-api/tests/api.rs b/crates/nexus-api/tests/api.rs index a238ae2..95c3404 100644 --- a/crates/nexus-api/tests/api.rs +++ b/crates/nexus-api/tests/api.rs @@ -7139,7 +7139,7 @@ async fn modellkopf_wird_nachgelesen_und_mit_passung_auf_der_modellseite_gezeigt name: name.to_string(), engine: "llama.cpp".to_string(), path: dir.join(datei), - quantization: Some("Q8_0".to_string()), + quantization: (name != "kopf-gross").then(|| "Q8_0".to_string()), size_bytes: Some(groesse), gpus: vec![0], context: None, @@ -7187,7 +7187,7 @@ async fn modellkopf_wird_nachgelesen_und_mit_passung_auf_der_modellseite_gezeigt for erwartet in [ "Aus der Modelldatei", "
Architektur
llama
", - "
Quantisierung (aus der Datei)
Q4_K_M
", + "
Quantisierung
Q4_K_M (aus der Datei)
", "
Trainierter Kontext
8192 Tokens
", "
Vision-Projektor
mmproj-F16.gguf
", "geschätzt: Gewichte 2,0 GB + KV-Cache 0,4 GB bei 8192 Tokens (trainierter Kontext, weil keiner eingestellt ist) = 2,4 GB", diff --git a/crates/nexus-store/src/registry.rs b/crates/nexus-store/src/registry.rs index b9e1579..c8df8cc 100644 --- a/crates/nexus-store/src/registry.rs +++ b/crates/nexus-store/src/registry.rs @@ -472,6 +472,19 @@ impl Store { 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. pub fn artifact_kopf(&self, model: &str) -> Result> { let row = self.connection().query_row( diff --git a/scripts/ui-pruefung/modellkopf.mjs b/scripts/ui-pruefung/modellkopf.mjs new file mode 100644 index 0000000..24decee --- /dev/null +++ b/scripts/ui-pruefung/modellkopf.mjs @@ -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 (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);