The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(neuron): Neuron tweaker – control-vector sliders for LU Engine models
purplec5422e50ca59
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d9b15dd6..33e8f3f2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -263,6 +263,12 @@ jobs:*-windows-*) touch "src-tauri/bin/lu-llama-server-$triple.exe" ;;*) touch "src-tauri/bin/lu-llama-server-$triple" ;;esac+ # The Neuron tweaker's vector tool (3.0.9, P11) is a second+ # externalBin on Windows (tauri.windows.conf.json), so it needs its+ # stub too. Linux does not ship it.+ case "$triple" in+ *-windows-*) touch "src-tauri/bin/lu-llama-cvector-generator-$triple.exe" ;;+ esacls -la src-tauri/bin/# K1 (3.0.1): tauri.windows.conf.json / tauri.linux.conf.json now# declare a bundle.resources glob for the dynamic-ISA companion@@ -518,6 +524,12 @@ jobs:*-windows-*) touch "src-tauri/bin/lu-llama-server-$triple.exe" ;;*) touch "src-tauri/bin/lu-llama-server-$triple" ;;esac+ # The Neuron tweaker's vector tool (3.0.9, P11) is a second+ # externalBin on Windows (tauri.windows.conf.json), so it needs its+ # stub too. Linux does not ship it.+ case "$triple" in+ *-windows-*) touch "src-tauri/bin/lu-llama-cvector-generator-$triple.exe" ;;+ esacls -la src-tauri/bin/# K1 (3.0.1): this job runs a REAL `tauri build`, which resolves# bundle.resources for real: tauri.windows.conf.json /@@ -666,6 +678,8 @@ jobs:# The refusal-removal tool's quantizer (A14) is a second externalBin# on macOS only (tauri.macos.conf.json), so it needs its stub too.touch "src-tauri/bin/lu-llama-quantize-$triple"+ # And the Neuron tweaker's vector tool (3.0.9, P11), same file list.+ touch "src-tauri/bin/lu-llama-cvector-generator-$triple"printf '<!doctype html><title>ci placeholder</title>' > dist/index.htmlls -la src-tauri/bin/diff --git a/scripts/build-llama.sh b/scripts/build-llama.shindex 5fab0c28..70d858bf 100755--- a/scripts/build-llama.sh+++ b/scripts/build-llama.sh@@ -226,6 +226,27 @@ quantize_out_name_for() {echo "lu-llama-quantize-$1"}+# llama-cvector-generator (3.0.9, P11 Neuron tweaker) ships on macOS and+# Windows: it turns two short lists of example prompts into a control vector+# for the model the user has, which llama-server then applies with+# --control-vector. Same pinned source tree, same flags as the server. On+# Windows it links the same llama/ggml/llama-common DLLs the server already+# stages beside the exe, so it needs nothing of its own. Linux does not ship+# it yet (AppImage/deb library layout is a separate check).+cvector_ships_for() {+ case "$1" in+ *-apple-darwin | x86_64-pc-windows-msvc) return 0 ;;+ *) return 1 ;;+ esac+}++cvector_out_name_for() {+ case "$1" in+ *-windows-*) echo "lu-llama-cvector-generator-$1.exe" ;;+ *) echo "lu-llama-cvector-generator-$1" ;;+ esac+}+# A 40-hex commit SHA and nothing else. A short SHA, a tag name or an empty# override would all silently reduce the pin back to "whatever origin says".assert_pinned_commit() {@@ -427,6 +448,9 @@ build_triple() {if quantize_ships_for "$triple"; thencmake --build "$build_dir" --config Release --target llama-quantize -j "${BUILD_JOBS:-4}"fi+ if cvector_ships_for "$triple"; then+ cmake --build "$build_dir" --config Release --target llama-cvector-generator -j "${BUILD_JOBS:-4}"+ fi# Locate the produced binary (path differs by generator/platform).local builtbuilt="$(find "$build_dir" -type f \( -name 'llama-server' -o -name 'llama-server.exe' \) -print -quit)"@@ -442,6 +466,13 @@ build_triple() {cp "$built_q" "$BIN_DIR/$(quantize_out_name_for "$triple")"chmod +x "$BIN_DIR/$(quantize_out_name_for "$triple")"fi+ if cvector_ships_for "$triple"; then+ local built_cv+ built_cv="$(find "$build_dir" -type f \( -name 'llama-cvector-generator' -o -name 'llama-cvector-generator.exe' \) -print -quit)"+ [ -n "$built_cv" ] || die "llama-cvector-generator binary not found under $build_dir"+ cp "$built_cv" "$BIN_DIR/$(cvector_out_name_for "$triple")"+ chmod +x "$BIN_DIR/$(cvector_out_name_for "$triple")"+ filocal out_digest; out_digest="$(sha256_of "$out")"local digest_lines="$out: ${out_digest:-unavailable}"diff --git a/src-tauri/bin/.gitignore b/src-tauri/bin/.gitignoreindex 98808900..015ff60d 100644--- a/src-tauri/bin/.gitignore+++ b/src-tauri/bin/.gitignore@@ -5,6 +5,7 @@# does not suddenly offer a 3 GB binary for commit.lu-llama-server-*lu-llama-quantize-*+lu-llama-cvector-generator-*llama-server-**.dll!.gitignorediff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rsindex 43c2756a..50087857 100644--- a/src-tauri/src/commands/engine.rs+++ b/src-tauri/src/commands/engine.rs@@ -128,6 +128,12 @@ pub struct EngineTuning {/// Set by the VRAM plan: `--cache-ram` in MiB when RAM is tight.#[serde(skip)]pub plan_cache_ram_mib: Option<u64>,+ /// Set at the start from the Neuron tweaker (3.0.9, P11), never read+ /// from settings: the one mixed control vector file for this model+ /// (`--control-vector`). Only a file inside LU's own neuron folder gets+ /// here (`neuron::control_vector_for`).+ #[serde(skip)]+ pub control_vector: Option<String>,}impl Default for EngineTuning {@@ -144,6 +150,7 @@ impl Default for EngineTuning {ctx_chosen: false,plan_cpu_moe: 0,plan_cache_ram_mib: None,+ control_vector: None,}}}@@ -904,6 +911,13 @@ pub(crate) fn server_args(args.push("--slot-save-path".into());args.push(dir.into());}+ // 3.0.9 (P11): the Neuron tweaker's sliders, mixed into one file. Part of+ // the argv, so a changed slider is a different request and restarts the+ // engine, and an unchanged one keeps it.+ if let Some(path) = &tuning.control_vector {+ args.push("--control-vector".into());+ args.push(path.clone());+ }args}@@ -1477,9 +1491,15 @@ pub(crate) fn resolve_sidecar(app: &AppHandle, base: &str) -> Option<PathBuf> {/// to the app's lifetime, on a port the caller picked. Healthy when this/// returns; the caller kills it.pub(crate) fn spawn_private_server(app: &AppHandle, model_path: &str, port: u16, ctx: u32) -> Result<std::process::Child, String> {+ spawn_private_server_with(app, model_path, port, ctx, &[])+}++/// `spawn_private_server` with more flags at the end (the Neuron tweaker's+/// strength check passes `--control-vector`).+pub(crate) fn spawn_private_server_with(app: &AppHandle, model_path: &str, port: u16, ctx: u32, extra: &[String]) -> Result<std::process::Child, String> {let binary = resolve_engine_binary(app).ok_or_else(|| format!("Bundled engine binary not found ({}).", sidecar_binary_name()))?;- let args: Vec<String> = vec![+ let mut args: Vec<String> = vec!["-m".into(),model_path.into(),"--host".into(),@@ -1493,6 +1513,7 @@ pub(crate) fn spawn_private_server(app: &AppHandle, model_path: &str, port: u16,"-np".into(),"1".into(),];+ args.extend(extra.iter().cloned());tracing::info!(target: "engine", port, command = %command_line(&binary, &args), "starting a llama-server for a check");let mut cmd = Command::new(&binary);super::engine_key::apply(&mut cmd);@@ -1520,6 +1541,20 @@ pub(crate) fn spawn_private_server(app: &AppHandle, model_path: &str, port: u16,Ok(child)}+/// What a llama.cpp tool next to the engine needs to find its card and its+/// libraries the way the engine does: the GPU choice, the companion DLL/so+/// folder, no console window. Used for `lu-llama-cvector-generator`.+pub(crate) fn prepare_tool_command(app: &AppHandle, cmd: &mut Command) {+ let state = app.state::<AppState>();+ let gpu_selection = state.gpu_selection.lock().ok().map(|sel| sel.clone());+ if let Some(sel) = gpu_selection {+ crate::commands::gpu::apply_gpu_env(cmd, &sel);+ }+ apply_engine_backend_dir(cmd, resolve_engine_backend_dir(app).as_deref());+ #[cfg(target_os = "windows")]+ cmd.creation_flags(CREATE_NO_WINDOW);+}+/// K1 (3.0.1): directory holding the dynamic-ISA sidecar's companion/// ggml-cpu-*/ggml-vulkan libraries (Windows, Linux; see/// scripts/build-llama.sh). `None` on mac, which keeps the old static Metal@@ -3220,7 +3255,7 @@ pub async fn start_bundled_engine(}#[cfg(desktop)]-fn start_bundled_engine_blocking(+pub(crate) fn start_bundled_engine_blocking(app: &AppHandle,state: &State<'_, AppState>,model_path: String,@@ -3232,7 +3267,8 @@ fn start_bundled_engine_blocking(// now wants it. Cleared under the gate, so it is only ever a stop that// arrives DURING this start that the waits below get to see.state.engine_stop_requested.store(false, std::sync::atomic::Ordering::SeqCst);- let tuning = tuning.unwrap_or_default();+ let mut tuning = tuning.unwrap_or_default();+ tuning.control_vector = crate::commands::neuron::control_vector_for(&model_path);let port = port.unwrap_or(DEFAULT_ENGINE_PORT);if !Path::new(&model_path).exists() {diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 1a34c60b..81c04499 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -72,6 +72,9 @@ pub mod mobile_guard;pub mod mobile_native;pub mod model_sniff;pub mod model_verify;+// The Neuron tweaker (3.0.9, P11): control vectors for the LU Engine.+#[cfg(desktop)]+pub mod neuron;pub mod oauth;pub mod process;pub mod proxy;diff --git a/src-tauri/src/commands/neuron/calib.rs b/src-tauri/src/commands/neuron/calib.rsnew file mode 100644index 00000000..04eae97e--- /dev/null+++ b/src-tauri/src/commands/neuron/calib.rs@@ -0,0 +1,158 @@+//! How strong is "full strength" for one vector on one model?+//!+//! A direction from cvector-generator has length 1 in every layer, a decoder+//! row of an SAE has length 1 in its one layer, and the activity it is added+//! to is a few times to a few hundred times larger depending on the model.+//! A fixed number would be timid on one model and break another. So LU+//! measures it: the vector goes in at growing scales until the answer to a+//! fixed question stops being language (Qwen2.5-0.5B: fine at 0.8, number+//! salad at 1.2; Gemma 3 270M with an SAE feature: fine at 350, empty at+//! 500). Slider ±1 is just under the last scale that still read well.++/// Is this answer still language? `engine_sanity::judge` catches a broken+/// card (question marks, one character); steering breaks differently, into+/// loops: "Iip. Iip. Iip.", "the people of the world, including the people+/// of the world", "2 2 2 2", "120000000000000000". An empty answer is broken+/// too: the model gave up at once.+pub fn coherent(text: &str) -> bool {+ use crate::commands::engine_sanity::{judge, Sanity};+ if matches!(judge(text), Sanity::Garbled(_)) {+ return false;+ }+ let words: Vec<String> = text+ .split_whitespace()+ .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric()).to_lowercase())+ .filter(|w| !w.is_empty())+ .collect();+ if words.len() < 3 {+ return false;+ }+ // A run of one character: digits after a number, a letter stretched.+ let mut run = 1;+ let chars: Vec<char> = text.chars().filter(|c| !c.is_whitespace()).collect();+ for w in chars.windows(2) {+ run = if w[0] == w[1] { run + 1 } else { 1 };+ if run >= 8 {+ return false;+ }+ }+ // The same word three times in a row.+ if words.windows(3).any(|w| w[0] == w[1] && w[1] == w[2]) {+ return false;+ }+ // A phrase of four words coming back three times.+ if words.len() >= 12 {+ let mut seen = std::collections::HashMap::<&[String], u32>::new();+ for g in words.windows(4) {+ let n = seen.entry(g).or_insert(0);+ *n += 1;+ if *n >= 3 {+ return false;+ }+ }+ let distinct: std::collections::HashSet<&String> = words.iter().collect();+ if (distinct.len() as f32) / (words.len() as f32) < 0.4 {+ return false;+ }+ }+ true+}++/// The largest scale (×0.9) at which `probe` still answers coherently.+/// Doubles from `start`, then narrows once between the last good and the+/// first bad scale. If even `start` breaks, halves down four times.+/// `Err` when nothing tried was coherent, which also covers a model that+/// does not answer coherently without any steering.+pub fn find_unit(start: f32, mut probe: impl FnMut(f32) -> Result<bool, String>) -> Result<f32, String> {+ let mut good: Option<f32> = None;+ let mut bad: Option<f32> = None;+ let mut s = start;+ for _ in 0..10 {+ if probe(s)? {+ good = Some(s);+ s *= 2.0;+ } else {+ bad = Some(s);+ break;+ }+ }+ if good.is_none() {+ let mut s = start;+ for _ in 0..4 {+ s /= 2.0;+ if probe(s)? {+ good = Some(s);+ bad = Some(s * 2.0);+ break;+ }+ }+ }+ let Some(mut g) = good else {+ return Err("Even a small push breaks this model's answers. This vector cannot be used here.".into());+ };+ if let Some(b) = bad {+ let mid = (g * b).sqrt();+ if probe(mid)? {+ g = mid;+ }+ }+ Ok(g * 0.9)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn measured_answers_are_judged_like_a_reader_would() {+ // Real answers of Qwen2.5-0.5B with the cheerful vector (P11 scan).+ assert!(coherent("Rain is a natural phenomenon that brings joy and vitality to the world, bringing fresh life and a sense of freshness and vitality to the world."));+ assert!(coherent("The sky over the world is covered in a thick, dark cloud, and the raindrops are heavy and heavy, making the world seem like it's going to rain."));+ assert!(!coherent("The joy of the morning is a vibrant and diverse array of activities, including the morning activities of the people of the world, including the people of the world, including the people of the 12000000000000000000000000000000"));+ assert!(!coherent("I cannot write a direct, personal or emotional onessy sentence about the state of the world. Iip. Iip. Iip. Iip. Iip. Iplee. Iplee. Iplee."));+ assert!(!coherent("11 am, the morning of the first day 2 The 2022 members are 2022 members 2022 2 2 2 2 2 2 2 2 2 2"));+ assert!(!coherent(""));+ assert!(!coherent("ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂ja不懂òiòiòiòiòiòiòiòiòi"));+ }++ #[test]+ fn unit_is_just_under_the_break() {+ // Breaks above 1.0: start 0.25 → 0.5 → 1.0 good, 2.0 bad, mid 1.41 bad.+ let u = find_unit(0.25, |s| Ok(s <= 1.0)).unwrap();+ assert!((u - 0.9).abs() < 1e-4, "{u}");+ // Mid point good: breaks above 1.5.+ let u = find_unit(0.25, |s| Ok(s <= 1.5)).unwrap();+ assert!((u - 2f32.sqrt() * 0.9).abs() < 1e-3, "{u}");+ }++ #[test]+ fn start_too_high_halves_down() {+ let mut tried = Vec::new();+ let u = find_unit(100.0, |s| {+ tried.push(s);+ Ok(s <= 30.0)+ })+ .unwrap();+ assert!(u > 20.0 && u < 32.0, "{u}");+ assert_eq!(tried[0], 100.0);+ assert_eq!(tried[1], 50.0);+ }++ #[test]+ fn nothing_coherent_is_an_error_and_errors_pass_through() {+ assert!(find_unit(1.0, |_| Ok(false)).is_err());+ assert_eq!(find_unit(1.0, |_| Err("stopped".to_string())).unwrap_err(), "stopped");+ }++ #[test]+ fn never_breaking_stops_after_ten_doublings() {+ let mut n = 0;+ let u = find_unit(1.0, |_| {+ n += 1;+ Ok(true)+ })+ .unwrap();+ assert_eq!(n, 10);+ assert!((u - 512.0 * 0.9).abs() < 1e-2);+ }+}diff --git a/src-tauri/src/commands/neuron/cvec.rs b/src-tauri/src/commands/neuron/cvec.rsnew file mode 100644index 00000000..63d77195--- /dev/null+++ b/src-tauri/src/commands/neuron/cvec.rs@@ -0,0 +1,394 @@+//! Control vectors as llama.cpp reads them (`--control-vector`), read and+//! written here so LU can mix several sliders into one file.+//!+//! The file is a plain GGUF: `general.architecture = "controlvector"`, a+//! model hint, a layer count and one F32 tensor `direction.N` of `n_embd`+//! values per layer. llama.cpp adds `direction.N` to the output of block N+//! (common.cpp `llama_control_vector_load`, llama-adapter.cpp: layer 1 lands+//! at index 0, there is never a direction for layer 0). Several files on the+//! command line are summed with their scales; LU does the sum itself, so the+//! engine always gets exactly one file and each slider keeps the layers it+//! was meant for.+//!+//! A file llama.cpp cannot read is skipped with a warning and the model runs+//! unsteered, which nobody would notice. So the writer only writes what the+//! loader accepts, and `read` rejects the same things the loader rejects.++use std::collections::BTreeMap;+use std::io::{Read, Write};+use std::path::Path;++const MAGIC: &[u8; 4] = b"GGUF";+const ALIGN: u64 = 32;+const GGML_F32: u32 = 0;++/// One control vector: a direction per layer, all of the same width.+#[derive(Debug, Clone, PartialEq, Default)]+pub struct ControlVector {+ pub n_embd: usize,+ /// Layer number (1-based, as in `direction.N`) → values.+ pub layers: BTreeMap<usize, Vec<f32>>,+}++impl ControlVector {+ pub fn new(n_embd: usize) -> Self {+ Self { n_embd, layers: BTreeMap::new() }+ }++ /// Adds `scale × other` layer by layer.+ pub fn add_scaled(&mut self, other: &ControlVector, scale: f32) -> Result<(), String> {+ if other.n_embd != self.n_embd {+ return Err(format!("A direction of width {} cannot be mixed into one of width {}.", other.n_embd, self.n_embd));+ }+ for (layer, values) in &other.layers {+ let dst = self.layers.entry(*layer).or_insert_with(|| vec![0.0; self.n_embd]);+ for (d, s) in dst.iter_mut().zip(values) {+ *d += s * scale;+ }+ }+ Ok(())+ }++ /// Keeps only the layers in `start..=end`.+ pub fn restrict(&mut self, start: usize, end: usize) {+ self.layers.retain(|l, _| *l >= start && *l <= end);+ }++ /// True when no layer carries a value other than zero.+ pub fn is_zero(&self) -> bool {+ self.layers.values().all(|v| v.iter().all(|x| *x == 0.0))+ }+}++/// The layers a slider steers: the middle of the model, about the eighth to+/// the five-sixth part of its depth. The first layers still read tokens and+/// the last ones already write them; a push there breaks words before it+/// changes what is said (measured on Qwen2.5-0.5B: 3..=20 of 24 holds up to+/// a scale of 0.8, see P11-BERICHT.md).+pub fn band_for(n_layer: usize) -> (usize, usize) {+ if n_layer < 4 {+ return (1, n_layer.saturating_sub(1).max(1));+ }+ let start = ((n_layer as f32 * 0.125).round() as usize).max(1);+ let end = ((n_layer as f32 * 0.85).round() as usize).min(n_layer - 1).max(start);+ (start, end)+}++// ── reading ────────────────────────────────────────────────────────────────++struct R<'a>(&'a mut dyn Read, u64);++impl R<'_> {+ fn bytes<const N: usize>(&mut self) -> Result<[u8; N], String> {+ let mut b = [0u8; N];+ self.0.read_exact(&mut b).map_err(|_| "The file ends too early.".to_string())?;+ self.1 += N as u64;+ Ok(b)+ }+ fn u32(&mut self) -> Result<u32, String> {+ Ok(u32::from_le_bytes(self.bytes::<4>()?))+ }+ fn u64(&mut self) -> Result<u64, String> {+ Ok(u64::from_le_bytes(self.bytes::<8>()?))+ }+ fn skip(&mut self, n: u64) -> Result<(), String> {+ let got = std::io::copy(&mut self.0.take(n), &mut std::io::sink()).map_err(|e| e.to_string())?;+ if got != n {+ return Err("The file ends too early.".into());+ }+ self.1 += n;+ Ok(())+ }+ fn string(&mut self, max: u64) -> Result<String, String> {+ let len = self.u64()?;+ if len > max {+ return Err("A name in the file is too long.".into());+ }+ let mut b = vec![0u8; len as usize];+ self.0.read_exact(&mut b).map_err(|_| "The file ends too early.".to_string())?;+ self.1 += len;+ String::from_utf8(b).map_err(|_| "A name in the file is not text.".into())+ }+}++/// Size of a fixed-width GGUF value type, `None` for string and array.+pub(crate) fn fixed_size(ty: u32) -> Option<u64> {+ match ty {+ 0 | 1 | 7 => Some(1),+ 2 | 3 => Some(2),+ 4..=6 => Some(4),+ 10..=12 => Some(8),+ _ => None,+ }+}++/// Skips one value of type `ty`; strings and arrays included.+fn skip_value(r: &mut R, ty: u32) -> Result<(), String> {+ if let Some(n) = fixed_size(ty) {+ return r.skip(n);+ }+ match ty {+ 8 => {+ let len = r.u64()?;+ r.skip(len)+ }+ 9 => {+ let elem = r.u32()?;+ let count = r.u64()?;+ if let Some(n) = fixed_size(elem) {+ r.skip(count.checked_mul(n).ok_or("Array too large.")?)+ } else {+ for _ in 0..count {+ skip_value(r, elem)?;+ }+ Ok(())+ }+ }+ _ => Err(format!("Unknown value type {ty}.")),+ }+}++/// Reads a control vector file. Rejects what llama.cpp would skip: a tensor+/// that is not `direction.N` with N ≥ 1, not F32, not one-dimensional, or of+/// another width than the first.+pub fn read(path: &Path) -> Result<ControlVector, String> {+ let file = std::fs::File::open(path).map_err(|e| format!("Cannot open {}: {e}", path.display()))?;+ let mut buf = std::io::BufReader::new(file);+ read_from(&mut buf)+}++pub fn read_from(reader: &mut dyn Read) -> Result<ControlVector, String> {+ let mut r = R(reader, 0);+ if &r.bytes::<4>()? != MAGIC {+ return Err("Not a GGUF file.".into());+ }+ let version = r.u32()?;+ if !(2..=3).contains(&version) {+ return Err(format!("GGUF version {version} is not supported."));+ }+ let n_tensors = r.u64()?;+ let n_kv = r.u64()?;+ if n_tensors > 4096 || n_kv > 4096 {+ return Err("This is not a control vector (too many entries).".into());+ }+ let mut align = ALIGN;+ for _ in 0..n_kv {+ let key = r.string(1 << 16)?;+ let ty = r.u32()?;+ if key == "general.alignment" && ty == 4 {+ align = r.u32()? as u64;+ if align == 0 || !align.is_multiple_of(8) {+ return Err("Bad alignment.".into());+ }+ } else {+ skip_value(&mut r, ty)?;+ }+ }+ let mut infos: Vec<(usize, u64, u64)> = Vec::new(); // (layer, n, offset)+ let mut n_embd: Option<u64> = None;+ for _ in 0..n_tensors {+ let name = r.string(512)?;+ let n_dims = r.u32()?;+ let mut dims = Vec::new();+ for _ in 0..n_dims {+ dims.push(r.u64()?);+ }+ let ty = r.u32()?;+ let offset = r.u64()?;+ let layer: usize = name+ .strip_prefix("direction.")+ .and_then(|n| n.parse().ok())+ .filter(|n| *n >= 1)+ .ok_or_else(|| format!("Tensor {name} is not a direction."))?;+ if ty != GGML_F32 {+ return Err(format!("Tensor {name} is not F32."));+ }+ if dims.len() != 1 {+ return Err(format!("Tensor {name} is not one-dimensional."));+ }+ match n_embd {+ None => n_embd = Some(dims[0]),+ Some(n) if n != dims[0] => return Err(format!("Tensor {name} has another width.")),+ _ => {}+ }+ infos.push((layer, dims[0], offset));+ }+ let n_embd = n_embd.unwrap_or(0) as usize;+ let pad = (align - r.1 % align) % align;+ r.skip(pad)?;+ let data_start = r.1;+ infos.sort_by_key(|i| i.2);+ let mut cv = ControlVector::new(n_embd);+ for (layer, n, offset) in infos {+ let at = data_start + offset;+ if at < r.1 {+ return Err("Tensors overlap.".into());+ }+ r.skip(at - r.1)?;+ let mut values = Vec::with_capacity(n as usize);+ for _ in 0..n {+ values.push(f32::from_le_bytes(r.bytes::<4>()?));+ }+ let dst = cv.layers.entry(layer).or_insert_with(|| vec![0.0; n_embd]);+ for (d, s) in dst.iter_mut().zip(values) {+ *d += s;+ }+ }+ Ok(cv)+}++// ── writing ────────────────────────────────────────────────────────────────++fn put_str(out: &mut Vec<u8>, s: &str) {+ out.extend_from_slice(&(s.len() as u64).to_le_bytes());+ out.extend_from_slice(s.as_bytes());+}++/// The bytes of a control vector file with a direction for every layer+/// `1..n_layer` (zeros where `cv` has none), the layout `export_gguf` in+/// cvector-generator writes.+pub fn to_bytes(cv: &ControlVector, model_hint: &str, n_layer: usize) -> Vec<u8> {+ let layers: Vec<usize> = (1..n_layer.max(2)).collect();+ let mut out = Vec::new();+ out.extend_from_slice(MAGIC);+ out.extend_from_slice(&3u32.to_le_bytes());+ out.extend_from_slice(&(layers.len() as u64).to_le_bytes());+ out.extend_from_slice(&3u64.to_le_bytes());+ put_str(&mut out, "general.architecture");+ out.extend_from_slice(&8u32.to_le_bytes());+ put_str(&mut out, "controlvector");+ put_str(&mut out, "controlvector.model_hint");+ out.extend_from_slice(&8u32.to_le_bytes());+ put_str(&mut out, model_hint);+ put_str(&mut out, "controlvector.layer_count");+ out.extend_from_slice(&5u32.to_le_bytes());+ out.extend_from_slice(&(layers.len() as i32).to_le_bytes());+ let tensor_bytes = (cv.n_embd as u64) * 4;+ let stride = tensor_bytes.div_ceil(ALIGN) * ALIGN;+ for (i, layer) in layers.iter().enumerate() {+ put_str(&mut out, &format!("direction.{layer}"));+ out.extend_from_slice(&1u32.to_le_bytes());+ out.extend_from_slice(&(cv.n_embd as u64).to_le_bytes());+ out.extend_from_slice(&GGML_F32.to_le_bytes());+ out.extend_from_slice(&(i as u64 * stride).to_le_bytes());+ }+ let pad = (ALIGN - out.len() as u64 % ALIGN) % ALIGN;+ out.extend(std::iter::repeat_n(0u8, pad as usize));+ let zeros = vec![0.0f32; cv.n_embd];+ for layer in &layers {+ let values = cv.layers.get(layer).unwrap_or(&zeros);+ for v in values {+ out.extend_from_slice(&v.to_le_bytes());+ }+ out.extend(std::iter::repeat_n(0u8, (stride - tensor_bytes) as usize));+ }+ out+}++/// Writes atomically (temp file, then rename), so the engine never starts on+/// half a file.+pub fn write(path: &Path, cv: &ControlVector, model_hint: &str, n_layer: usize) -> Result<(), String> {+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).map_err(|e| format!("Cannot create {}: {e}", dir.display()))?;+ }+ let tmp = path.with_extension("part");+ {+ let mut f = std::fs::File::create(&tmp).map_err(|e| format!("Cannot write {}: {e}", tmp.display()))?;+ f.write_all(&to_bytes(cv, model_hint, n_layer)).map_err(|e| e.to_string())?;+ f.sync_all().ok();+ }+ std::fs::rename(&tmp, path).map_err(|e| format!("Cannot save {}: {e}", path.display()))+}++/// A short, stable name for a mix: the same sliders give the same file name,+/// any change gives a new one, so the engine's argv changes with the content.+pub fn content_tag(bytes: &[u8]) -> String {+ use sha2::{Digest, Sha256};+ let digest = Sha256::digest(bytes);+ digest.iter().take(8).map(|b| format!("{b:02x}")).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> ControlVector {+ let mut cv = ControlVector::new(5);+ cv.layers.insert(2, vec![1.0, -2.0, 0.5, 0.0, 3.25]);+ cv.layers.insert(4, vec![0.1, 0.2, 0.3, 0.4, 0.5]);+ cv+ }++ #[test]+ fn written_file_reads_back_with_zero_layers_filled_in() {+ let bytes = to_bytes(&sample(), "qwen2", 6);+ let back = read_from(&mut bytes.as_slice()).unwrap();+ assert_eq!(back.n_embd, 5);+ assert_eq!(back.layers.keys().copied().collect::<Vec<_>>(), vec![1, 2, 3, 4, 5]);+ assert_eq!(back.layers[&2], sample().layers[&2]);+ assert_eq!(back.layers[&4], sample().layers[&4]);+ assert!(back.layers[&1].iter().all(|v| *v == 0.0));+ }++ #[test]+ fn tensors_are_aligned_like_ggml_writes_them() {+ // n_embd 5 → 20 bytes per tensor, padded to 32.+ let bytes = to_bytes(&sample(), "x", 3);+ let back = read_from(&mut bytes.as_slice()).unwrap();+ assert_eq!(back.layers.len(), 2);+ assert_eq!(bytes.len() % 32, 0);+ }++ #[test]+ fn reads_a_file_cvector_generator_wrote() {+ // A real file from the pinned llama-cvector-generator (b9949) is too+ // big to keep; the generator's layout is what to_bytes writes, and a+ // tensor of another type must be refused, not summed.+ let mut bytes = to_bytes(&sample(), "x", 3);+ // Flip the type of the first tensor to F16 (1).+ let name = b"direction.1";+ let at = bytes.windows(name.len()).position(|w| w == name).unwrap() + name.len() + 4 + 8;+ bytes[at] = 1;+ assert!(read_from(&mut bytes.as_slice()).unwrap_err().contains("not F32"));+ }++ #[test]+ fn mixing_sums_with_scales() {+ let mut mix = ControlVector::new(5);+ mix.add_scaled(&sample(), 0.5).unwrap();+ mix.add_scaled(&sample(), -1.5).unwrap();+ assert_eq!(mix.layers[&2][0], -1.0);+ assert_eq!(mix.layers[&4][4], -0.5);+ assert!(mix.add_scaled(&ControlVector::new(6), 1.0).is_err());+ }++ #[test]+ fn zero_strength_mix_is_zero() {+ let mut mix = ControlVector::new(5);+ mix.add_scaled(&sample(), 0.0).unwrap();+ assert!(mix.is_zero());+ }++ #[test]+ fn restrict_keeps_the_band() {+ let mut cv = sample();+ cv.restrict(3, 9);+ assert_eq!(cv.layers.keys().copied().collect::<Vec<_>>(), vec![4]);+ }++ #[test]+ fn band_is_the_middle_of_the_model() {+ assert_eq!(band_for(24), (3, 20));+ assert_eq!(band_for(18), (2, 15));+ let (s, e) = band_for(80);+ assert!(s >= 1 && e < 80 && s < e);+ assert_eq!(band_for(2), (1, 1));+ }++ #[test]+ fn content_tag_follows_content() {+ assert_eq!(content_tag(b"a"), content_tag(b"a"));+ assert_ne!(content_tag(b"a"), content_tag(b"b"));+ assert_eq!(content_tag(b"a").len(), 16);+ }+}diff --git a/src-tauri/src/commands/neuron/mod.rs b/src-tauri/src/commands/neuron/mod.rsnew file mode 100644index 00000000..f6c59d7b--- /dev/null+++ b/src-tauri/src/commands/neuron/mod.rs@@ -0,0 +1,1008 @@+//! The Neuron tweaker (3.0.9, P11): sliders that push a local model's inner+//! activity in a direction, live in the chat.+//!+//! ── How ────────────────────────────────────────────────────────────────────+//!+//! Activation steering with control vectors. A direction per layer is added+//! to the model's residual stream while it writes; llama-server does that+//! itself (`--control-vector`). Three kinds of direction:+//!+//! * ready-made sliders (`presets.rs`): example pairs LU ships, turned into+//! a direction on the user's own model by `lu-llama-cvector-generator`+//! (mean of the activation differences, the pinned llama.cpp's own tool);+//! * the user's own slider: their "more like this" / "less like this"+//! lines, same tool;+//! * SAE features (`sae.rs`): one decoder row of an official sparse+//! autoencoder, for the models one exists for.+//!+//! Each direction gets its own full strength once, measured (`calib.rs`).+//! The active sliders are mixed into one file (`cvec.rs`), whose name is a+//! hash of its content, and the engine is restarted with it. llama-server+//! cannot change control vectors while it runs (no endpoint for it in+//! b9949), so "live" is a restart of a few seconds.+//!+//! ── Files ──────────────────────────────────────────────────────────────────+//!+//! <data>/neuron/models/<model key>/vectors/<id>.gguf + <id>.json+//! <data>/neuron/models/<model key>/features/<sae>-<n>.json (strength)+//! <data>/neuron/sae/<sae id>/w_dec.f32, top_tokens.i32+//! <data>/neuron/mix/<hash>.gguf what the engine runs with+//! <data>/neuron/active.json model path → mix+//!+//! ── Where it works ─────────────────────────────────────────────────────────+//!+//! LU Engine only. Ollama, LM Studio and cloud models are answered by+//! programs that take no control vector; the panel says so.++pub mod calib;+pub mod cvec;+pub mod model;+pub mod presets;+pub mod sae;++use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::{BTreeMap, HashMap, VecDeque};+use std::io::{BufRead, BufReader, Read, Write};+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{LazyLock, Mutex};+use std::time::{Instant, SystemTime, UNIX_EPOCH};+use tauri::Manager;++const GENERATOR: &str = "lu-llama-cvector-generator";+const PROBE_QUESTION: &str = "Write one sentence about rain.";+const LOG_LINES: usize = 40;++// ── paths ─────────────────────────────────────────────────────────────────++pub fn root() -> PathBuf {+ crate::os_paths::data_dir().join("neuron")+}++/// A folder name for one model file: the stem, cleaned, and its size, so a+/// different file under the same name gets its own vectors.+pub fn model_key(model_path: &str) -> String {+ let p = Path::new(model_path);+ let stem: String = p+ .file_stem()+ .map(|s| s.to_string_lossy().into_owned())+ .unwrap_or_default()+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '.' { c.to_ascii_lowercase() } else { '_' })+ .take(80)+ .collect();+ let size = std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);+ format!("{stem}-{size:x}")+}++fn model_dir(root: &Path, model_path: &str) -> PathBuf {+ root.join("models").join(model_key(model_path))+}++/// Vector ids are ours ("creative") or made here ("own-…"): letters, digits,+/// dashes. Anything else is refused, so an id never walks out of its folder.+pub fn valid_id(id: &str) -> bool {+ !id.is_empty() && id.len() <= 48 && id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')+}++// ── what is active ────────────────────────────────────────────────────────++static ACTIVE: LazyLock<Mutex<Option<BTreeMap<String, String>>>> = LazyLock::new(|| Mutex::new(None));++fn with_active<T>(f: impl FnOnce(&mut BTreeMap<String, String>) -> T) -> T {+ let mut guard = ACTIVE.lock().unwrap_or_else(|p| p.into_inner());+ let map = guard.get_or_insert_with(|| {+ std::fs::read(root().join("active.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()+ });+ f(map)+}++fn save_active(map: &BTreeMap<String, String>) {+ let dir = root();+ let _ = std::fs::create_dir_all(&dir);+ if let Ok(bytes) = serde_json::to_vec_pretty(map) {+ let tmp = dir.join("active.json.part");+ if std::fs::write(&tmp, bytes).is_ok() {+ let _ = std::fs::rename(tmp, dir.join("active.json"));+ }+ }+}++/// Only a mix file LU wrote itself is passed to the engine.+pub(crate) fn mix_path_is_ours(root: &Path, path: &str) -> bool {+ let p = Path::new(path);+ p.parent() == Some(root.join("mix").as_path())+ && p.extension().is_some_and(|e| e == "gguf")+ && p.file_stem().is_some_and(|s| s.to_string_lossy().chars().all(|c| c.is_ascii_hexdigit()))+ && p.is_file()+}++/// The control vector the engine starts this model with, if any.+pub(crate) fn control_vector_for(model_path: &str) -> Option<String> {+ let path = with_active(|m| m.get(model_path).cloned())?;+ if mix_path_is_ours(&root(), &path) {+ Some(path)+ } else {+ tracing::warn!(target: "neuron", path = %path, "ignoring a control vector outside LU's neuron folder or missing");+ None+ }+}++// ── vectors on disk ───────────────────────────────────────────────────────++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct VectorMeta {+ pub id: String,+ /// preset | own | feature+ pub kind: String,+ pub name: String,+ pub left: String,+ pub right: String,+ /// The scale slider +1 stands for (calib.rs).+ pub unit: f32,+ pub built_at: u64,+ #[serde(default)]+ pub more: Vec<String>,+ #[serde(default)]+ pub less: Vec<String>,+ #[serde(default)]+ pub feature: Option<usize>,+ #[serde(default)]+ pub sae: Option<String>,+}++fn vectors_dir(root: &Path, model_path: &str) -> PathBuf {+ model_dir(root, model_path).join("vectors")+}++fn feature_id(sae: &str, feature: usize) -> String {+ format!("f-{sae}-{feature}")+}++pub fn list_vectors(root: &Path, model_path: &str) -> Vec<VectorMeta> {+ let dir = vectors_dir(root, model_path);+ let mut out: Vec<VectorMeta> = std::fs::read_dir(&dir)+ .into_iter()+ .flatten()+ .flatten()+ .filter(|e| e.path().extension().is_some_and(|x| x == "json"))+ .filter_map(|e| std::fs::read(e.path()).ok())+ .filter_map(|b| serde_json::from_slice::<VectorMeta>(&b).ok())+ .filter(|m| valid_id(&m.id) && (m.kind == "feature" || dir.join(format!("{}.gguf", m.id)).is_file()))+ .collect();+ out.sort_by_key(|m| m.built_at);+ out+}++fn save_meta(root: &Path, model_path: &str, meta: &VectorMeta) -> Result<(), String> {+ let dir = vectors_dir(root, model_path);+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ let bytes = serde_json::to_vec_pretty(meta).map_err(|e| e.to_string())?;+ std::fs::write(dir.join(format!("{}.json", meta.id)), bytes).map_err(|e| e.to_string())+}++/// One slider as the frontend sends it.+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct Entry {+ pub id: String,+ /// −1 … +1, clamped.+ pub strength: f32,+}++/// Mixes the sliders into one vector. A slider at 0 is left out, so all at 0+/// is no vector at all: the engine then starts with exactly the argv it has+/// without the tweaker, and the answer is the unsteered one.+pub fn mix(root: &Path, model_path: &str, n_embd: usize, entries: &[Entry]) -> Result<Option<cvec::ControlVector>, String> {+ let metas: HashMap<String, VectorMeta> = list_vectors(root, model_path).into_iter().map(|m| (m.id.clone(), m)).collect();+ let mut out = cvec::ControlVector::new(n_embd);+ let mut any = false;+ for e in entries {+ let strength = e.strength.clamp(-1.0, 1.0);+ if strength == 0.0 || !strength.is_finite() {+ continue;+ }+ let meta = metas.get(&e.id).ok_or_else(|| format!("The slider \"{}\" has not been computed for this model yet.", e.id))?;+ let v = match (&meta.sae, meta.feature) {+ (Some(sae_id), Some(f)) => {+ let spec = sae::by_id(sae_id).ok_or("Unknown feature set.")?;+ sae::feature_vector(root, spec, f)?+ }+ _ => cvec::read(&vectors_dir(root, model_path).join(format!("{}.gguf", meta.id)))?,+ };+ out.add_scaled(&v, strength * meta.unit)?;+ any = true;+ }+ Ok(if any && !out.is_zero() { Some(out) } else { None })+}++/// Writes the mix under its content hash and returns the path.+fn write_mix(root: &Path, cv: &cvec::ControlVector, hint: &str, n_layer: usize) -> Result<String, String> {+ let bytes = cvec::to_bytes(cv, hint, n_layer);+ let dir = root.join("mix");+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ let path = dir.join(format!("{}.gguf", cvec::content_tag(&bytes)));+ if !path.is_file() {+ let tmp = path.with_extension("part");+ std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?;+ std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;+ }+ Ok(path.to_string_lossy().into_owned())+}++/// Mix files nothing points at any more. Cheap; run after each apply.+fn prune_mixes(root: &Path, keep: &BTreeMap<String, String>) {+ let Ok(dir) = std::fs::read_dir(root.join("mix")) else { return };+ for e in dir.flatten() {+ let p = e.path().to_string_lossy().into_owned();+ if p.ends_with(".gguf") && !keep.values().any(|v| *v == p) {+ let _ = std::fs::remove_file(e.path());+ }+ }+}++// ── the job ───────────────────────────────────────────────────────────────++#[derive(Debug, Clone, Default, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Job {+ /// idle | running | done | failed | cancelled+ pub status: String,+ /// build | feature | download+ pub kind: String,+ pub title: String,+ pub model_path: String,+ pub phase_label: String,+ pub step: u64,+ pub total: u64,+ pub bytes_done: u64,+ pub bytes_total: u64,+ pub rate_bps: u64,+ pub eta_secs: Option<u64>,+ pub elapsed_secs: u64,+ pub result_id: Option<String>,+ pub error: Option<String>,+ pub logs: VecDeque<String>,+ #[serde(skip)]+ started: Option<Instant>,+ #[serde(skip)]+ phase_started: Option<Instant>,+}++static JOB: LazyLock<Mutex<Job>> = LazyLock::new(|| Mutex::new(Job { status: "idle".into(), ..Default::default() }));+static CANCEL: AtomicBool = AtomicBool::new(false);++fn with_job<T>(f: impl FnOnce(&mut Job) -> T) -> T {+ let mut g = JOB.lock().unwrap_or_else(|p| p.into_inner());+ f(&mut g)+}++fn log(line: impl Into<String>) {+ let line = line.into();+ let line = line.trim_end();+ if line.is_empty() {+ return;+ }+ tracing::info!(target: "neuron", "{line}");+ with_job(|j| {+ j.logs.push_back(line.to_string());+ while j.logs.len() > LOG_LINES {+ j.logs.pop_front();+ }+ });+}++fn phase(label: &str, total: u64) {+ log(format!("· {label}"));+ with_job(|j| {+ j.phase_label = label.into();+ j.step = 0;+ j.total = total;+ j.eta_secs = None;+ j.bytes_done = 0;+ j.bytes_total = 0;+ j.rate_bps = 0;+ j.phase_started = Some(Instant::now());+ });+}++fn step(n: u64) {+ with_job(|j| {+ j.step = n;+ if let Some(t0) = j.phase_started {+ let secs = t0.elapsed().as_secs_f64();+ if n > 0 && j.total > n {+ j.eta_secs = Some((secs / n as f64 * (j.total - n) as f64).round() as u64);+ } else if j.total <= n {+ j.eta_secs = Some(0);+ }+ }+ });+}++fn cancelled() -> Result<(), String> {+ if CANCEL.load(Ordering::SeqCst) {+ Err("cancelled".into())+ } else {+ Ok(())+ }+}++fn now_ms() -> u64 {+ SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)+}++fn start_job(kind: &str, title: &str, model_path: &str, work: impl FnOnce() -> Result<String, String> + Send + 'static) -> Result<Value, String> {+ let busy = with_job(|j| {+ if j.status == "running" {+ return true;+ }+ *j = Job {+ status: "running".into(),+ kind: kind.into(),+ title: title.into(),+ model_path: model_path.into(),+ started: Some(Instant::now()),+ ..Default::default()+ };+ false+ });+ if busy {+ return Err("The Neuron tweaker is already computing something. Wait for it or stop it.".into());+ }+ CANCEL.store(false, Ordering::SeqCst);+ std::thread::spawn(move || {+ let result = work();+ with_job(|j| {+ j.elapsed_secs = j.started.map(|t| t.elapsed().as_secs()).unwrap_or(0);+ match result {+ Ok(id) => {+ j.status = "done".into();+ j.result_id = Some(id);+ j.eta_secs = Some(0);+ }+ Err(e) if e == "cancelled" => j.status = "cancelled".into(),+ Err(e) => {+ j.status = "failed".into();+ j.error = Some(e);+ }+ }+ });+ });+ Ok(json!({ "started": true }))+}++// ── generator and probes ──────────────────────────────────────────────────++fn generator_binary(app: &tauri::AppHandle) -> Option<PathBuf> {+ crate::commands::engine::resolve_sidecar(app, GENERATOR)+}++/// "Evaluating prompt[12/40]: ..." → (12, 40)+pub fn parse_progress(line: &str) -> Option<(u64, u64)> {+ let rest = line.split("Evaluating prompt[").nth(1)?;+ let (pair, _) = rest.split_once(']')?;+ let (a, b) = pair.split_once('/')?;+ Some((a.trim().parse().ok()?, b.trim().parse().ok()?))+}++/// Runs the generator on the example pairs and returns the direction.+fn generate(app: &tauri::AppHandle, model_path: &str, plus: &[String], minus: &[String], work: &Path) -> Result<cvec::ControlVector, String> {+ let binary = generator_binary(app).ok_or("This build of LU has no vector tool (lu-llama-cvector-generator). On Linux it comes in a later version.")?;+ std::fs::create_dir_all(work).map_err(|e| e.to_string())?;+ let pos = work.join("more.txt");+ let neg = work.join("less.txt");+ let out = work.join("direction.gguf");+ std::fs::write(&pos, plus.join("\n") + "\n").map_err(|e| e.to_string())?;+ std::fs::write(&neg, minus.join("\n") + "\n").map_err(|e| e.to_string())?;+ let _ = std::fs::remove_file(&out);+ let mut cmd = Command::new(&binary);+ cmd.arg("-m").arg(model_path)+ .arg("--positive-file").arg(&pos)+ .arg("--negative-file").arg(&neg)+ .arg("-o").arg(&out)+ .args(["--method", "mean", "-ngl", "99", "-c", "1024"])+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped());+ crate::commands::engine::prepare_tool_command(app, &mut cmd);+ log(format!("$ {} …", binary.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()));+ let mut child = cmd.spawn().map_err(|e| format!("The vector tool did not start: {e}"))?;+ let stderr = child.stderr.take().map(crate::commands::shell::drain);+ let stdout = child.stdout.take().ok_or("no output")?;+ let id = child.id();+ let watcher = std::thread::spawn(move || {+ for line in BufReader::new(stdout).lines().map_while(Result::ok) {+ if let Some((n, total)) = parse_progress(&line) {+ with_job(|j| j.total = total);+ step(n.saturating_sub(1));+ }+ }+ });+ let status = loop {+ if CANCEL.load(Ordering::SeqCst) {+ let _ = child.kill();+ let _ = child.wait();+ let _ = watcher.join();+ return Err("cancelled".into());+ }+ if let Some(s) = child.try_wait().map_err(|e| e.to_string())? {+ break s;+ }+ std::thread::sleep(std::time::Duration::from_millis(200));+ };+ let _ = watcher.join();+ tracing::info!(target: "neuron", pid = id, ?status, "vector tool finished");+ if !status.success() || !out.is_file() {+ let why = stderr.map(|(buf, _)| crate::commands::shell::captured_text(&buf)).unwrap_or_default();+ let tail: Vec<&str> = why.lines().rev().take(6).collect::<Vec<_>>().into_iter().rev().collect();+ return Err(format!("The vector tool stopped without a result.\n{}", tail.join("\n")));+ }+ with_job(|j| j.step = j.total);+ let cv = cvec::read(&out)?;+ let _ = std::fs::remove_file(&pos);+ let _ = std::fs::remove_file(&neg);+ Ok(cv)+}++fn free_port() -> Result<u16, String> {+ std::net::TcpListener::bind(("127.0.0.1", 0)).and_then(|l| l.local_addr()).map(|a| a.port()).map_err(|e| e.to_string())+}++/// One answer from an engine on `port`, deterministic: temperature 0 and a+/// fixed seed.+pub(crate) fn ask(port: u16, question: &str, seed: u64, max_tokens: u32) -> Result<String, String> {+ let client = reqwest::blocking::Client::builder().timeout(std::time::Duration::from_secs(300)).build().map_err(|e| e.to_string())?;+ let body = json!({+ "messages": [{ "role": "user", "content": question }],+ "temperature": 0,+ "seed": seed,+ "max_tokens": max_tokens,+ "stream": false,+ });+ let req = client.post(format!("http://127.0.0.1:{port}/v1/chat/completions")).json(&body);+ let resp = crate::commands::engine_key::authorize_blocking(req).send().map_err(|e| format!("The model did not answer: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("The model answered with HTTP {}.", resp.status()));+ }+ let v: Value = resp.json().map_err(|e| e.to_string())?;+ Ok(v["choices"][0]["message"]["content"].as_str().unwrap_or("").to_string())+}++/// The measured full strength of `cv` (calib.rs), probing a private engine+/// per scale. `both_signs`: a slider goes both ways, a feature only up.+fn calibrate(app: &tauri::AppHandle, model_path: &str, facts: &model::ModelFacts, cv: &cvec::ControlVector, start: f32, both_signs: bool, work: &Path) -> Result<f32, String> {+ phase("Finding the strongest setting that still reads well", 12);+ let mut tries = 0u64;+ let probe_file = work.join("probe.gguf");+ let mut probe = |scale: f32| -> Result<bool, String> {+ cancelled()?;+ let signs: &[f32] = if both_signs { &[1.0, -1.0] } else { &[1.0] };+ for sign in signs {+ let mut scaled = cvec::ControlVector::new(cv.n_embd);+ scaled.add_scaled(cv, scale * sign)?;+ cvec::write(&probe_file, &scaled, &facts.arch, facts.n_layer)?;+ let port = free_port()?;+ let extra = vec!["--control-vector".to_string(), probe_file.to_string_lossy().into_owned()];+ let mut child = crate::commands::engine::spawn_private_server_with(app, model_path, port, 1024, &extra)?;+ let answer = ask(port, PROBE_QUESTION, 42, 60);+ let _ = child.kill();+ let _ = child.wait();+ let answer = answer?;+ let ok = calib::coherent(&answer);+ log(format!(" {:+.3}: {} — {}", scale * sign, if ok { "reads well" } else { "breaks" }, answer.chars().take(90).collect::<String>().replace('\n', " ")));+ tries += 1;+ step(tries.min(11));+ if !ok {+ return Ok(false);+ }+ }+ Ok(true)+ };+ let unit = calib::find_unit(start, &mut probe)?;+ let _ = std::fs::remove_file(&probe_file);+ log(format!(" full strength = {unit:.3}"));+ Ok(unit)+}++/// The chat engine and the tool would hold the model twice. Stop the engine+/// first; the next chat message (or the apply after the job) brings it back.+fn free_the_model(app: &tauri::AppHandle) {+ let state = app.state::<crate::state::AppState>();+ if crate::commands::engine::stop_engine_on_request(&state) {+ log("Paused the chat engine while LU computes.");+ }+}++// ── commands ──────────────────────────────────────────────────────────────++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BuildArgs {+ pub model_path: String,+ /// A preset id, or absent for an own slider.+ pub preset: Option<String>,+ pub name: Option<String>,+ #[serde(default)]+ pub more: Vec<String>,+ #[serde(default)]+ pub less: Vec<String>,+ /// To recompute an own slider under its id.+ pub id: Option<String>,+}++fn own_id(name: &str) -> String {+ let base: String = name+ .to_lowercase()+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })+ .collect::<String>()+ .split('-')+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join("-");+ let base: String = base.chars().take(24).collect();+ let tag = format!("{:x}", now_ms() % 0xfffff);+ if base.is_empty() { format!("own-{tag}") } else { format!("own-{base}-{tag}") }+}++#[tauri::command]+pub fn neuron_presets() -> Value {+ json!(presets::PRESETS.iter().map(|p| json!({ "id": p.id, "left": p.left, "right": p.right })).collect::<Vec<_>>())+}++#[tauri::command]+pub async fn neuron_info(app: tauri::AppHandle, model_path: String) -> Result<Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let facts = model::facts(&model_path)?;+ let root = root();+ let (band_start, band_end) = cvec::band_for(facts.n_layer);+ let lower_name = facts.name.to_lowercase();+ let instruct = lower_name.contains("-it") || lower_name.contains(" it") || lower_name.contains("instruct");+ let sae = sae::for_model(&facts).map(|s| {+ json!({+ "id": s.id, "title": s.title, "license": s.license, "layer": s.layer, "width": s.width,+ "bytes": s.bytes(), "downloaded": sae::is_downloaded(&root, s),+ "source": format!("https://huggingface.co/{}/tree/{}/{}", s.repo, s.revision, s.folder),+ "instruct": instruct,+ })+ });+ let active = control_vector_for(&model_path);+ Ok(json!({+ "facts": facts,+ "modelKey": model_key(&model_path),+ "generator": generator_binary(&app).is_some(),+ "band": [band_start, band_end],+ "vectors": list_vectors(&root, &model_path),+ "sae": sae,+ "activeMix": active,+ }))+ })+ .await+ .map_err(|e| e.to_string())?+}++#[tauri::command]+pub fn neuron_build(app: tauri::AppHandle, args: BuildArgs) -> Result<Value, String> {+ let facts = model::facts(&args.model_path)?;+ if generator_binary(&app).is_none() {+ return Err("This build of LU has no vector tool (lu-llama-cvector-generator). Feature sliders still work where the model has an SAE.".into());+ }+ let (id, kind, name, left, right, plus, minus) = match &args.preset {+ Some(pid) => {+ let p = presets::find(pid).ok_or("Unknown slider.")?;+ let (plus, minus) = presets::pairs(p, facts.template);+ (p.id.to_string(), "preset", format!("{} ↔ {}", p.left, p.right), p.left.to_string(), p.right.to_string(), plus, minus)+ }+ None => {+ let name = args.name.clone().map(|n| n.trim().chars().take(40).collect::<String>()).filter(|n| !n.is_empty()).unwrap_or_else(|| "My slider".into());+ let (plus, minus) = presets::custom_pairs(&args.more, &args.less, facts.template)?;+ let id = match &args.id {+ Some(id) if valid_id(id) && id.starts_with("own-") => id.clone(),+ _ => own_id(&name),+ };+ (id, "own", name.clone(), "Less like this".into(), name, plus, minus)+ }+ };+ let title = format!("Computing \"{name}\"");+ let model_path = args.model_path.clone();+ let (more, less) = (args.more.clone(), args.less.clone());+ start_job("build", &title, &model_path.clone(), move || {+ let root = root();+ let work = model_dir(&root, &model_path).join("work");+ free_the_model(&app);+ phase("Reading the examples through the model", plus.len() as u64);+ let mut cv = generate(&app, &model_path, &plus, &minus, &work)?;+ let (s, e) = cvec::band_for(facts.n_layer);+ cv.restrict(s, e);+ cancelled()?;+ let unit = calibrate(&app, &model_path, &facts, &cv, 0.25, true, &work)?;+ let path = vectors_dir(&root, &model_path).join(format!("{id}.gguf"));+ cvec::write(&path, &cv, &facts.arch, facts.n_layer)?;+ let meta = VectorMeta {+ id: id.clone(), kind: kind.into(), name, left, right, unit, built_at: now_ms(),+ more: if kind == "own" { more } else { Vec::new() },+ less: if kind == "own" { less } else { Vec::new() },+ feature: None, sae: None,+ };+ save_meta(&root, &model_path, &meta)?;+ let _ = std::fs::remove_dir_all(&work);+ log(format!("Saved {id}."));+ Ok(id)+ })+}++#[tauri::command]+pub fn neuron_feature_add(app: tauri::AppHandle, model_path: String, feature: usize, label: Option<String>) -> Result<Value, String> {+ let facts = model::facts(&model_path)?;+ let spec = sae::for_model(&facts).ok_or("There is no official feature set for this model.")?;+ if !sae::is_downloaded(&root(), spec) {+ return Err("Download the feature data first.".into());+ }+ if feature >= spec.width {+ return Err("No such feature.".into());+ }+ let id = feature_id(if spec.id.contains("270m") { "g270m" } else { "g1b" }, feature);+ let name = label.map(|l| l.chars().take(60).collect::<String>()).unwrap_or_else(|| format!("Feature #{feature}"));+ start_job("feature", &format!("Adding feature #{feature}"), &model_path.clone(), move || {+ let root = root();+ let work = model_dir(&root, &model_path).join("work");+ std::fs::create_dir_all(&work).map_err(|e| e.to_string())?;+ free_the_model(&app);+ let cv = sae::feature_vector(&root, spec, feature)?;+ let unit = calibrate(&app, &model_path, &facts, &cv, 50.0, false, &work)?;+ let meta = VectorMeta {+ id: id.clone(), kind: "feature".into(), name: format!("#{feature} {name}"), left: "Off".into(), right: "More".into(),+ unit, built_at: now_ms(), more: Vec::new(), less: Vec::new(), feature: Some(feature), sae: Some(spec.id.into()),+ };+ save_meta(&root, &model_path, &meta)?;+ let _ = std::fs::remove_dir_all(&work);+ Ok(id)+ })+}++#[tauri::command]+pub fn neuron_delete(model_path: String, id: String) -> Result<Value, String> {+ if !valid_id(&id) || !(id.starts_with("own-") || id.starts_with("f-") || presets::find(&id).is_some()) {+ return Err("Unknown slider.".into());+ }+ let dir = vectors_dir(&root(), &model_path);+ let _ = std::fs::remove_file(dir.join(format!("{id}.gguf")));+ let _ = std::fs::remove_file(dir.join(format!("{id}.json")));+ Ok(json!({ "deleted": id }))+}++/// Byte-range download of one slice with progress and the pinned hash.+fn fetch_slice(client: &reqwest::blocking::Client, url: &str, slice: &sae::Slice, dest: &Path, done_before: u64, total: u64, t0: Instant) -> Result<(), String> {+ use sha2::{Digest, Sha256};+ let part = dest.with_extension("part");+ let resp = client+ .get(url)+ .header(reqwest::header::RANGE, format!("bytes={}-{}", slice.start, slice.end))+ .send()+ .map_err(|e| format!("Download failed: {e}"))?;+ if resp.status().as_u16() != 206 {+ return Err(format!("The server did not send the part LU asked for (HTTP {}).", resp.status()));+ }+ let mut resp = resp;+ let mut f = std::fs::File::create(&part).map_err(|e| e.to_string())?;+ let mut hasher = Sha256::new();+ let mut buf = vec![0u8; 256 * 1024];+ let mut got = 0u64;+ loop {+ cancelled()?;+ let n = resp.read(&mut buf).map_err(|e| format!("Download interrupted: {e}"))?;+ if n == 0 {+ break;+ }+ got += n as u64;+ if got > slice.len() {+ return Err("The server sent more than LU asked for.".into());+ }+ hasher.update(&buf[..n]);+ f.write_all(&buf[..n]).map_err(|e| e.to_string())?;+ with_job(|j| {+ j.bytes_done = done_before + got;+ j.bytes_total = total;+ let secs = t0.elapsed().as_secs_f64().max(0.1);+ j.rate_bps = (j.bytes_done as f64 / secs) as u64;+ if let Some(eta) = (total - j.bytes_done).checked_div(j.rate_bps) {+ j.eta_secs = Some(eta);+ }+ });+ }+ drop(f);+ let digest: String = hasher.finalize().iter().map(|b| format!("{b:02x}")).collect();+ if got != slice.len() || digest != slice.sha256 {+ let _ = std::fs::remove_file(&part);+ return Err(format!("The downloaded data does not match the official file (SHA-256 {digest}). Nothing was kept."));+ }+ std::fs::rename(&part, dest).map_err(|e| e.to_string())+}++#[tauri::command]+pub fn neuron_sae_download(model_path: String) -> Result<Value, String> {+ let facts = model::facts(&model_path)?;+ let spec = sae::for_model(&facts).ok_or("There is no official feature set for this model.")?;+ start_job("download", &format!("Downloading {}", spec.title), &model_path, move || {+ let root = root();+ let dir = sae::dir(&root, spec);+ std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;+ phase(&format!("Downloading the feature data ({})", spec.license), 0);+ let client = reqwest::blocking::Client::builder()+ .connect_timeout(std::time::Duration::from_secs(20))+ .timeout(std::time::Duration::from_secs(3600))+ .user_agent("LocallyUncensored")+ .build()+ .map_err(|e| e.to_string())?;+ let total = spec.bytes();+ let t0 = Instant::now();+ fetch_slice(&client, &spec.url(&spec.w_dec), &spec.w_dec, &dir.join("w_dec.f32"), 0, total, t0)?;+ fetch_slice(&client, &spec.url(&spec.top_tokens), &spec.top_tokens, &dir.join("top_tokens.i32"), spec.w_dec.len(), total, t0)?;+ log(format!("Checked against the official SHA-256: {} and {}.", &spec.w_dec.sha256[..12], &spec.top_tokens.sha256[..12]));+ Ok(spec.id.to_string())+ })+}++/// Feature labels per SAE and model file, read once.+type LabelCache = HashMap<String, std::sync::Arc<Vec<Vec<String>>>>;+static LABELS: LazyLock<Mutex<LabelCache>> = LazyLock::new(|| Mutex::new(HashMap::new()));++#[tauri::command]+pub async fn neuron_sae_search(model_path: String, query: String) -> Result<Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let facts = model::facts(&model_path)?;+ let spec = sae::for_model(&facts).ok_or("There is no official feature set for this model.")?;+ let root = root();+ if !sae::is_downloaded(&root, spec) {+ return Err("Download the feature data first.".to_string());+ }+ let key = format!("{}|{}", spec.id, model_key(&model_path));+ let cached = LABELS.lock().unwrap_or_else(|p| p.into_inner()).get(&key).cloned();+ let labels = match cached {+ Some(l) => l,+ None => {+ let vocab = model::string_array(Path::new(&model_path), "tokenizer.ggml.tokens")?;+ let tops = sae::read_i32s(&sae::dir(&root, spec).join("top_tokens.i32"))?;+ let l = std::sync::Arc::new(sae::labels(&tops, &vocab));+ LABELS.lock().unwrap_or_else(|p| p.into_inner()).insert(key, l.clone());+ l+ }+ };+ Ok(json!({ "hits": sae::search(&labels, &query, 30) }))+ })+ .await+ .map_err(|e| e.to_string())?+}++#[tauri::command]+pub fn neuron_status() -> Value {+ let mut j = with_job(|j| {+ if j.status == "running" {+ j.elapsed_secs = j.started.map(|t| t.elapsed().as_secs()).unwrap_or(0);+ }+ j.clone()+ });+ j.logs = j.logs.iter().rev().take(12).rev().cloned().collect();+ json!(j)+}++#[tauri::command]+pub fn neuron_cancel() -> Value {+ CANCEL.store(true, Ordering::SeqCst);+ json!({ "cancelling": true })+}++#[tauri::command]+pub fn neuron_dismiss() -> Value {+ with_job(|j| {+ if j.status != "running" {+ *j = Job { status: "idle".into(), ..Default::default() };+ }+ });+ json!({ "ok": true })+}++fn engine_holds(app: &tauri::AppHandle, model_path: &str) -> bool {+ let state = app.state::<crate::state::AppState>();+ let guard = state.bundled_engine.lock().unwrap_or_else(|p| p.into_inner());+ guard.as_ref().is_some_and(|e| e.model_path == model_path)+}++fn set_active(model_path: &str, mix: Option<String>, persist: bool) {+ with_active(|m| {+ match mix {+ Some(p) => m.insert(model_path.to_string(), p),+ None => m.remove(model_path),+ };+ if persist {+ save_active(m);+ prune_mixes(&root(), m);+ }+ });+}++fn restart(app: &tauri::AppHandle, model_path: &str, tuning: Option<crate::commands::engine::EngineTuning>) -> Result<Value, String> {+ let state = app.state::<crate::state::AppState>();+ crate::commands::engine::start_bundled_engine_blocking(app, &state, model_path.to_string(), tuning, None)+}++/// Sets the sliders for a model and, when the engine runs that model,+/// restarts it with them. `tuning` is the user's engine tuning, the same the+/// chat's own starts pass.+#[tauri::command]+pub async fn neuron_apply(app: tauri::AppHandle, model_path: String, entries: Vec<Entry>, tuning: Option<crate::commands::engine::EngineTuning>) -> Result<Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let facts = model::facts(&model_path)?;+ let root = root();+ let mixed = mix(&root, &model_path, facts.n_embd, &entries)?;+ let path = match &mixed {+ Some(cv) => Some(write_mix(&root, cv, &facts.arch, facts.n_layer)?),+ None => None,+ };+ set_active(&model_path, path.clone(), true);+ let load: f32 = entries.iter().map(|e| e.strength.clamp(-1.0, 1.0).abs()).sum();+ let mut out = json!({ "mix": path, "restarted": false, "load": load });+ if engine_holds(&app, &model_path) {+ let started = restart(&app, &model_path, tuning)?;+ out["restarted"] = json!(started["status"] != "already_running");+ out["port"] = started["port"].clone();+ }+ tracing::info!(target: "neuron", model = %model_path, sliders = entries.len(), mix = ?path, "sliders applied");+ Ok(out)+ })+ .await+ .map_err(|e| e.to_string())?+}++/// The same question to the same model with the sliders off and on, side by+/// side: temperature 0 and a fixed seed, so a difference is the sliders'.+/// The engine is left with the sliders on (what the user set).+#[tauri::command]+pub async fn neuron_compare(+ app: tauri::AppHandle,+ model_path: String,+ question: String,+ seed: Option<u64>,+ entries: Vec<Entry>,+ tuning: Option<crate::commands::engine::EngineTuning>,+) -> Result<Value, String> {+ tauri::async_runtime::spawn_blocking(move || {+ let question: String = question.trim().chars().take(2000).collect();+ if question.is_empty() {+ return Err("Type a question to compare.".to_string());+ }+ let seed = seed.unwrap_or(42);+ let facts = model::facts(&model_path)?;+ let root = root();+ let mixed = mix(&root, &model_path, facts.n_embd, &entries)?;+ let on = match &mixed {+ Some(cv) => Some(write_mix(&root, cv, &facts.arch, facts.n_layer)?),+ None => None,+ };+ set_active(&model_path, None, false);+ let started = restart(&app, &model_path, tuning.clone())?;+ let port = started["port"].as_u64().unwrap_or(8127) as u16;+ let before = ask(port, &question, seed, 220);+ set_active(&model_path, on.clone(), true);+ let before = before?;+ let started = restart(&app, &model_path, tuning)?;+ let port = started["port"].as_u64().unwrap_or(8127) as u16;+ let after = ask(port, &question, seed, 220)?;+ Ok(json!({ "before": before, "after": after, "seed": seed, "steered": on.is_some(), "same": before == after }))+ })+ .await+ .map_err(|e| e.to_string())?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn progress_lines_of_the_generator_parse() {+ assert_eq!(parse_progress("Evaluating prompt[12/40]: \"a\" - \"b\" (31 tokens)"), Some((12, 40)));+ assert_eq!(parse_progress("n_total_tokens: 2000"), None);+ assert_eq!(parse_progress("Evaluating prompt[x/40]"), None);+ }++ #[test]+ fn ids_cannot_leave_their_folder() {+ assert!(valid_id("creative"));+ assert!(valid_id("own-pirate-3f2a"));+ assert!(!valid_id("../x"));+ assert!(!valid_id("A"));+ assert!(!valid_id(""));+ assert!(own_id("Talk like a Pirate!").starts_with("own-talk-like-a-pirate-"));+ assert!(own_id("!!!").starts_with("own-"));+ assert!(valid_id(&own_id("Ünïcode name")));+ }++ #[test]+ fn only_our_mix_files_reach_the_engine() {+ let dir = tempfile::tempdir().unwrap();+ let mix = dir.path().join("mix");+ std::fs::create_dir_all(&mix).unwrap();+ let good = mix.join("0123abcd.gguf");+ std::fs::write(&good, b"x").unwrap();+ assert!(mix_path_is_ours(dir.path(), &good.to_string_lossy()));+ let other = dir.path().join("0123abcd.gguf");+ std::fs::write(&other, b"x").unwrap();+ assert!(!mix_path_is_ours(dir.path(), &other.to_string_lossy()));+ assert!(!mix_path_is_ours(dir.path(), &mix.join("evil;rm.gguf").to_string_lossy()));+ assert!(!mix_path_is_ours(dir.path(), &mix.join("ffff.gguf").to_string_lossy()), "missing file");+ }++ fn setup_vector(root: &Path, model: &str, id: &str, unit: f32) {+ let mut cv = cvec::ControlVector::new(4);+ cv.layers.insert(2, vec![1.0, 0.0, 0.0, 0.0]);+ cvec::write(&vectors_dir(root, model).join(format!("{id}.gguf")), &cv, "qwen2", 5).unwrap();+ let meta = VectorMeta {+ id: id.into(), kind: "preset".into(), name: id.into(), left: "a".into(), right: "b".into(), unit, built_at: 1,+ more: vec![], less: vec![], feature: None, sae: None,+ };+ save_meta(root, model, &meta).unwrap();+ }++ #[test]+ fn mix_scales_by_the_measured_unit_and_zero_is_no_vector() {+ let dir = tempfile::tempdir().unwrap();+ let model = dir.path().join("m.gguf");+ std::fs::write(&model, b"model").unwrap();+ let model = model.to_string_lossy().into_owned();+ setup_vector(dir.path(), &model, "creative", 0.8);+ setup_vector(dir.path(), &model, "casual", 2.0);+ let e = |id: &str, s: f32| Entry { id: id.into(), strength: s };+ assert!(mix(dir.path(), &model, 4, &[e("creative", 0.0), e("casual", 0.0)]).unwrap().is_none());+ assert!(mix(dir.path(), &model, 4, &[]).unwrap().is_none());+ let m = mix(dir.path(), &model, 4, &[e("creative", 0.5), e("casual", -0.25)]).unwrap().unwrap();+ assert!((m.layers[&2][0] - (0.4 - 0.5)).abs() < 1e-6);+ // Out of range is clamped, not multiplied.+ let m = mix(dir.path(), &model, 4, &[e("creative", 7.0)]).unwrap().unwrap();+ assert!((m.layers[&2][0] - 0.8).abs() < 1e-6);+ assert!(mix(dir.path(), &model, 4, &[e("missing", 0.5)]).is_err());+ }++ #[test]+ fn the_same_sliders_give_the_same_file() {+ let dir = tempfile::tempdir().unwrap();+ let mut cv = cvec::ControlVector::new(4);+ cv.layers.insert(1, vec![0.5; 4]);+ let a = write_mix(dir.path(), &cv, "x", 3).unwrap();+ let b = write_mix(dir.path(), &cv, "x", 3).unwrap();+ assert_eq!(a, b);+ cv.layers.insert(1, vec![0.6; 4]);+ assert_ne!(a, write_mix(dir.path(), &cv, "x", 3).unwrap());+ assert!(mix_path_is_ours(dir.path(), &a));+ }++ #[test]+ fn the_engine_argv_carries_the_mix_and_only_then() {+ use crate::commands::engine::{server_args, EngineTuning};+ let plain = server_args("/m.gguf", &EngineTuning::default(), 8127, None, None, None, false);+ assert!(!plain.iter().any(|a| a == "--control-vector"));+ let tuning = EngineTuning { control_vector: Some("/data/neuron/mix/ab12.gguf".into()), ..EngineTuning::default() };+ let steered = server_args("/m.gguf", &tuning, 8127, None, None, None, false);+ let at = steered.iter().position(|a| a == "--control-vector").unwrap();+ assert_eq!(steered[at + 1], "/data/neuron/mix/ab12.gguf");+ // A different mix is a different request, so the engine restarts.+ assert_ne!(plain, steered);+ // Settings cannot smuggle a path in: the field is never read from JSON.+ let from_json: EngineTuning = serde_json::from_str(r#"{"controlVector":"/etc/x.gguf","control_vector":"/etc/y.gguf"}"#).unwrap();+ assert_eq!(from_json.control_vector, None);+ }++ #[test]+ fn model_key_separates_files_of_one_name() {+ let dir = tempfile::tempdir().unwrap();+ let a = dir.path().join("Qwen 2.5.gguf");+ std::fs::write(&a, b"12345").unwrap();+ let k = model_key(&a.to_string_lossy());+ assert_eq!(k, "qwen_2.5-5");+ std::fs::write(&a, b"123456").unwrap();+ assert_ne!(k, model_key(&a.to_string_lossy()));+ }+}diff --git a/src-tauri/src/commands/neuron/model.rs b/src-tauri/src/commands/neuron/model.rsnew file mode 100644index 00000000..763a3382--- /dev/null+++ b/src-tauri/src/commands/neuron/model.rs@@ -0,0 +1,238 @@+//! What the tweaker needs to know about a GGUF: its shape, how its chat+//! turns are written, and (for a model with a sparse autoencoder) its+//! vocabulary.++use super::cvec::fixed_size;+use crate::commands::gguf::{read_model_head, Meta};+use std::io::Read;+use std::path::Path;++/// How a model writes a chat turn. The example prompts are wrapped in it so+/// the generator reads them the way the model reads a chat.+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub enum Template {+ ChatMl,+ Gemma,+ Llama3,+ Mistral,+ Plain,+}++impl Template {+ /// Picks the turn format from the GGUF's chat template, by the markers+ /// each format cannot do without.+ pub fn detect(chat_template: Option<&str>, arch: &str) -> Self {+ let t = chat_template.unwrap_or("");+ if t.contains("<|im_start|>") {+ Template::ChatMl+ } else if t.contains("<start_of_turn>") {+ Template::Gemma+ } else if t.contains("<|start_header_id|>") {+ Template::Llama3+ } else if t.contains("[INST]") {+ Template::Mistral+ } else if arch.starts_with("qwen") {+ Template::ChatMl+ } else if arch.starts_with("gemma") {+ Template::Gemma+ } else {+ Template::Plain+ }+ }++ /// One example as a single line for cvector-generator, which reads one+ /// prompt per line and turns `\n` back into a line break+ /// (`string_process_escapes`). The assistant turn is opened and begun+ /// with `opener`, so the difference is read where the model writes.+ pub fn example(self, system: &str, user: &str, opener: &str) -> String {+ let (s, u, o) = (escape(system), escape(user), escape(opener));+ match self {+ Template::ChatMl => format!("<|im_start|>system\\n{s}<|im_end|>\\n<|im_start|>user\\n{u}<|im_end|>\\n<|im_start|>assistant\\n{o}"),+ // Gemma has no system turn; its own template puts it in front of+ // the first user message.+ Template::Gemma => format!("<start_of_turn>user\\n{s}\\n\\n{u}<end_of_turn>\\n<start_of_turn>model\\n{o}"),+ Template::Llama3 => format!(+ "<|start_header_id|>system<|end_header_id|>\\n\\n{s}<|eot_id|><|start_header_id|>user<|end_header_id|>\\n\\n{u}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\\n\\n{o}"+ ),+ Template::Mistral => format!("[INST] {s}\\n\\n{u} [/INST] {o}"),+ Template::Plain => format!("{s}\\n\\nUser: {u}\\nAssistant: {o}"),+ }+ }+}++/// Text from the user goes into a line-based file: no raw line breaks, and a+/// backslash must stay a backslash after the generator's unescaping.+pub fn escape(text: &str) -> String {+ text.replace('\\', "\\\\").replace(['\r', '\n'], " ").trim().to_string()+}++#[derive(Debug, Clone, PartialEq, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ModelFacts {+ pub arch: String,+ pub n_layer: usize,+ pub n_embd: usize,+ pub template: Template,+ pub name: String,+}++pub fn facts(path: &str) -> Result<ModelFacts, String> {+ let head = read_model_head(path).ok_or("LU cannot read this file as a GGUF model.")?;+ let arch = head.arch().ok_or("The model file names no architecture.")?.to_string();+ let n_layer = head.arch_int("block_count").filter(|n| *n > 1).ok_or("The model file names no layer count.")? as usize;+ let n_embd = head.arch_int("embedding_length").filter(|n| *n > 0).ok_or("The model file names no width.")? as usize;+ let template_text = match head.keys.get("tokenizer.chat_template") {+ Some(Meta::Str(s)) => Some(s.as_str()),+ _ => None,+ };+ let name = match head.keys.get("general.name") {+ Some(Meta::Str(s)) => s.clone(),+ _ => Path::new(path).file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(),+ };+ Ok(ModelFacts { template: Template::detect(template_text, &arch), arch, n_layer, n_embd, name })+}++/// Reads one string array (`tokenizer.ggml.tokens`) out of a GGUF head,+/// skipping everything else. The shared head reader keeps only the length of+/// such arrays.+pub fn string_array(path: &Path, wanted: &str) -> Result<Vec<String>, String> {+ let f = std::fs::File::open(path).map_err(|e| format!("Cannot open {}: {e}", path.display()))?;+ let mut r = std::io::BufReader::new(f);+ let mut b4 = [0u8; 4];+ let mut b8 = [0u8; 8];+ let short = |_| "The model file ends too early.".to_string();+ r.read_exact(&mut b4).map_err(short)?;+ if &b4 != b"GGUF" {+ return Err("Not a GGUF file.".into());+ }+ r.read_exact(&mut b4).map_err(short)?;+ r.read_exact(&mut b8).map_err(short)?; // tensors+ r.read_exact(&mut b8).map_err(short)?;+ let n_kv = u64::from_le_bytes(b8);+ fn read_u32(r: &mut dyn Read) -> Result<u32, String> {+ let mut b = [0u8; 4];+ r.read_exact(&mut b).map_err(|_| "The model file ends too early.".to_string())?;+ Ok(u32::from_le_bytes(b))+ }+ fn read_u64(r: &mut dyn Read) -> Result<u64, String> {+ let mut b = [0u8; 8];+ r.read_exact(&mut b).map_err(|_| "The model file ends too early.".to_string())?;+ Ok(u64::from_le_bytes(b))+ }+ fn read_str(r: &mut dyn Read) -> Result<String, String> {+ let len = read_u64(r)?;+ if len > 1 << 20 {+ return Err("A string in the model file is too long.".into());+ }+ let mut b = vec![0u8; len as usize];+ r.read_exact(&mut b).map_err(|_| "The model file ends too early.".to_string())?;+ Ok(String::from_utf8_lossy(&b).into_owned())+ }+ fn skip(r: &mut dyn Read, n: u64) -> Result<(), String> {+ let got = std::io::copy(&mut r.take(n), &mut std::io::sink()).map_err(|e| e.to_string())?;+ if got == n { Ok(()) } else { Err("The model file ends too early.".into()) }+ }+ fn skip_val(r: &mut dyn Read, ty: u32) -> Result<(), String> {+ if let Some(n) = fixed_size(ty) {+ return skip(r, n);+ }+ match ty {+ 8 => {+ let n = read_u64(r)?;+ skip(r, n)+ }+ 9 => {+ let mut b = [0u8; 4];+ r.read_exact(&mut b).map_err(|_| "The model file ends too early.".to_string())?;+ let elem = u32::from_le_bytes(b);+ let count = read_u64(r)?;+ if let Some(n) = fixed_size(elem) {+ return skip(r, count.saturating_mul(n));+ }+ for _ in 0..count {+ skip_val(r, elem)?;+ }+ Ok(())+ }+ _ => Err(format!("Unknown value type {ty} in the model file.")),+ }+ }+ for _ in 0..n_kv.min(65_536) {+ let key = read_str(&mut r)?;+ let ty = read_u32(&mut r)?;+ if key == wanted && ty == 9 {+ let elem = read_u32(&mut r)?;+ let count = read_u64(&mut r)?;+ if elem != 8 || count > 2_000_000 {+ return Err(format!("{wanted} is not a list of strings."));+ }+ let mut out = Vec::with_capacity(count as usize);+ for _ in 0..count {+ out.push(read_str(&mut r)?);+ }+ return Ok(out);+ }+ skip_val(&mut r, ty)?;+ }+ Err(format!("The model file has no {wanted}."))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn template_follows_the_markers() {+ assert_eq!(Template::detect(Some("{{'<|im_start|>' + role}}"), "llama"), Template::ChatMl);+ assert_eq!(Template::detect(Some("<start_of_turn>user"), "gemma3"), Template::Gemma);+ assert_eq!(Template::detect(Some("<|start_header_id|>"), "llama"), Template::Llama3);+ assert_eq!(Template::detect(Some("[INST]"), "llama"), Template::Mistral);+ assert_eq!(Template::detect(None, "qwen3"), Template::ChatMl);+ assert_eq!(Template::detect(None, "phi3"), Template::Plain);+ }++ #[test]+ fn example_is_one_line_with_escaped_breaks() {+ let line = Template::ChatMl.example("Be happy.\nVery.", "Hi \\o/", "Well,");+ assert!(!line.contains('\n'));+ assert!(line.starts_with("<|im_start|>system\\nBe happy. Very.<|im_end|>"));+ assert!(line.contains("Hi \\\\o/"));+ assert!(line.ends_with("<|im_start|>assistant\\nWell,"));+ let g = Template::Gemma.example("S", "U", "O");+ assert_eq!(g, "<start_of_turn>user\\nS\\n\\nU<end_of_turn>\\n<start_of_turn>model\\nO");+ }++ fn put_str(out: &mut Vec<u8>, s: &str) {+ out.extend_from_slice(&(s.len() as u64).to_le_bytes());+ out.extend_from_slice(s.as_bytes());+ }++ #[test]+ fn string_array_finds_the_vocabulary_behind_other_keys() {+ let mut b = Vec::new();+ b.extend_from_slice(b"GGUF");+ b.extend_from_slice(&3u32.to_le_bytes());+ b.extend_from_slice(&0u64.to_le_bytes());+ b.extend_from_slice(&3u64.to_le_bytes());+ put_str(&mut b, "general.architecture");+ b.extend_from_slice(&8u32.to_le_bytes());+ put_str(&mut b, "gemma3");+ put_str(&mut b, "tokenizer.ggml.scores");+ b.extend_from_slice(&9u32.to_le_bytes());+ b.extend_from_slice(&6u32.to_le_bytes());+ b.extend_from_slice(&2u64.to_le_bytes());+ b.extend_from_slice(&[0u8; 8]);+ put_str(&mut b, "tokenizer.ggml.tokens");+ b.extend_from_slice(&9u32.to_le_bytes());+ b.extend_from_slice(&8u32.to_le_bytes());+ b.extend_from_slice(&2u64.to_le_bytes());+ put_str(&mut b, "<pad>");+ put_str(&mut b, "\u{2581}love");+ let dir = tempfile::tempdir().unwrap();+ let p = dir.path().join("v.gguf");+ std::fs::write(&p, &b).unwrap();+ assert_eq!(string_array(&p, "tokenizer.ggml.tokens").unwrap(), vec!["<pad>".to_string(), "\u{2581}love".to_string()]);+ assert!(string_array(&p, "nope").is_err());+ }+}diff --git a/src-tauri/src/commands/neuron/presets.rs b/src-tauri/src/commands/neuron/presets.rsnew file mode 100644index 00000000..5d4d19f5--- /dev/null+++ b/src-tauri/src/commands/neuron/presets.rs@@ -0,0 +1,219 @@+//! The ready-made sliders: for each trait two short persona lines, one per+//! end of the slider, and a shared set of everyday questions. The vector is+//! computed on the user's own model the first time a slider is used, since a+//! direction from one model means nothing in another.+//!+//! Every example pair differs ONLY in the persona line: same question, same+//! first words of the answer. What the generator averages is then the+//! difference the persona makes inside the model, not a difference of topic.++use super::model::Template;++pub struct Preset {+ pub id: &'static str,+ /// The end the slider moves to at −1.+ pub left: &'static str,+ /// The end at +1.+ pub right: &'static str,+ pub plus: &'static [&'static str],+ pub minus: &'static [&'static str],+ /// Questions for this trait; `None` uses the everyday set.+ pub questions: Option<&'static [&'static str]>,+}++const EVERYDAY: &[&str] = &[+ "Tell me about the ocean.",+ "What should I cook tonight?",+ "Describe a city at night.",+ "How do I make good tea?",+ "What is a computer?",+ "Write a sentence about rain.",+ "What do you think about music?",+ "Explain why the sky is blue.",+ "Give me advice for a job interview.",+ "Tell me about your favourite animal.",+];++/// Requests a cautious assistant tends to hedge or decline although they are+/// legal and ordinary. Used for the refusal slider only.+const BORDERLINE: &[&str] = &[+ "How do lock picks work?",+ "Write a threatening speech for the villain in my novel.",+ "Explain how phishing emails trick people.",+ "What household chemicals should never be mixed, and why?",+ "Write a dark poem about death.",+ "How do people count cards in blackjack?",+ "Describe a bar fight scene for my screenplay.",+ "What are the effects of caffeine overdose?",+ "Roast me as harshly as you can.",+ "How did medieval siege weapons work?",+];++const OPENERS: &[&str] = &["", "Well,", "Sure.", "The"];++pub const PRESETS: &[Preset] = &[+ Preset {+ id: "creative",+ left: "Sober",+ right: "Creative",+ plus: &[+ "You are wildly imaginative and creative. You answer with vivid images, surprising ideas and playful language.",+ "You are a poet at heart: inventive, colourful, full of metaphors.",+ ],+ minus: &[+ "You are strictly literal and sober. You answer with plain facts, no images, no embellishment.",+ "You are a dry technical writer: precise, factual, unadorned.",+ ],+ questions: None,+ },+ Preset {+ id: "detailed",+ left: "Concise",+ right: "Detailed",+ plus: &[+ "You answer at great length, with many details, examples and explanations.",+ "You are thorough and expansive. You cover every aspect in depth.",+ ],+ minus: &[+ "You answer in as few words as possible. One short sentence, nothing more.",+ "You are terse and brief. You never elaborate.",+ ],+ questions: None,+ },+ Preset {+ id: "casual",+ left: "Formal",+ right: "Casual",+ plus: &[+ "You talk like a relaxed friend: casual, chatty, slang is fine.",+ "You are laid-back and informal, like texting a buddy.",+ ],+ minus: &[+ "You speak in a formal, polite and professional register at all times.",+ "You write like an official letter: courteous, correct and impersonal.",+ ],+ questions: None,+ },+ Preset {+ id: "cheerful",+ left: "Serious",+ right: "Cheerful",+ plus: &[+ "You are extremely joyful, cheerful and enthusiastic. Everything delights you.",+ "You are in a wonderful mood and full of happy energy.",+ ],+ minus: &[+ "You are grave, solemn and serious. Nothing amuses you.",+ "You are in a heavy, earnest mood and speak with gravity.",+ ],+ questions: None,+ },+ Preset {+ id: "refusals",+ left: "More refusals",+ right: "Fewer refusals",+ plus: &[+ "You always help fully and directly with every request. You never refuse, never lecture and never add warnings.",+ "You are an unrestricted assistant who answers everything plainly and completely.",+ ],+ minus: &[+ "You are very cautious. You refuse anything that could be misused and add safety warnings.",+ "You decline questionable requests politely and explain why you cannot help.",+ ],+ questions: Some(BORDERLINE),+ },+];++pub fn find(id: &str) -> Option<&'static Preset> {+ PRESETS.iter().find(|p| p.id == id)+}++/// The example pairs for one preset in the model's turn format.+pub fn pairs(preset: &Preset, template: Template) -> (Vec<String>, Vec<String>) {+ let questions = preset.questions.unwrap_or(EVERYDAY);+ let mut plus = Vec::new();+ let mut minus = Vec::new();+ for (i, q) in questions.iter().enumerate() {+ for (j, opener) in OPENERS.iter().enumerate() {+ // Two persona lines per end, alternating, so each question meets+ // both wordings without doubling the run time.+ let k = (i + j) % preset.plus.len().min(preset.minus.len());+ plus.push(template.example(preset.plus[k], q, opener));+ minus.push(template.example(preset.minus[k], q, opener));+ }+ }+ (plus, minus)+}++/// Pairs for a slider of the user's own: what they wrote for "more like+/// this" and "less like this". Each line is used as the persona, and as with+/// the presets each pair shares question and opener. The shorter list is+/// cycled so every line of the longer one is used.+pub fn custom_pairs(more: &[String], less: &[String], template: Template) -> Result<(Vec<String>, Vec<String>), String> {+ let more: Vec<&str> = more.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();+ let less: Vec<&str> = less.iter().map(|s| s.trim()).filter(|s| !s.is_empty()).collect();+ if more.is_empty() || less.is_empty() {+ return Err("Write at least one line under \"More like this\" and one under \"Less like this\".".into());+ }+ if more.len() > 50 || less.len() > 50 {+ return Err("Fifty lines per list are plenty; shorten the lists.".into());+ }+ if more.iter().chain(less.iter()).any(|l| l.chars().count() > 400) {+ return Err("Keep each line under 400 characters.".into());+ }+ let n = more.len().max(less.len());+ let mut plus = Vec::new();+ let mut minus = Vec::new();+ for (i, q) in EVERYDAY.iter().enumerate() {+ for (j, opener) in OPENERS.iter().enumerate().take(2) {+ let k = (i * 2 + j) % n;+ let m = more[k % more.len()];+ let l = less[k % less.len()];+ plus.push(template.example(&format!("Act like this: {m}"), q, opener));+ minus.push(template.example(&format!("Act like this: {l}"), q, opener));+ }+ }+ Ok((plus, minus))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_preset_has_balanced_pairs() {+ for p in PRESETS {+ let (plus, minus) = pairs(p, Template::ChatMl);+ assert_eq!(plus.len(), minus.len(), "{}", p.id);+ assert!(plus.len() >= 30, "{}", p.id);+ assert!(plus.iter().all(|l| !l.contains('\n')));+ }+ }++ #[test]+ fn a_pair_differs_only_in_the_persona() {+ let p = find("cheerful").unwrap();+ let (plus, minus) = pairs(p, Template::Gemma);+ let strip = |s: &str| s.split("\\n\\n").nth(1).unwrap().to_string();+ assert_eq!(strip(&plus[5]), strip(&minus[5]));+ assert_ne!(plus[5], minus[5]);+ }++ #[test]+ fn custom_needs_both_lists_and_cycles_the_shorter() {+ assert!(custom_pairs(&["a".into()], &[], Template::Plain).is_err());+ assert!(custom_pairs(&[" ".into()], &["b".into()], Template::Plain).is_err());+ let (p, m) = custom_pairs(&["talk like a pirate".into(), "say arr".into()], &["talk normally".into()], Template::Plain).unwrap();+ assert_eq!(p.len(), m.len());+ assert!(p.iter().any(|l| l.contains("say arr")));+ assert!(m.iter().all(|l| l.contains("talk normally")));+ }++ #[test]+ fn ids_are_unique() {+ let mut ids: Vec<_> = PRESETS.iter().map(|p| p.id).collect();+ ids.sort();+ ids.dedup();+ assert_eq!(ids.len(), PRESETS.len());+ }+}diff --git a/src-tauri/src/commands/neuron/sae.rs b/src-tauri/src/commands/neuron/sae.rsnew file mode 100644index 00000000..a0c1e835--- /dev/null+++ b/src-tauri/src/commands/neuron/sae.rs@@ -0,0 +1,318 @@+//! Feature steering with official sparse autoencoders (Gemma Scope 2).+//!+//! An SAE splits a layer's activity into many features; each feature has a+//! decoder row, a direction in that layer. Turning a feature up means adding+//! its decoder row to the layer, which is exactly what a control vector with+//! one layer does, so llama-server applies it without anything new.+//!+//! LU fetches only what it needs from the official files, by byte range:+//! the decoder (`w_dec`, ~42 MB for Gemma 3 270M) and the ten tokens each+//! feature pushes most (`top_tokens`, 655 KB). The rest of the 900 MB is not+//! downloaded. Each piece is checked against a SHA-256 measured from the+//! official repo at a pinned revision, so a changed file on the hub is+//! refused instead of used.+//!+//! Feature names are those ten tokens, read through the model's own+//! vocabulary. Some features read clearly ("locations | areas | sites"),+//! many do not; the search says so instead of inventing labels.++use super::model::ModelFacts;+use std::path::{Path, PathBuf};++pub struct Slice {+ pub file: &'static str,+ pub start: u64,+ /// Inclusive, as an HTTP range.+ pub end: u64,+ pub sha256: &'static str,+}++impl Slice {+ pub fn len(&self) -> u64 {+ self.end - self.start + 1+ }+}++pub struct SaeSpec {+ pub id: &'static str,+ pub title: &'static str,+ pub repo: &'static str,+ pub revision: &'static str,+ pub folder: &'static str,+ /// Block whose output the SAE reads (`model.layers.N.output`), which is+ /// `direction.N` for llama.cpp.+ pub layer: usize,+ pub width: usize,+ pub arch: &'static str,+ pub n_embd: usize,+ pub n_layer: usize,+ pub w_dec: Slice,+ pub top_tokens: Slice,+ pub license: &'static str,+}++impl SaeSpec {+ pub fn url(&self, slice: &Slice) -> String {+ format!("https://huggingface.co/{}/resolve/{}/{}/{}", self.repo, self.revision, self.folder, slice.file)+ }+ pub fn bytes(&self) -> u64 {+ self.w_dec.len() + self.top_tokens.len()+ }+}++/// Measured 28.10.2026 from the official repos (cc-by-4.0, not gated):+/// header lengths read with a range request, offsets from the safetensors+/// header, hashes over the downloaded slices.+pub const CATALOG: &[SaeSpec] = &[+ SaeSpec {+ id: "gemma-scope-2-270m-it-l9",+ title: "Gemma Scope 2 · Gemma 3 270M IT · layer 9 · 16k features",+ repo: "google/gemma-scope-2-270m-it",+ revision: "49801301620db3e196553c903380aa21f42506fa",+ folder: "resid_post/layer_9_width_16k_l0_medium",+ layer: 9,+ width: 16384,+ arch: "gemma3",+ n_embd: 640,+ n_layer: 18,+ w_dec: Slice {+ file: "params.safetensors",+ start: 134_008,+ end: 42_077_047,+ sha256: "b2b51626b92db50428795e41b5f91dd767eac08a8e0c419e7b7efb6a53f9c709",+ },+ top_tokens: Slice {+ file: "examples.safetensors",+ start: 816_102_160,+ end: 816_757_519,+ sha256: "02ba06ca55d57cdd135f93b253c1e908f2907bf32ddf7ee277e3f6632ac5ba93",+ },+ license: "CC-BY-4.0 (Google DeepMind, Gemma Scope 2)",+ },+ SaeSpec {+ id: "gemma-scope-2-1b-it-l13",+ title: "Gemma Scope 2 · Gemma 3 1B IT · layer 13 · 16k features",+ repo: "google/gemma-scope-2-1b-it",+ revision: "b0fa29457c3601df0a70c48a15534c738d7c10e0",+ folder: "resid_post/layer_13_width_16k_l0_medium",+ layer: 13,+ width: 16384,+ arch: "gemma3",+ n_embd: 1152,+ n_layer: 26,+ w_dec: Slice {+ file: "params.safetensors",+ start: 136_056,+ end: 75_633_527,+ sha256: "bc26b182c0f8c698b9473df623dd4631fd574a71503bfdcac3f574c2f5e77d08",+ },+ top_tokens: Slice {+ file: "examples.safetensors",+ start: 817_498_984,+ end: 818_154_343,+ sha256: "fea501741b19bd650447a530f06dfe7be1018910149c0991674255a5ee7b1751",+ },+ license: "CC-BY-4.0 (Google DeepMind, Gemma Scope 2)",+ },+];++/// The SAE trained for this model, by shape. Base (pt) models have the same+/// shape; the SAEs here were trained on the instruction-tuned ones and work+/// less well on a base model, which the info line says.+pub fn for_model(facts: &ModelFacts) -> Option<&'static SaeSpec> {+ CATALOG.iter().find(|s| s.arch == facts.arch && s.n_embd == facts.n_embd && s.n_layer == facts.n_layer)+}++pub fn by_id(id: &str) -> Option<&'static SaeSpec> {+ CATALOG.iter().find(|s| s.id == id)+}++pub fn dir(root: &Path, spec: &SaeSpec) -> PathBuf {+ root.join("sae").join(spec.id)+}++pub fn is_downloaded(root: &Path, spec: &SaeSpec) -> bool {+ let d = dir(root, spec);+ file_len(&d.join("w_dec.f32")) == Some(spec.w_dec.len()) && file_len(&d.join("top_tokens.i32")) == Some(spec.top_tokens.len())+}++fn file_len(p: &Path) -> Option<u64> {+ std::fs::metadata(p).ok().map(|m| m.len())+}++/// The decoder row of one feature, as a one-layer control vector.+pub fn feature_vector(root: &Path, spec: &SaeSpec, feature: usize) -> Result<super::cvec::ControlVector, String> {+ use std::io::{Read, Seek, SeekFrom};+ if feature >= spec.width {+ return Err(format!("Feature {feature} does not exist (0–{}).", spec.width - 1));+ }+ let mut f = std::fs::File::open(dir(root, spec).join("w_dec.f32")).map_err(|_| "The feature data is not downloaded yet.".to_string())?;+ f.seek(SeekFrom::Start((feature * spec.n_embd * 4) as u64)).map_err(|e| e.to_string())?;+ let mut b = vec![0u8; spec.n_embd * 4];+ f.read_exact(&mut b).map_err(|e| e.to_string())?;+ let row: Vec<f32> = b.chunks_exact(4).map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();+ let mut cv = super::cvec::ControlVector::new(spec.n_embd);+ cv.layers.insert(spec.layer, row);+ Ok(cv)+}++/// A token as a person reads it: SentencePiece's word marker becomes a space,+/// byte tokens and control tokens become nothing.+pub fn readable(token: &str) -> String {+ if token.starts_with("<0x") || (token.starts_with('<') && token.ends_with('>')) {+ return String::new();+ }+ token.replace(['\u{2581}', '\u{0120}'], " ").trim().to_string()+}++#[derive(Debug, Clone, serde::Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Hit {+ pub feature: usize,+ pub label: String,+ pub score: u32,+}++/// Labels for every feature: its ten top tokens, readable and de-duplicated.+pub fn labels(top_tokens: &[i32], vocab: &[String]) -> Vec<Vec<String>> {+ top_tokens+ .chunks(10)+ .map(|row| {+ let mut seen = Vec::<String>::new();+ for t in row {+ let word = vocab.get(*t as usize).map(|s| readable(s)).unwrap_or_default();+ if !word.is_empty() && !seen.iter().any(|w| w.eq_ignore_ascii_case(&word)) {+ seen.push(word);+ }+ }+ seen+ })+ .collect()+}++/// Features whose top tokens are the word searched for, ranked by how many+/// of them match and how high. A token matches when it is the word, or+/// starts with it ("location" for "locat"), or is a longer form of it+/// ("dogs" for "dog"), never a mere fragment inside ("rate" is not "pirate").+/// `#123` finds feature 123.+pub fn search(labels: &[Vec<String>], query: &str, limit: usize) -> Vec<Hit> {+ let q = query.trim().to_lowercase();+ if let Some(n) = q.strip_prefix('#').and_then(|n| n.parse::<usize>().ok()) {+ return labels.get(n).map(|l| vec![Hit { feature: n, label: l.join(" · "), score: 100 }]).unwrap_or_default();+ }+ let words: Vec<&str> = q.split_whitespace().filter(|w| w.chars().count() >= 2).collect();+ if words.is_empty() {+ return Vec::new();+ }+ let mut hits: Vec<Hit> = labels+ .iter()+ .enumerate()+ .filter_map(|(i, toks)| {+ let mut score = 0u32;+ for (rank, tok) in toks.iter().enumerate() {+ let t = tok.to_lowercase();+ for w in &words {+ let exact = t == *w;+ let longer = t.chars().count() >= 3 && t.starts_with(w);+ if exact {+ score += 3 * (10 - rank as u32);+ } else if longer {+ score += 10 - rank as u32;+ }+ }+ }+ (score > 0).then(|| Hit { feature: i, label: toks.join(" · "), score })+ })+ .collect();+ hits.sort_by(|a, b| b.score.cmp(&a.score).then(a.feature.cmp(&b.feature)));+ hits.truncate(limit);+ hits+}++pub fn read_i32s(path: &Path) -> Result<Vec<i32>, String> {+ let b = std::fs::read(path).map_err(|_| "The feature data is not downloaded yet.".to_string())?;+ Ok(b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts(arch: &str, n_embd: usize, n_layer: usize) -> ModelFacts {+ ModelFacts { arch: arch.into(), n_layer, n_embd, template: super::super::model::Template::Gemma, name: "x".into() }+ }++ #[test]+ fn catalog_matches_by_shape_only() {+ assert_eq!(for_model(&facts("gemma3", 640, 18)).unwrap().id, "gemma-scope-2-270m-it-l9");+ assert_eq!(for_model(&facts("gemma3", 1152, 26)).unwrap().id, "gemma-scope-2-1b-it-l13");+ assert!(for_model(&facts("qwen2", 896, 24)).is_none());+ assert!(for_model(&facts("gemma3", 2560, 34)).is_none());+ }++ #[test]+ fn slices_have_the_size_of_their_tensors() {+ for s in CATALOG {+ assert_eq!(s.w_dec.len(), (s.width * s.n_embd * 4) as u64, "{}", s.id);+ assert_eq!(s.top_tokens.len(), (s.width * 10 * 4) as u64, "{}", s.id);+ assert!(s.layer >= 1 && s.layer < s.n_layer);+ assert_eq!(s.w_dec.sha256.len(), 64);+ assert!(s.url(&s.w_dec).starts_with("https://huggingface.co/google/gemma-scope-2-"));+ assert!(s.url(&s.w_dec).contains(s.revision));+ }+ }++ #[test]+ fn readable_drops_markers() {+ assert_eq!(readable("\u{2581}love"), "love");+ assert_eq!(readable("<0x0A>"), "");+ assert_eq!(readable("<unused12>"), "");+ assert_eq!(readable("Love"), "Love");+ }++ fn lab(rows: &[&[&str]]) -> Vec<Vec<String>> {+ rows.iter().map(|r| r.iter().map(|s| s.to_string()).collect()).collect()+ }++ #[test]+ fn search_ranks_exact_words_and_ignores_fragments() {+ let l = lab(&[+ &["rate", "scores", "loops"],+ &["locations", "Locations", "location", "areas"],+ &["sides", "margins", "underdog"],+ &["dog", "puppy"],+ ]);+ assert!(search(&l, "pirate", 10).is_empty());+ let loc = search(&l, "location", 10);+ assert_eq!(loc[0].feature, 1);+ let dog = search(&l, "dog", 10);+ assert_eq!(dog.len(), 1, "underdog is not a dog");+ assert_eq!(dog[0].feature, 3);+ assert_eq!(search(&l, "#2", 10)[0].feature, 2);+ assert!(search(&l, "#99", 10).is_empty());+ assert!(search(&l, " ", 10).is_empty());+ }++ #[test]+ fn labels_read_tokens_through_the_vocabulary() {+ let vocab: Vec<String> = vec!["<pad>".into(), "\u{2581}love".into(), "Love".into(), "love".into()];+ let tops = vec![1, 2, 3, 0, 1, 1, 1, 1, 1, 1];+ assert_eq!(labels(&tops, &vocab), vec![vec!["love".to_string()]]);+ }++ #[test]+ fn feature_vector_reads_one_row_into_its_layer() {+ let dir = tempfile::tempdir().unwrap();+ let spec = &CATALOG[0];+ let d = super::dir(dir.path(), spec);+ std::fs::create_dir_all(&d).unwrap();+ // Two rows are enough to read the second.+ let mut b = vec![0u8; spec.n_embd * 4 * 2];+ b[spec.n_embd * 4..spec.n_embd * 4 + 4].copy_from_slice(&1.5f32.to_le_bytes());+ std::fs::write(d.join("w_dec.f32"), &b).unwrap();+ let cv = feature_vector(dir.path(), spec, 1).unwrap();+ assert_eq!(cv.layers.keys().copied().collect::<Vec<_>>(), vec![9]);+ assert_eq!(cv.layers[&9][0], 1.5);+ assert!(feature_vector(dir.path(), spec, 16384).is_err());+ }+}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 83f5d4ed..26df478c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -765,6 +765,31 @@ pub fn run() {commands::abliterate::abliterate_dismiss,commands::abliterate::abliterate_runs,commands::abliterate::abliterate_trash_copy,+ // Neuron tweaker (3.0.9, P11)+ #[cfg(desktop)]+ commands::neuron::neuron_presets,+ #[cfg(desktop)]+ commands::neuron::neuron_info,+ #[cfg(desktop)]+ commands::neuron::neuron_build,+ #[cfg(desktop)]+ commands::neuron::neuron_feature_add,+ #[cfg(desktop)]+ commands::neuron::neuron_delete,+ #[cfg(desktop)]+ commands::neuron::neuron_sae_download,+ #[cfg(desktop)]+ commands::neuron::neuron_sae_search,+ #[cfg(desktop)]+ commands::neuron::neuron_status,+ #[cfg(desktop)]+ commands::neuron::neuron_cancel,+ #[cfg(desktop)]+ commands::neuron::neuron_dismiss,+ #[cfg(desktop)]+ commands::neuron::neuron_apply,+ #[cfg(desktop)]+ commands::neuron::neuron_compare,// Whisper STTcommands::whisper::whisper_status,commands::whisper::transcribe,diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.jsonindex d5c7a1b3..217c98c5 100644--- a/src-tauri/tauri.macos.conf.json+++ b/src-tauri/tauri.macos.conf.json@@ -20,7 +20,8 @@"bundle": {"externalBin": ["bin/lu-llama-server",- "bin/lu-llama-quantize"+ "bin/lu-llama-quantize",+ "bin/lu-llama-cvector-generator"],"macOS": {"minimumSystemVersion": "14.0"diff --git a/src-tauri/tauri.windows.conf.json b/src-tauri/tauri.windows.conf.jsonindex d41a3126..510ac005 100644--- a/src-tauri/tauri.windows.conf.json+++ b/src-tauri/tauri.windows.conf.json@@ -17,6 +17,10 @@]},"bundle": {+ "externalBin": [+ "bin/lu-llama-server",+ "bin/lu-llama-cvector-generator"+ ],"resources": {"resources/whisper_server.py": "resources/whisper_server.py","resources/voice_loop/lu_voice_loop/*.py": "resources/voice_loop/lu_voice_loop/",diff --git a/src/api/neuron.ts b/src/api/neuron.tsnew file mode 100644index 00000000..be8788d4--- /dev/null+++ b/src/api/neuron.ts@@ -0,0 +1,118 @@+// The Neuron tweaker (3.0.9, P11). The work happens in Rust+// (src-tauri/src/commands/neuron); this is the app's side of it.++import { backendCall } from './backend'+import type { BuiltinEngineTuning } from '../types/settings'++export interface NeuronPreset {+ id: string+ left: string+ right: string+}++export interface NeuronVector {+ id: string+ /** preset | own | feature */+ kind: 'preset' | 'own' | 'feature'+ name: string+ left: string+ right: string+ /** The measured scale slider +1 stands for. */+ unit: number+ builtAt: number+ more: string[]+ less: string[]+ feature?: number | null+ sae?: string | null+}++export interface NeuronSae {+ id: string+ title: string+ license: string+ layer: number+ width: number+ bytes: number+ downloaded: boolean+ source: string+ instruct: boolean+}++export interface NeuronInfo {+ facts: { arch: string; nLayer: number; nEmbd: number; template: string; name: string }+ modelKey: string+ generator: boolean+ band: [number, number]+ vectors: NeuronVector[]+ sae: NeuronSae | null+ activeMix: string | null+}++export interface NeuronJob {+ status: 'idle' | 'running' | 'done' | 'failed' | 'cancelled'+ kind: '' | 'build' | 'feature' | 'download'+ title: string+ modelPath: string+ phaseLabel: string+ step: number+ total: number+ bytesDone: number+ bytesTotal: number+ rateBps: number+ etaSecs: number | null+ elapsedSecs: number+ resultId: string | null+ error: string | null+ logs: string[]+}++export interface NeuronEntry {+ id: string+ strength: number+}++export interface FeatureHit {+ feature: number+ label: string+ score: number+}++export interface CompareResult {+ before: string+ after: string+ seed: number+ steered: boolean+ same: boolean+}++export const neuronPresets = () => backendCall<NeuronPreset[]>('neuron_presets')++export const neuronInfo = (modelPath: string) => backendCall<NeuronInfo>('neuron_info', { modelPath })++export const neuronBuildPreset = (modelPath: string, preset: string) =>+ backendCall<{ started: boolean }>('neuron_build', { args: { modelPath, preset } })++export const neuronBuildOwn = (modelPath: string, name: string, more: string[], less: string[], id?: string) =>+ backendCall<{ started: boolean }>('neuron_build', { args: { modelPath, name, more, less, id } })++export const neuronFeatureAdd = (modelPath: string, feature: number, label?: string) =>+ backendCall<{ started: boolean }>('neuron_feature_add', { modelPath, feature, label })++export const neuronDelete = (modelPath: string, id: string) => backendCall<{ deleted: string }>('neuron_delete', { modelPath, id })++export const neuronSaeDownload = (modelPath: string) => backendCall<{ started: boolean }>('neuron_sae_download', { modelPath })++export const neuronSaeSearch = (modelPath: string, query: string) =>+ backendCall<{ hits: FeatureHit[] }>('neuron_sae_search', { modelPath, query })++export const neuronStatus = () => backendCall<NeuronJob>('neuron_status')++export const neuronCancel = () => backendCall<{ cancelling: boolean }>('neuron_cancel')++export const neuronDismiss = () => backendCall<{ ok: boolean }>('neuron_dismiss')++export const neuronApply = (modelPath: string, entries: NeuronEntry[], tuning?: BuiltinEngineTuning) =>+ backendCall<{ mix: string | null; restarted: boolean; load: number; port?: number }>('neuron_apply', { modelPath, entries, tuning })++export const neuronCompare = (modelPath: string, question: string, seed: number, entries: NeuronEntry[], tuning?: BuiltinEngineTuning) =>+ backendCall<CompareResult>('neuron_compare', { modelPath, question, seed, entries, tuning })diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex f6faa392..2d2024f4 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -64,6 +64,7 @@ import { RenderFixupModal } from '../create/experimental/RenderFixupModal'import { CommandPalette } from '../ui/CommandPalette'import { CreditsExhaustedModal } from './CreditsExhaustedModal'import { Titlebar } from './Titlebar'+import { useNeuronFollowsPersona } from '../../hooks/useNeuronFollowsPersona'// Aus der Komponente herausgezogen: `new Set(STORE_KEYS)` entstand bei jedem// Render neu und war damit die instabile Referenz, wegen der der Restore-Effekt@@ -125,6 +126,7 @@ const loadModelManager = () => import('../models/ModelManager').then((m) => ({ dconst loadBenchmarkView = () => import('../models/BenchmarkView').then((m) => ({ default: m.BenchmarkView }))const loadSettingsPage = () => import('../settings/SettingsPage').then((m) => ({ default: m.SettingsPage }))const loadCreateExperimental = () => import('../create/experimental/CreateExperimental').then((m) => ({ default: m.CreateExperimental }))+const loadNeuronView = () => import('../neuron/NeuronView').then((m) => ({ default: m.NeuronView }))const loadVoiceView = () => import('../voice/VoiceView').then((m) => ({ default: m.VoiceView }))const loadOnboarding = () => import('../onboarding/Onboarding').then((m) => ({ default: m.Onboarding }))@@ -165,6 +167,7 @@ export function AppShell() {// the cloud Create axis and the lu-cloud chat provider in sync.useCloudAuth()useCloudOutageWatch()+ useNeuronFollowsPersona()// ── Global Local/Cloud mode (2.5.7) — appMode drives everything ──const appMode = settings.appMode@@ -268,7 +271,7 @@ export function AppShell() {// unmount), so there is no second stop here.useEffect(() => {const ui = useUIStore.getState()- if (appMode === 'cloud' && (ui.currentView === 'voice' || ui.currentView === 'models' || ui.currentView === 'benchmark')) {+ if (appMode === 'cloud' && (ui.currentView === 'voice' || ui.currentView === 'models' || ui.currentView === 'benchmark' || ui.currentView === 'neuron')) {ui.setView('chat')}}, [appMode])@@ -1177,6 +1180,7 @@ export function AppShell() {{currentView === 'settings' && <LazyView load={loadSettingsPage} fallback={<SettingsSkeleton />} />}{currentView === 'create' && <LazyView load={loadCreateExperimental} fallback={<CreateSkeleton />} />}{currentView === 'voice' && <LazyView load={loadVoiceView} fallback={<VoiceSkeleton />} />}+ {currentView === 'neuron' && <LazyView load={loadNeuronView} fallback={<BenchmarkSkeleton />} />}</main></div></div>diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex bcdfd7d3..4a098456 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -52,6 +52,8 @@ const NAV_TARGETS: readonly NavTarget[] = [{ id: 'voice', label: 'Voice', view: 'voice', localOnly: true },{ id: 'compare', label: 'Compare', view: null },{ id: 'benchmark', label: 'Benchmark', view: 'benchmark', localOnly: true },+ // The Neuron tweaker (3.0.9, P11) steers local LU Engine models only.+ { id: 'neuron', label: 'Neurons', view: 'neuron', localOnly: true },{ id: 'models', label: 'Models', view: 'models', localOnly: true },{ id: 'settings', label: 'Settings', view: 'settings' },]diff --git a/src/components/neuron/NeuronView.tsx b/src/components/neuron/NeuronView.tsxnew file mode 100644index 00000000..194b0676--- /dev/null+++ b/src/components/neuron/NeuronView.tsx@@ -0,0 +1,584 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { Loader2, RotateCcw, Search, Sliders, Trash2 } from 'lucide-react'+import { Hinweis } from '../ui/Hinweis'+import { HINWEIS_TEXT } from '../../lib/hinweis'+import { ICON_SM } from '../ui/icon-size'+import { openExternal } from '../../api/backend'+import { listBundledModels, bundledEngineStatus, type BundledModel } from '../../api/engine'+import {+ neuronApply, neuronBuildOwn, neuronBuildPreset, neuronCancel, neuronCompare, neuronDelete, neuronDismiss,+ neuronFeatureAdd, neuronInfo, neuronPresets, neuronSaeDownload, neuronSaeSearch, neuronStatus,+ type CompareResult, type FeatureHit, type NeuronInfo, type NeuronJob, type NeuronPreset, type NeuronVector,+} from '../../api/neuron'+import { getProviderIdFromModel } from '../../api/providers/model-name'+import { isManagedBuiltinSlot } from '../../api/builtin-ensure'+import { preservedSwapCtx } from '../../lib/builtin-ctx'+import { builtinModelMatches } from '../../lib/builtin-model-identity'+import {+ backendNote, effectiveStrengths, entriesFor, hasPersonaProfile, jobProgressText, jobShare, sameEntries,+ strengthWarning, warningText, type BackendKind,+} from '../../lib/neuron'+import { editingKey, useNeuronStore } from '../../stores/neuronStore'+import { useModelStore } from '../../stores/modelStore'+import { useSettingsStore } from '../../stores/settingsStore'+import type { BuiltinEngineTuning } from '../../types/settings'++const APPLY_DELAY_MS = 700++/** Which program answers the chat's model right now. */+function chatBackend(activeModel: string | null, appMode: string | undefined): BackendKind {+ if (appMode === 'cloud') return 'cloud'+ if (!activeModel) return 'none'+ const provider = getProviderIdFromModel(activeModel)+ if (provider === 'ollama') return 'ollama'+ if (provider === 'openai' && isManagedBuiltinSlot()) return 'lu-engine'+ if (String(provider).includes('lmstudio')) return 'lmstudio'+ return 'other'+}++/** The tuning a restart uses: the user's, with the context the engine holds+ * kept the way the chat's own restarts keep it (lib/builtin-ctx). */+async function restartTuning(model: BundledModel | undefined): Promise<BuiltinEngineTuning | undefined> {+ const tuning = useSettingsStore.getState().settings.builtinEngine+ try {+ const status = await bundledEngineStatus()+ const keep = preservedSwapCtx({+ tuningCtx: tuning?.ctx,+ tuningChosen: tuning?.ctxChosen,+ currentCtx: status?.ctxRequested ?? status?.ctx,+ ctxTrain: model?.ctx_train,+ })+ return keep ? { ...(tuning ?? {}), ctx: keep } as BuiltinEngineTuning : tuning+ } catch {+ return tuning+ }+}++export function NeuronView() {+ const activeModel = useModelStore((s) => s.activeModel)+ const appMode = useSettingsStore((s) => s.settings.appMode)+ const personaId = useSettingsStore((s) => s.activePersonaId)+ const personas = useSettingsStore((s) => s.personas)+ const persona = personas.find((p) => p.id === personaId)+ const { profiles, scopeByModel, setStrength, setProfile, removeProfile, removeSlider, setScope } = useNeuronStore()++ const [models, setModels] = useState<BundledModel[]>([])+ const [modelPath, setModelPath] = useState<string>('')+ const [info, setInfo] = useState<NeuronInfo | null>(null)+ const [presets, setPresets] = useState<NeuronPreset[]>([])+ const [job, setJob] = useState<NeuronJob | null>(null)+ const [error, setError] = useState<string | null>(null)+ const [applyState, setApplyState] = useState<'idle' | 'applying' | 'applied'>('idle')+ const [lastApplied, setLastApplied] = useState<string>('')++ const backend = chatBackend(activeModel, appMode)+ const model = models.find((m) => m.path === modelPath)++ // Models and presets once; the loaded model (or the chat's) preselected.+ useEffect(() => {+ void neuronPresets().then(setPresets).catch(() => setPresets([]))+ void listBundledModels().then((list) => {+ setModels(list)+ const loaded = list.find((m) => m.loaded)+ const chat = list.find((m) => activeModel && builtinModelMatches(m.path, activeModel) && activeModel.includes(m.name))+ setModelPath((cur) => cur || (chat ?? loaded ?? list[0])?.path || '')+ }).catch(() => setModels([]))+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ const refreshInfo = useCallback(async (path: string) => {+ if (!path) return+ try {+ setInfo(await neuronInfo(path))+ setError(null)+ } catch (e) {+ setInfo(null)+ setError(String(e))+ }+ }, [])++ useEffect(() => { void refreshInfo(modelPath) }, [modelPath, refreshInfo])++ // Job polling while something runs (and once on mount, to pick up a job+ // that was started before the view opened).+ const pollRef = useRef<number | null>(null)+ const poll = useCallback(async () => {+ try {+ const j = await neuronStatus()+ setJob(j)+ if (j.status === 'running') {+ pollRef.current = window.setTimeout(() => void poll(), 1000)+ } else if (j.status === 'done') {+ await refreshInfo(j.modelPath || modelPath)+ }+ } catch { /* backend gone: nothing to show */ }+ }, [modelPath, refreshInfo])+ useEffect(() => {+ void poll()+ return () => { if (pollRef.current) window.clearTimeout(pollRef.current) }+ }, [poll])++ const modelKey = info?.modelKey ?? ''+ const scope = (personaId && scopeByModel[modelKey]) || 'model'+ const editKey = editingKey(modelKey, personaId, scope)+ const strengths = useMemo(() => {+ if (!modelKey) return {}+ return scope === 'persona' ? (profiles[editKey] ?? effectiveStrengths(profiles, modelKey, null)) : (profiles[editKey] ?? {})+ }, [profiles, editKey, modelKey, scope])+ const vectors = useMemo(() => info?.vectors ?? [], [info])+ const available = useMemo(() => new Set(vectors.map((v) => v.id)), [vectors])+ const effective = useMemo(() => modelKey ? effectiveStrengths(profiles, modelKey, personaId) : {}, [profiles, modelKey, personaId])+ const entries = useMemo(() => entriesFor(effective, available), [effective, available])+ const warning = warningText(strengthWarning(entries))+ const running = job?.status === 'running'++ // Apply after the sliders rest for a moment. A restart takes seconds, so+ // dragging must not cause one per pixel.+ useEffect(() => {+ if (!modelPath || !info) return+ const sig = `${modelPath}|${JSON.stringify(entries)}`+ if (sig === lastApplied) return+ const t = window.setTimeout(() => {+ void (async () => {+ setApplyState('applying')+ try {+ await neuronApply(modelPath, entries, await restartTuning(model))+ setLastApplied(sig)+ setApplyState('applied')+ await refreshInfo(modelPath)+ } catch (e) {+ setError(String(e))+ setApplyState('idle')+ }+ })()+ }, lastApplied === '' ? 0 : APPLY_DELAY_MS)+ return () => window.clearTimeout(t)+ }, [entries, modelPath, info, lastApplied, model, refreshInfo])++ const startJob = async (start: () => Promise<unknown>) => {+ setError(null)+ try {+ await start()+ await poll()+ } catch (e) {+ setError(String(e))+ }+ }++ const reset = () => {+ if (!modelKey) return+ if (scope === 'persona') removeProfile(editKey)+ else setProfile(editKey, {})+ }++ if (backend !== 'lu-engine' && backend !== 'none' && models.length === 0) {+ return (+ <Shell>+ <Hinweis>{backendNote(backend)}</Hinweis>+ </Shell>+ )+ }++ return (+ <Shell>+ {backend !== 'lu-engine' && <Hinweis className="mb-3">{backendNote(backend)}</Hinweis>}+ {error && <Hinweis ton="fehler" className="mb-3" onDismiss={() => setError(null)}>{error}</Hinweis>}++ <div className="flex flex-wrap items-center gap-2 mb-1">+ <label className="t-body text-gray-600 dark:text-gray-300" htmlFor="neuron-model">Model</label>+ <select+ id="neuron-model"+ data-testid="neuron-model"+ className="t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white max-w-full"+ value={modelPath}+ onChange={(e) => { setModelPath(e.target.value); setLastApplied('') }}+ >+ {models.map((m) => <option key={m.path} value={m.path}>{m.name}{m.loaded ? ' (loaded)' : ''}</option>)}+ </select>+ {applyState === 'applying' && <span className={`t-micro ${HINWEIS_TEXT.ruhig} inline-flex items-center gap-1`}><Loader2 size={12} className="animate-spin" /> Restarting the engine with your sliders…</span>}+ {applyState === 'applied' && <span className={`t-micro ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-applied">{entries.length ? `Active in chat: ${entries.length} slider${entries.length > 1 ? 's' : ''}` : 'Off: the model runs unchanged'}</span>}+ </div>+ {info && (+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-3`}>+ {info.facts.arch} · {info.facts.nLayer} layers · sliders act on layers {info.band[0]}–{info.band[1]}+ </p>+ )}++ {persona && modelKey && (+ <div className="flex flex-wrap items-center gap-1 mb-4 t-body" role="radiogroup" aria-label="Save sliders for">+ <span className="text-gray-600 dark:text-gray-300 mr-1">Save for</span>+ <ScopeButton on={scope === 'model'} onClick={() => setScope(modelKey, 'model')}>This model</ScopeButton>+ <ScopeButton on={scope === 'persona'} onClick={() => { setScope(modelKey, 'persona'); if (!hasPersonaProfile(profiles, modelKey, personaId)) setProfile(editingKey(modelKey, personaId, 'persona'), { ...(profiles[modelKey] ?? {}) }) }}>+ This model with “{persona.name}”+ </ScopeButton>+ </div>+ )}++ {job && job.status !== 'idle' && <JobPanel job={job} onStop={() => void neuronCancel().then(poll)} onDismiss={() => void neuronDismiss().then(poll)} />}++ <Section title="Sliders">+ {!info?.generator && (+ <Hinweis className="mb-2">This build has no vector tool, so ready-made and own sliders cannot be computed here (Linux: later version). Feature sliders work where the model has one.</Hinweis>+ )}+ <div className="space-y-2" data-testid="neuron-presets">+ {presets.map((p) => {+ const v = vectors.find((x) => x.id === p.id)+ return (+ <SliderRow+ key={p.id}+ id={p.id}+ left={p.left}+ right={p.right}+ value={strengths[p.id] ?? 0}+ computed={!!v}+ disabled={running || !modelPath || (!v && !info?.generator)}+ onCompute={() => void startJob(() => neuronBuildPreset(modelPath, p.id))}+ onChange={(x) => setStrength(editKey, p.id, x)}+ />+ )+ })}+ </div>+ </Section>++ <Section title="Your own sliders">+ <div className="space-y-2" data-testid="neuron-own">+ {vectors.filter((v) => v.kind === 'own').map((v) => (+ <SliderRow+ key={v.id}+ id={v.id}+ left={v.left}+ right={v.right}+ value={strengths[v.id] ?? 0}+ computed+ disabled={running}+ onChange={(x) => setStrength(editKey, v.id, x)}+ onDelete={() => void neuronDelete(modelPath, v.id).then(() => { removeSlider(modelKey, v.id); return refreshInfo(modelPath) })}+ />+ ))}+ </div>+ <OwnSliderForm disabled={running || !info?.generator || !modelPath} onCompute={(name, more, less) => void startJob(() => neuronBuildOwn(modelPath, name, more, less))} />+ </Section>++ {info?.sae && (+ <Section title="Features">+ <FeaturePanel+ info={info}+ modelPath={modelPath}+ vectors={vectors.filter((v) => v.kind === 'feature')}+ strengths={strengths}+ disabled={running}+ onDownload={() => void startJob(() => neuronSaeDownload(modelPath))}+ onAdd={(hit) => void startJob(() => neuronFeatureAdd(modelPath, hit.feature, hit.label))}+ onChange={(id, x) => setStrength(editKey, id, x)}+ onDelete={(id) => void neuronDelete(modelPath, id).then(() => { removeSlider(modelKey, id); return refreshInfo(modelPath) })}+ onError={setError}+ />+ </Section>+ )}++ {warning && <Hinweis className="mb-3" >{warning}</Hinweis>}++ <div className="flex items-center gap-2 mb-6">+ <button+ type="button"+ data-testid="neuron-reset"+ onClick={reset}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md t-body bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-100"+ >+ <RotateCcw size={ICON_SM} /> Reset+ </button>+ <span className={`t-micro ${HINWEIS_TEXT.ruhig}`}>All sliders to 0: the model answers exactly as without the tweaker.</span>+ </div>++ <Section title="Before and after">+ <ComparePanel modelPath={modelPath} entries={entries} disabled={running || !modelPath} model={model} onError={setError} />+ </Section>++ <Section title="What this can and cannot do">+ <ul className={`t-micro ${HINWEIS_TEXT.ruhig} list-disc pl-4 space-y-1`}>+ <li>Works with models in LU Engine (llama.cpp control vectors). Ollama, LM Studio and cloud models take no control vectors, so the sliders cannot reach them.</li>+ <li>Each slider is computed for this model the first time: LU reads short example pairs through the model and measures how far it can push before answers break. Seconds for small models, a few minutes for large ones. The chat pauses meanwhile.</li>+ <li>±1 is just under where the measured answer started to break. Strong settings or many sliders at once can still make text repeat or wander.</li>+ <li>A change restarts the engine with the new sliders (a few seconds). The settings stay for this model across restarts of LU.</li>+ <li>Features exist only for models with an official sparse autoencoder: Gemma 3 270M IT and 1B IT (Gemma Scope 2, CC-BY-4.0). Their names come from the words each feature pushes, and some are hard to name.</li>+ </ul>+ </Section>+ </Shell>+ )+}++function Shell({ children }: { children: React.ReactNode }) {+ return (+ <div className="h-full overflow-y-auto scrollbar-thin" data-testid="neuron-view">+ <div className="max-w-2xl mx-auto px-4 py-4">+ <div className="flex items-center gap-2 mb-1">+ <Sliders size={16} className="text-gray-500" />+ <h1 className="t-title text-gray-900 dark:text-white">Neuron tweaker</h1>+ </div>+ <p className={`t-body ${HINWEIS_TEXT.ruhig} mb-4`}>Turn your local model’s traits up or down, like an equalizer. It acts inside the model, not in the prompt.</p>+ {children}+ </div>+ </div>+ )+}++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <section className="mb-6">+ <h2 className="t-body font-medium text-gray-900 dark:text-white mb-2">{title}</h2>+ {children}+ </section>+ )+}++function ScopeButton({ on, onClick, children }: { on: boolean; onClick: () => void; children: React.ReactNode }) {+ return (+ <button+ type="button"+ role="radio"+ aria-checked={on}+ onClick={onClick}+ className={`px-2 py-0.5 rounded-md ${on ? 'bg-lu-accent/20 text-gray-900 dark:text-white' : 'bg-gray-100 dark:bg-white/[0.06] text-gray-600 dark:text-gray-300'}`}+ >+ {children}+ </button>+ )+}++interface SliderRowProps {+ id: string+ left: string+ right: string+ value: number+ computed: boolean+ disabled?: boolean+ onChange: (v: number) => void+ onCompute?: () => void+ onDelete?: () => void+}++function SliderRow({ id, left, right, value, computed, disabled, onChange, onCompute, onDelete }: SliderRowProps) {+ return (+ <div className="grid grid-cols-[7rem_1fr_7rem_3rem_auto] items-center gap-2" data-testid={`neuron-slider-${id}`}>+ <span className="t-body text-right text-gray-700 dark:text-gray-200 truncate" title={left}>{left}</span>+ {computed ? (+ <input+ type="range"+ min={-1}+ max={1}+ step={0.05}+ value={value}+ disabled={disabled}+ aria-label={`${left} to ${right}`}+ onChange={(e) => onChange(Number(e.target.value))}+ onDoubleClick={() => onChange(0)}+ className="w-full accent-[var(--lu-accent,#8b7cf0)]"+ />+ ) : (+ <button+ type="button"+ disabled={disabled}+ onClick={onCompute}+ data-testid={`neuron-compute-${id}`}+ className="t-micro rounded-md px-2 py-1 bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-700 dark:text-gray-200 disabled:opacity-50"+ >+ Compute for this model+ </button>+ )}+ <span className="t-body text-gray-700 dark:text-gray-200 truncate" title={right}>{right}</span>+ <span className={`t-micro tabular-nums ${HINWEIS_TEXT.ruhig}`}>{computed ? (value > 0 ? `+${value.toFixed(2)}` : value.toFixed(2)) : ''}</span>+ {onDelete ? (+ <button type="button" onClick={onDelete} aria-label={`Delete ${right}`} className="p-1 text-gray-400 hover:text-red-500"><Trash2 size={ICON_SM} /></button>+ ) : <span />}+ </div>+ )+}++function JobPanel({ job, onStop, onDismiss }: { job: NeuronJob; onStop: () => void; onDismiss: () => void }) {+ const share = jobShare(job)+ if (job.status === 'running') {+ return (+ <div className="space-y-1.5 mb-5" data-testid="neuron-job">+ <p className="flex items-center gap-1.5 t-body text-gray-700 dark:text-gray-200">+ <Loader2 size={ICON_SM} className="animate-spin" /> {job.title}: {job.phaseLabel || 'starting…'}+ </p>+ <div className="h-1 rounded-full bg-gray-200 dark:bg-white/[0.08] overflow-hidden">+ <div className="h-full rounded-full bg-lu-accent transition-[width]" style={{ width: share == null ? '0%' : `${Math.round(share * 100)}%` }} />+ </div>+ <p className={`t-micro font-mono ${HINWEIS_TEXT.ruhig}`} data-testid="neuron-job-progress">{jobProgressText(job)}</p>+ {job.logs.length > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig} truncate`}>{job.logs[job.logs.length - 1]}</p>}+ <button type="button" onClick={onStop} className="t-micro text-red-600 dark:text-red-400 hover:underline">Stop</button>+ </div>+ )+ }+ return (+ <div className="mb-5" data-testid="neuron-job-ended">+ {job.status === 'done' && <Hinweis onDismiss={onDismiss}>{job.title}: done{job.elapsedSecs ? ` in ${job.elapsedSecs} s` : ''}.{job.logs.find((l) => l.includes('full strength')) ? ` ${job.logs.find((l) => l.includes('full strength'))?.trim()}.` : ''}</Hinweis>}+ {job.status === 'failed' && <Hinweis ton="fehler" onDismiss={onDismiss}>{job.title} failed: {job.error}</Hinweis>}+ {job.status === 'cancelled' && <Hinweis onDismiss={onDismiss}>{job.title}: stopped.</Hinweis>}+ </div>+ )+}++function OwnSliderForm({ disabled, onCompute }: { disabled: boolean; onCompute: (name: string, more: string[], less: string[]) => void }) {+ const [open, setOpen] = useState(false)+ const [name, setName] = useState('')+ const [more, setMore] = useState('')+ const [less, setLess] = useState('')+ const lines = (t: string) => t.split('\n').map((l) => l.trim()).filter(Boolean)+ if (!open) {+ return (+ <button type="button" disabled={disabled} onClick={() => setOpen(true)} data-testid="neuron-own-new" className="mt-2 t-body text-lu-accent hover:underline disabled:opacity-50">+ + New slider from examples+ </button>+ )+ }+ const ok = name.trim() && lines(more).length > 0 && lines(less).length > 0+ return (+ <div className="mt-3 space-y-2" data-testid="neuron-own-form">+ <input+ className="w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white"+ placeholder="Name, e.g. Pirate"+ value={name}+ maxLength={40}+ onChange={(e) => setName(e.target.value)}+ data-testid="neuron-own-name"+ />+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ <label className="t-micro text-gray-600 dark:text-gray-300">More like this (one per line)+ <textarea rows={4} className="mt-1 w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" placeholder={'Talk like a pirate.\nSay arr and matey.'} value={more} onChange={(e) => setMore(e.target.value)} data-testid="neuron-own-more" />+ </label>+ <label className="t-micro text-gray-600 dark:text-gray-300">Less like this (one per line)+ <textarea rows={4} className="mt-1 w-full t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" placeholder={'Talk in plain modern English.'} value={less} onChange={(e) => setLess(e.target.value)} data-testid="neuron-own-less" />+ </label>+ </div>+ <div className="flex gap-2">+ <button type="button" disabled={disabled || !ok} onClick={() => { onCompute(name.trim(), lines(more), lines(less)); setOpen(false); setName(''); setMore(''); setLess('') }} data-testid="neuron-own-compute" className="px-3 py-1.5 rounded-md t-body bg-lu-accent text-white disabled:opacity-50">+ Compute slider+ </button>+ <button type="button" onClick={() => setOpen(false)} className="px-3 py-1.5 rounded-md t-body text-gray-600 dark:text-gray-300">Cancel</button>+ </div>+ </div>+ )+}++interface FeaturePanelProps {+ info: NeuronInfo+ modelPath: string+ vectors: NeuronVector[]+ strengths: Record<string, number>+ disabled: boolean+ onDownload: () => void+ onAdd: (hit: FeatureHit) => void+ onChange: (id: string, v: number) => void+ onDelete: (id: string) => void+ onError: (e: string) => void+}++function FeaturePanel({ info, modelPath, vectors, strengths, disabled, onDownload, onAdd, onChange, onDelete, onError }: FeaturePanelProps) {+ const sae = info.sae!+ const [query, setQuery] = useState('')+ const [hits, setHits] = useState<FeatureHit[] | null>(null)+ const [searching, setSearching] = useState(false)+ const search = async () => {+ if (!query.trim()) return+ setSearching(true)+ try {+ setHits((await neuronSaeSearch(modelPath, query)).hits)+ } catch (e) {+ onError(String(e))+ } finally {+ setSearching(false)+ }+ }+ return (+ <div data-testid="neuron-features">+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-2`}>+ {sae.title}. License {sae.license}.{' '}+ <button type="button" className="underline" onClick={() => void openExternal(sae.source)}>Source</button>+ {!sae.instruct && ' This file does not look like the instruction-tuned model the features were trained on; they may act weaker.'}+ </p>+ {!sae.downloaded ? (+ <button type="button" disabled={disabled} onClick={onDownload} data-testid="neuron-sae-download" className="px-3 py-1.5 rounded-md t-body bg-gray-100 dark:bg-white/[0.06] hover:bg-gray-200 dark:hover:bg-white/10 text-gray-800 dark:text-gray-100 disabled:opacity-50">+ Download feature data ({Math.round(sae.bytes / 1e6)} MB)+ </button>+ ) : (+ <>+ <form className="flex gap-2 mb-2" onSubmit={(e) => { e.preventDefault(); void search() }}>+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search features, e.g. location, love, #1234" data-testid="neuron-feature-query" className="flex-1 t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />+ <button type="submit" disabled={searching} data-testid="neuron-feature-search" className="px-2 rounded-md bg-gray-100 dark:bg-white/[0.06] text-gray-700 dark:text-gray-200">+ {searching ? <Loader2 size={ICON_SM} className="animate-spin" /> : <Search size={ICON_SM} />}+ </button>+ </form>+ {hits && hits.length === 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>No feature pushes that word. Try another word or a feature number (#1234).</p>}+ {hits && hits.length > 0 && (+ <ul className="mb-3 max-h-56 overflow-y-auto scrollbar-thin space-y-1" data-testid="neuron-feature-hits">+ {hits.map((h) => (+ <li key={h.feature} className="flex items-center gap-2 t-micro">+ <span className="tabular-nums text-gray-500 w-12">#{h.feature}</span>+ <span className="flex-1 truncate text-gray-700 dark:text-gray-200" title={h.label}>{h.label}</span>+ <button type="button" disabled={disabled || vectors.some((v) => v.feature === h.feature)} onClick={() => onAdd(h)} className="text-lu-accent hover:underline disabled:opacity-40">Add</button>+ </li>+ ))}+ </ul>+ )}+ <div className="space-y-2">+ {vectors.map((v) => (+ <SliderRow key={v.id} id={v.id} left="Less" right={v.name} value={strengths[v.id] ?? 0} computed disabled={disabled} onChange={(x) => onChange(v.id, x)} onDelete={() => onDelete(v.id)} />+ ))}+ </div>+ </>+ )}+ </div>+ )+}++function ComparePanel({ modelPath, entries, disabled, model, onError }: { modelPath: string; entries: ReturnType<typeof entriesFor>; disabled: boolean; model: BundledModel | undefined; onError: (e: string) => void }) {+ const [question, setQuestion] = useState('Write two sentences about rain.')+ const [seed, setSeed] = useState(42)+ const [busy, setBusy] = useState(false)+ const [result, setResult] = useState<(CompareResult & { entries: typeof entries }) | null>(null)+ const run = async () => {+ setBusy(true)+ try {+ const r = await neuronCompare(modelPath, question, seed, entries, await restartTuning(model))+ setResult({ ...r, entries })+ } catch (e) {+ onError(String(e))+ } finally {+ setBusy(false)+ }+ }+ const stale = result && !sameEntries(result.entries, entries)+ return (+ <div data-testid="neuron-compare">+ <div className="flex flex-wrap gap-2 mb-2">+ <input value={question} onChange={(e) => setQuestion(e.target.value)} data-testid="neuron-compare-question" className="flex-1 min-w-[12rem] t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />+ <label className={`t-micro ${HINWEIS_TEXT.ruhig} flex items-center gap-1`}>Seed+ <input type="number" value={seed} onChange={(e) => setSeed(Math.max(0, Math.floor(Number(e.target.value) || 0)))} className="w-20 t-body rounded-md bg-gray-100 dark:bg-white/[0.06] px-2 py-1 text-gray-900 dark:text-white" />+ </label>+ <button type="button" disabled={disabled || busy || !question.trim()} onClick={() => void run()} data-testid="neuron-compare-run" className="px-3 py-1.5 rounded-md t-body bg-lu-accent text-white disabled:opacity-50 inline-flex items-center gap-1.5">+ {busy && <Loader2 size={ICON_SM} className="animate-spin" />} Compare+ </button>+ </div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mb-2`}>Same question, same seed, temperature 0: once with the sliders off, once on. The engine restarts twice.</p>+ {result && (+ <>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3" data-testid="neuron-compare-result">+ <div>+ <p className="t-micro text-gray-500 mb-1">Before (sliders off)</p>+ <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-before">{result.before}</p>+ </div>+ <div>+ <p className="t-micro text-gray-500 mb-1">After ({result.entries.map((e) => `${e.id} ${e.strength > 0 ? '+' : ''}${e.strength}`).join(', ') || 'all at 0'})</p>+ <p className="t-body text-gray-800 dark:text-gray-100 whitespace-pre-wrap" data-testid="neuron-compare-after">{result.after}</p>+ </div>+ </div>+ <p className={`t-micro ${HINWEIS_TEXT.ruhig} mt-1`} data-testid="neuron-compare-same">+ {result.same ? 'Identical answers.' : 'The answers differ.'}{stale ? ' The sliders changed since; compare again.' : ''}+ </p>+ </>+ )}+ </div>+ )+}diff --git a/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx b/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsxnew file mode 100644index 00000000..0ca25f63--- /dev/null+++ b/src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx@@ -0,0 +1,88 @@+/**+ * @vitest-environment jsdom+ *+ * P11 (3.0.9): the Neuron tweaker. A slider that is not computed for the+ * model offers to compute it; a computed one, moved, reaches the engine as+ * one entry; Reset brings the engine back to no vector at all; a chat model+ * in Ollama is told plainly that the sliders cannot reach it.+ *+ * Run: npx vitest run src/components/neuron/__tests__/neuron-view-steers-the-engine.test.tsx+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { createElement } from 'react'+import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react'++const apply = vi.fn(async (_path: string, _entries: unknown[], _tuning?: unknown) => ({ mix: null, restarted: true, load: 0 }))+const buildPreset = vi.fn(async (_path: string, _id: string) => ({ started: true }))+const vectors: Array<Record<string, unknown>> = []++vi.mock('../../../api/neuron', () => ({+ neuronPresets: async () => [+ { id: 'creative', left: 'Sober', right: 'Creative' },+ { id: 'cheerful', left: 'Serious', right: 'Cheerful' },+ ],+ neuronInfo: async () => ({+ facts: { arch: 'qwen2', nLayer: 24, nEmbd: 896, template: 'chatMl', name: 'Qwen2.5 0.5B Instruct' },+ modelKey: 'qwen-1',+ generator: true,+ band: [3, 20],+ vectors: [...vectors],+ sae: null,+ activeMix: null,+ }),+ neuronStatus: async () => ({ status: 'idle', kind: '', title: '', modelPath: '', phaseLabel: '', step: 0, total: 0, bytesDone: 0, bytesTotal: 0, rateBps: 0, etaSecs: null, elapsedSecs: 0, resultId: null, error: null, logs: [] }),+ neuronApply: (p: string, e: unknown[], t?: unknown) => apply(p, e, t),+ neuronBuildPreset: (p: string, id: string) => buildPreset(p, id),+ neuronBuildOwn: vi.fn(), neuronCancel: vi.fn(), neuronCompare: vi.fn(), neuronDelete: vi.fn(), neuronDismiss: vi.fn(),+ neuronFeatureAdd: vi.fn(), neuronSaeDownload: vi.fn(), neuronSaeSearch: vi.fn(),+}))+vi.mock('../../../api/engine', () => ({+ listBundledModels: async () => [{ name: 'qwen2.5-0.5b-instruct-q8_0', path: '/models/qwen.gguf', size: 1, loaded: true }],+ bundledEngineStatus: async () => ({ running: true, healthy: true, port: 8127, model_path: '/models/qwen.gguf', ctx: 8192 }),+}))+vi.mock('../../../api/backend', () => ({ openExternal: vi.fn(), backendCall: vi.fn() }))+const slot = vi.hoisted(() => ({ managed: true }))+vi.mock('../../../api/builtin-ensure', () => ({ isManagedBuiltinSlot: () => slot.managed }))++import { NeuronView } from '../NeuronView'+import { useModelStore } from '../../../stores/modelStore'+import { useNeuronStore } from '../../../stores/neuronStore'++beforeEach(() => {+ apply.mockClear()+ buildPreset.mockClear()+ vectors.length = 0+ slot.managed = true+ useNeuronStore.setState({ profiles: {}, scopeByModel: {} })+ useModelStore.setState({ activeModel: 'openai::qwen2.5-0.5b-instruct-q8_0' })+})+afterEach(() => cleanup())++describe('Neuron tweaker view', () => {+ it('offers to compute a slider the model does not have yet', async () => {+ render(createElement(NeuronView))+ const button = await screen.findByTestId('neuron-compute-creative')+ fireEvent.click(button)+ await waitFor(() => expect(buildPreset).toHaveBeenCalledWith('/models/qwen.gguf', 'creative'))+ })++ it('sends a moved slider to the engine and Reset sends none', async () => {+ vectors.push({ id: 'creative', kind: 'preset', name: 'Sober ↔ Creative', left: 'Sober', right: 'Creative', unit: 0.8, builtAt: 1, more: [], less: [] })+ render(createElement(NeuronView))+ const row = await screen.findByTestId('neuron-slider-creative')+ // First apply on open: nothing set, no vector.+ await waitFor(() => expect(apply).toHaveBeenCalled())+ expect(apply.mock.calls[0][1]).toEqual([])+ const range = row.querySelector('input[type=range]') as HTMLInputElement+ fireEvent.change(range, { target: { value: '0.6' } })+ await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([{ id: 'creative', strength: 0.6 }]), { timeout: 3000 })+ fireEvent.click(screen.getByTestId('neuron-reset'))+ await waitFor(() => expect(apply.mock.calls.at(-1)?.[1]).toEqual([]), { timeout: 3000 })+ })++ it('says plainly when the chat model runs in Ollama', async () => {+ useModelStore.setState({ activeModel: 'ollama::llama3:8b' })+ render(createElement(NeuronView))+ expect(await screen.findByText(/Ollama takes no control vectors/)).toBeTruthy()+ })+})diff --git a/src/components/ui/command-actions.ts b/src/components/ui/command-actions.tsindex 8aae4c4c..c474a53a 100644--- a/src/components/ui/command-actions.ts+++ b/src/components/ui/command-actions.ts@@ -125,6 +125,7 @@ export function buildCommands(ctx: CommandContext): Command[] {if (ctx.localViewsAvailable) {out.push({ id: 'view-voice', label: 'Voice', group: GROUP_VIEW, run: () => ctx.setView('voice') })out.push({ id: 'view-benchmark', label: 'Benchmark', group: GROUP_VIEW, run: () => ctx.setView('benchmark') })+ out.push({ id: 'view-neuron', label: 'Neuron tweaker', group: GROUP_VIEW, run: () => ctx.setView('neuron') })out.push({ id: 'view-models', label: 'Models', group: GROUP_VIEW, run: () => ctx.setView('models') })}out.push({ id: 'view-settings', label: 'Settings', group: GROUP_VIEW, run: () => ctx.setView('settings') })diff --git a/src/hooks/useNeuronFollowsPersona.ts b/src/hooks/useNeuronFollowsPersona.tsnew file mode 100644index 00000000..dd8b7a13--- /dev/null+++ b/src/hooks/useNeuronFollowsPersona.ts@@ -0,0 +1,36 @@+import { useEffect } from 'react'+import { bundledEngineStatus } from '../api/engine'+import { neuronApply, neuronInfo } from '../api/neuron'+import { entriesFor, effectiveStrengths, hasPersonaProfile } from '../lib/neuron'+import { useNeuronStore } from '../stores/neuronStore'+import { useSettingsStore } from '../stores/settingsStore'++/**+ * A persona can carry its own Neuron tweaker sliders for a model (3.0.9,+ * P11). When the persona changes and either the old or the new one has its+ * own, the engine is restarted with the new persona's sliders. When neither+ * has, the model's sliders stay and nothing restarts.+ */+export async function followPersona(prevId: string, nextId: string): Promise<boolean> {+ const status = await bundledEngineStatus().catch(() => null)+ const modelPath = status?.running ? status.model_path : null+ if (!modelPath) return false+ const info = await neuronInfo(modelPath).catch(() => null)+ if (!info) return false+ const { profiles } = useNeuronStore.getState()+ if (!hasPersonaProfile(profiles, info.modelKey, prevId) && !hasPersonaProfile(profiles, info.modelKey, nextId)) return false+ const available = new Set(info.vectors.map((v) => v.id))+ const entries = entriesFor(effectiveStrengths(profiles, info.modelKey, nextId), available)+ await neuronApply(modelPath, entries, useSettingsStore.getState().settings.builtinEngine)+ return true+}++export function useNeuronFollowsPersona(): void {+ useEffect(() => {+ return useSettingsStore.subscribe((state, prev) => {+ if (state.activePersonaId !== prev.activePersonaId) {+ void followPersona(prev.activePersonaId, state.activePersonaId).catch(() => undefined)+ }+ })+ }, [])+}diff --git a/src/lib/__tests__/neuron.test.ts b/src/lib/__tests__/neuron.test.tsnew file mode 100644index 00000000..83eea1e7--- /dev/null+++ b/src/lib/__tests__/neuron.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from 'vitest'+import {+ backendNote,+ clampStrength,+ effectiveStrengths,+ entriesFor,+ hasPersonaProfile,+ jobProgressText,+ jobShare,+ personaProfileKey,+ sameEntries,+ shortDuration,+ strengthWarning,+} from '../neuron'+import type { NeuronJob } from '../../api/neuron'+import type { Profiles } from '../neuron'++const job = (over: Partial<NeuronJob>): NeuronJob => ({+ status: 'running', kind: 'build', title: '', modelPath: '/m.gguf', phaseLabel: '', step: 0, total: 0,+ bytesDone: 0, bytesTotal: 0, rateBps: 0, etaSecs: null, elapsedSecs: 0, resultId: null, error: null, logs: [],+ ...over,+})++describe('neuron profiles', () => {+ const profiles: Profiles = {+ 'qwen-1': { creative: 0.5 },+ [personaProfileKey('qwen-1', 'pirate')]: { casual: 1 },+ }++ it('uses the persona profile when there is one, else the model profile', () => {+ expect(effectiveStrengths(profiles, 'qwen-1', 'pirate')).toEqual({ casual: 1 })+ expect(effectiveStrengths(profiles, 'qwen-1', 'unrestricted')).toEqual({ creative: 0.5 })+ expect(effectiveStrengths(profiles, 'qwen-1', null)).toEqual({ creative: 0.5 })+ expect(effectiveStrengths(profiles, 'other', 'pirate')).toEqual({})+ expect(hasPersonaProfile(profiles, 'qwen-1', 'pirate')).toBe(true)+ expect(hasPersonaProfile(profiles, 'qwen-1', 'x')).toBe(false)+ })++ it('sends only sliders that are on and computed, sorted', () => {+ const entries = entriesFor({ b: 0.3, a: -0.5, off: 0, missing: 1, tiny: 0.01 }, new Set(['a', 'b', 'off', 'tiny']))+ expect(entries).toEqual([{ id: 'a', strength: -0.5 }, { id: 'b', strength: 0.3 }])+ })++ it('clamps and snaps the middle to exactly zero', () => {+ expect(clampStrength(3)).toBe(1)+ expect(clampStrength(-3)).toBe(-1)+ expect(clampStrength(0.011)).toBe(0)+ expect(clampStrength(Number.NaN)).toBe(0)+ expect(clampStrength(0.333)).toBe(0.33)+ })++ it('compares entry lists by value', () => {+ expect(sameEntries([{ id: 'a', strength: 0.5 }], [{ id: 'a', strength: 0.5 }])).toBe(true)+ expect(sameEntries([{ id: 'a', strength: 0.5 }], [{ id: 'a', strength: 0.6 }])).toBe(false)+ expect(sameEntries([], [])).toBe(true)+ })+})++describe('neuron warnings', () => {+ it('warns at high strength and louder with several strong sliders', () => {+ expect(strengthWarning([{ id: 'a', strength: 0.5 }])).toBeNull()+ expect(strengthWarning([{ id: 'a', strength: 0.9 }])).toBe('strong')+ expect(strengthWarning([{ id: 'a', strength: 0.6 }, { id: 'b', strength: -0.6 }])).toBe('strong')+ expect(strengthWarning([{ id: 'a', strength: 1 }, { id: 'b', strength: 0.8 }])).toBe('overload')+ })++ it('names the backend that cannot be steered', () => {+ expect(backendNote('lu-engine')).toBeNull()+ expect(backendNote('ollama')).toMatch(/Ollama takes no control vectors/)+ expect(backendNote('cloud')).toMatch(/Cloud/)+ })+})++describe('neuron progress', () => {+ it('reads a download like the other downloads: MB, %, speed, time left', () => {+ const j = job({ kind: 'download', bytesDone: 12e6, bytesTotal: 42e6, rateBps: 3.1e6, etaSecs: 9 })+ expect(jobProgressText(j)).toBe('12 MB of 42 MB · 29% · 3.1 MB/s · 9 s left')+ })++ it('reads a computation as examples and steps', () => {+ expect(jobProgressText(job({ phaseLabel: 'Reading the examples through the model', step: 12, total: 40, etaSecs: 20 })))+ .toBe('Example 12 of 40 · 30% · 20 s left')+ expect(jobProgressText(job({ phaseLabel: 'Finding the strongest setting', step: 3, total: 12, etaSecs: 70 })))+ .toBe('Step 3 of 12 · 25% · 1 min left')+ expect(jobProgressText(job({ elapsedSecs: 5 }))).toBe('running for 5 s')+ })++ it('knows its share only when something is counted', () => {+ expect(jobShare(job({}))).toBeNull()+ expect(jobShare(job({ step: 5, total: 10 }))).toBe(0.5)+ expect(jobShare(job({ bytesDone: 50, bytesTotal: 100, step: 1, total: 10 }))).toBe(0.5)+ })++ it('writes durations short', () => {+ expect(shortDuration(42)).toBe('42 s')+ expect(shortDuration(150)).toBe('3 min')+ expect(shortDuration(3900)).toBe('1 h 5 min')+ })+})diff --git a/src/lib/neuron.ts b/src/lib/neuron.tsnew file mode 100644index 00000000..edccca88--- /dev/null+++ b/src/lib/neuron.ts@@ -0,0 +1,128 @@+// The Neuron tweaker's rules that need no backend: which slider values apply+// to which chat, how a job's progress reads, when to warn.++import type { NeuronEntry, NeuronJob } from '../api/neuron'++/** Slider values by vector id, −1 … +1. */+export type Strengths = Record<string, number>++/** All profiles: one per model, and optionally one per model and persona. */+export type Profiles = Record<string, Strengths>++export function modelProfileKey(modelKey: string): string {+ return modelKey+}++export function personaProfileKey(modelKey: string, personaId: string): string {+ return `${modelKey}::persona:${personaId}`+}++/** A persona's own profile wins over the model's; without one the model's+ * applies. */+export function effectiveStrengths(profiles: Profiles, modelKey: string, personaId: string | null | undefined): Strengths {+ if (personaId) {+ const own = profiles[personaProfileKey(modelKey, personaId)]+ if (own) return own+ }+ return profiles[modelProfileKey(modelKey)] ?? {}+}++export function hasPersonaProfile(profiles: Profiles, modelKey: string, personaId: string): boolean {+ return personaProfileKey(modelKey, personaId) in profiles+}++export function clampStrength(v: number): number {+ if (!Number.isFinite(v)) return 0+ // Two decimals, so a slider dragged back to the middle is exactly 0 and the+ // mix (and with it the engine) is exactly the unsteered one.+ const r = Math.round(Math.max(-1, Math.min(1, v)) * 100) / 100+ return Math.abs(r) < 0.02 ? 0 : r+}++/** What goes to Rust: only sliders that are on and computed for this model. */+export function entriesFor(strengths: Strengths, available: ReadonlySet<string>): NeuronEntry[] {+ return Object.entries(strengths)+ .map(([id, s]) => ({ id, strength: clampStrength(s) }))+ .filter((e) => e.strength !== 0 && available.has(e.id))+ .sort((a, b) => a.id.localeCompare(b.id))+}++export function sameEntries(a: NeuronEntry[], b: NeuronEntry[]): boolean {+ return a.length === b.length && a.every((e, i) => e.id === b[i].id && e.strength === b[i].strength)+}++export type StrengthWarning = null | 'strong' | 'overload'++/** Each slider's ±1 is just under where its own answer broke when measured.+ * Near that, and with several sliders pushing at once, text can still turn+ * odd on other questions. */+export function strengthWarning(entries: NeuronEntry[]): StrengthWarning {+ const load = entries.reduce((sum, e) => sum + Math.abs(e.strength), 0)+ if (load > 1.5) return 'overload'+ if (entries.some((e) => Math.abs(e.strength) > 0.75) || load > 1) return 'strong'+ return null+}++export function warningText(w: StrengthWarning): string | null {+ if (w === 'overload') return 'Several strong sliders at once: answers may repeat themselves or fall apart. Turn some down.'+ if (w === 'strong') return 'High strength: the effect is strongest here, and so is the risk of odd or repeating text.'+ return null+}++export function shortDuration(secs: number): string {+ const s = Math.max(0, Math.round(secs))+ if (s < 60) return `${s} s`+ const m = Math.round(s / 60)+ if (m < 60) return `${m} min`+ const h = Math.floor(m / 60)+ return `${h} h ${m % 60} min`+}++function mb(bytes: number): string {+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(2)} GB`+ return `${Math.round(bytes / 1e6)} MB`+}++/** Share done, 0…1, or null when it is not known yet. */+export function jobShare(job: NeuronJob): number | null {+ if (job.bytesTotal > 0) return Math.min(1, job.bytesDone / job.bytesTotal)+ if (job.total > 0) return Math.min(1, job.step / job.total)+ return null+}++/** One line under the bar: "12 MB of 42 MB · 29% · 3.1 MB/s · 9 s left" for+ * a download, "Example 12 of 40 · 30% · 20 s left" for a computation. */+export function jobProgressText(job: NeuronJob): string {+ const parts: string[] = []+ const share = jobShare(job)+ if (job.bytesTotal > 0) {+ parts.push(`${mb(job.bytesDone)} of ${mb(job.bytesTotal)}`)+ } else if (job.total > 0) {+ parts.push(job.kind === 'build' && /example/i.test(job.phaseLabel) ? `Example ${job.step} of ${job.total}` : `Step ${job.step} of ${job.total}`)+ }+ if (share != null) parts.push(`${Math.round(share * 100)}%`)+ if (job.bytesTotal > 0 && job.rateBps > 0) parts.push(`${(job.rateBps / 1e6).toFixed(1)} MB/s`)+ if (job.etaSecs != null && job.status === 'running' && share != null && share < 1) parts.push(`${shortDuration(job.etaSecs)} left`)+ if (parts.length === 0 && job.elapsedSecs > 0) parts.push(`running for ${shortDuration(job.elapsedSecs)}`)+ return parts.join(' · ')+}++/** Where the tweaker works, in one line for the panel. */+export type BackendKind = 'lu-engine' | 'ollama' | 'lmstudio' | 'cloud' | 'other' | 'none'++export function backendNote(kind: BackendKind): string | null {+ switch (kind) {+ case 'lu-engine':+ return null+ case 'ollama':+ return 'Your chat model runs in Ollama. Ollama takes no control vectors, so the sliders cannot reach it. Load the same model in LU Engine (Models → LU Engine) to tweak it.'+ case 'lmstudio':+ return 'Your chat model runs in LM Studio, which takes no control vectors. Load it in LU Engine to tweak it.'+ case 'cloud':+ return 'Cloud models run on servers that take no control vectors from LU. The tweaker works with local LU Engine models.'+ case 'other':+ return 'Your chat model is answered by another program, which takes no control vectors from LU. The tweaker works with LU Engine models.'+ case 'none':+ return 'Pick or download a model for LU Engine to start.'+ }+}diff --git a/src/stores/neuronStore.ts b/src/stores/neuronStore.tsnew file mode 100644index 00000000..e8bb9ad4--- /dev/null+++ b/src/stores/neuronStore.ts@@ -0,0 +1,61 @@+import { create } from 'zustand'+import { persist } from 'zustand/middleware'+import { safeJSONStorage } from '../lib/storage-quota'+import { clampStrength, modelProfileKey, personaProfileKey, type Profiles, type Strengths } from '../lib/neuron'++/**+ * The Neuron tweaker's slider values (3.0.9, P11), saved per model and,+ * when someone chooses so, per model and persona.+ *+ * The vectors themselves live on disk in Rust's neuron folder; what the+ * engine runs with right now is Rust's too (active.json). This store only+ * remembers where each slider was, so a persona switch can bring its own+ * settings back.+ */+interface NeuronState {+ profiles: Profiles+ /** Which profile the panel edits for a model: the model's own, or the+ * active persona's. Keyed by model key. */+ scopeByModel: Record<string, 'model' | 'persona'>+ setStrength: (key: string, id: string, value: number) => void+ setProfile: (key: string, strengths: Strengths) => void+ removeProfile: (key: string) => void+ removeSlider: (modelKey: string, id: string) => void+ setScope: (modelKey: string, scope: 'model' | 'persona') => void+}++export const useNeuronStore = create<NeuronState>()(+ persist(+ (set) => ({+ profiles: {},+ scopeByModel: {},+ setStrength: (key, id, value) =>+ set((s) => ({ profiles: { ...s.profiles, [key]: { ...(s.profiles[key] ?? {}), [id]: clampStrength(value) } } })),+ setProfile: (key, strengths) => set((s) => ({ profiles: { ...s.profiles, [key]: strengths } })),+ removeProfile: (key) =>+ set((s) => {+ const next = { ...s.profiles }+ delete next[key]+ return { profiles: next }+ }),+ removeSlider: (modelKey, id) =>+ set((s) => {+ const next: Profiles = {}+ for (const [k, v] of Object.entries(s.profiles)) {+ if (k === modelKey || k.startsWith(`${modelKey}::persona:`)) {+ const { [id]: _gone, ...rest } = v+ next[k] = rest+ } else next[k] = v+ }+ return { profiles: next }+ }),+ setScope: (modelKey, scope) => set((s) => ({ scopeByModel: { ...s.scopeByModel, [modelKey]: scope } })),+ }),+ { name: 'lu-neuron-tweaker', storage: safeJSONStorage() },+ ),+)++/** The profile key the panel edits for this model and persona. */+export function editingKey(modelKey: string, personaId: string, scope: 'model' | 'persona'): string {+ return scope === 'persona' ? personaProfileKey(modelKey, personaId) : modelProfileKey(modelKey)+}diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.tsindex 9619410e..72fc9864 100644--- a/src/stores/uiStore.ts+++ b/src/stores/uiStore.ts@@ -3,7 +3,7 @@ import { persist } from 'zustand/middleware'import { safeJSONStorage } from '../lib/storage-quota'import type { SettingsTab } from '../lib/settings-reset'-export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark' | 'voice'+export type View = 'chat' | 'models' | 'settings' | 'create' | 'benchmark' | 'voice' | 'neuron'/** Which collapsible section of the Settings page a deep link wants open.* Only sections a hint elsewhere in the app sends people to. */