Skip to content

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.

feat(neuron): single MLP neurons as sliders (neuron_mlp_add)

purple5875acf871f6
diff --git a/dev-server/remote-stubs.ts b/dev-server/remote-stubs.ts
index 261ca170..0eed5b52 100644
--- a/dev-server/remote-stubs.ts
+++ b/dev-server/remote-stubs.ts
@@ -100,7 +100,7 @@ export function registerRemoteStubs(routes: RouteMount): void {
'/local-api/abliterate-plan', '/local-api/abliterate-start', '/local-api/abliterate-status',
'/local-api/abliterate-cancel', '/local-api/abliterate-dismiss', '/local-api/abliterate-runs',
'/local-api/abliterate-trash-copy',
- '/local-api/neuron-presets', '/local-api/neuron-info', '/local-api/neuron-build', '/local-api/neuron-feature-add', '/local-api/neuron-delete', '/local-api/neuron-sae-download', '/local-api/neuron-sae-search', '/local-api/neuron-status', '/local-api/neuron-cancel', '/local-api/neuron-dismiss', '/local-api/neuron-apply', '/local-api/neuron-compare',
+ '/local-api/neuron-presets', '/local-api/neuron-info', '/local-api/neuron-build', '/local-api/neuron-feature-add', '/local-api/neuron-mlp-add', '/local-api/neuron-delete', '/local-api/neuron-sae-download', '/local-api/neuron-sae-search', '/local-api/neuron-status', '/local-api/neuron-cancel', '/local-api/neuron-dismiss', '/local-api/neuron-apply', '/local-api/neuron-compare',
]) {
routes.use(path, (_req, res) => {
res.writeHead(501, { 'Content-Type': 'application/json' })
diff --git a/scripts/llama-patches/0004-cvector-generator-layer-norms.patch b/scripts/llama-patches/0004-cvector-generator-layer-norms.patch
new file mode 100644
index 00000000..15fd8106
--- /dev/null
+++ b/scripts/llama-patches/0004-cvector-generator-layer-norms.patch
@@ -0,0 +1,69 @@
+--- a/tools/cvector-generator/cvector-generator.cpp
++++ b/tools/cvector-generator/cvector-generator.cpp
+@@ -9,6 +9,9 @@
+ #include "mean.hpp"
+
+ #include <clocale>
++#include <algorithm>
++#include <cmath>
++#include <cstdlib>
+
+ #ifdef GGML_USE_CUDA
+ #include "ggml-cuda.h"
+@@ -466,6 +469,14 @@ int main(int argc, char ** argv) {
+
+ std::cout << "n_total_tokens: " << n_total_tokens << std::endl;
+
++ // LU: with LU_LAYER_NORMS set the tool measures instead of building a
++ // vector: the length of the residual stream after each block, over every
++ // token but the first, for the positive lines. The app takes the median
++ // per block as the unit of a single-neuron slider (the unit neuron
++ // recipes are shared in). The negative lines are not read.
++ const bool lu_norms = getenv("LU_LAYER_NORMS") != nullptr;
++ std::vector<std::vector<float>> lu_norms_by_layer;
++
+ for(size_t i = 0; i < ctx_train.positive_entries.size(); ++i) {
+ bool success = false;
+ tokenized_prompt t = tokenized_prompts[i];
+@@ -485,6 +496,23 @@ int main(int argc, char ** argv) {
+ success = get_hidden_layers(ctx, t.tokens_pos);
+ if (!success) break;
+
++ if (lu_norms) {
++ lu_norms_by_layer.resize(cb_data.v_pos.size());
++ for (size_t il = 0; il < cb_data.v_pos.size(); il++) {
++ const ggml_tensor * h = cb_data.v_pos[il];
++ for (int64_t r = 1; r < h->ne[1]; r++) {
++ const float * row = (const float *) ((const char *) h->data + r * h->nb[1]);
++ double sum = 0.0;
++ for (int64_t j = 0; j < h->ne[0]; j++) {
++ sum += (double) row[j] * row[j];
++ }
++ lu_norms_by_layer[il].push_back((float) std::sqrt(sum));
++ }
++ }
++ cb_data.reset();
++ continue;
++ }
++
+ cb_data.is_eval_pos = false;
+ success = get_hidden_layers(ctx, t.tokens_neg);
+ if (!success) break;
+@@ -506,6 +534,17 @@ int main(int argc, char ** argv) {
+ cb_data.reset();
+ }
+
++ if (lu_norms) {
++ for (size_t il = 0; il < lu_norms_by_layer.size(); il++) {
++ auto & v = lu_norms_by_layer[il];
++ if (v.empty()) continue;
++ std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
++ printf("LU norm %d %.6f\n", (int) il, v[v.size() / 2]);
++ }
++ fflush(stdout);
++ return 0;
++ }
++
+ // done with the model, we can now free it to make gain some memory
+ printf("Done evaluate prompts, unload model...\n");
+
diff --git a/scripts/neuron/column-check.py b/scripts/neuron/column-check.py
new file mode 100644
index 00000000..79528250
--- /dev/null
+++ b/scripts/neuron/column-check.py
@@ -0,0 +1,31 @@
+"""Checks LU's single-neuron column read (src-tauri/src/commands/neuron/weights.rs)
+against llama.cpp's own gguf-py on a real model.
+
+Run with python3 -I and the llama.cpp checkout's gguf-py on the path:
+ python3 -I scripts/neuron/column-check.py <llama.cpp>/gguf-py model.gguf LAYER NEURON lu-column.txt
+The last file is what `LU_COLUMN_CHECK=model|layer|neuron|file cargo test a_real_column -- --ignored` wrote.
+"""
+import sys
+
+import types
+
+sys.path.insert(0, sys.argv[1])
+# gguf-py's metadata module imports yaml for model cards; nothing here reads one.
+sys.modules.setdefault("yaml", types.ModuleType("yaml"))
+import numpy as np # noqa: E402
+from gguf import GGUFReader # noqa: E402
+from gguf.quants import dequantize # noqa: E402
+
+model, layer, neuron, lu_file = sys.argv[2], sys.argv[3], int(sys.argv[4]), sys.argv[5]
+name = f"blk.{layer}.ffn_down.weight" if layer.isdigit() else layer
+r = GGUFReader(model)
+t = next(t for t in r.tensors if t.name == name)
+w = dequantize(t.data, t.tensor_type) # shape [n_embd, n_ff]
+ref = w[:, neuron].astype(np.float64)
+lines = open(lu_file).read().split()
+n_ff, lu = int(lines[0]), np.array([float(x) for x in lines[1:]])
+assert n_ff == w.shape[1], (n_ff, w.shape)
+assert lu.shape == ref.shape, (lu.shape, ref.shape)
+err = np.max(np.abs(lu - ref)) / max(np.max(np.abs(ref)), 1e-30)
+print(f"{t.tensor_type.name:6s} n_embd={w.shape[0]} n_ff={n_ff} max rel. error {err:.2e} -> {'OK' if err < 1e-5 else 'MISMATCH'}")
+sys.exit(0 if err < 1e-5 else 1)
diff --git a/src-tauri/src/commands/gguf.rs b/src-tauri/src/commands/gguf.rs
index 327c8fbb..1dc046a1 100644
--- a/src-tauri/src/commands/gguf.rs
+++ b/src-tauri/src/commands/gguf.rs
@@ -519,6 +519,11 @@ fn read_meta(r: &mut R, ty: u32) -> Option<Meta> {
/// Read a GGUF head from any reader: every key and the tensor table, nothing
/// of the data behind it.
pub fn parse_head(reader: &mut dyn Read) -> Option<GgufHead> {
+ parse_head_with_offsets(reader).map(|(h, _)| h)
+}
+
+/// `parse_head` plus each tensor's offset inside the data section.
+fn parse_head_with_offsets(reader: &mut dyn Read) -> Option<(GgufHead, Vec<u64>)> {
let mut r = R(reader);
let mut magic = [0u8; 4];
r.0.read_exact(&mut magic).ok()?;
@@ -542,6 +547,7 @@ pub fn parse_head(reader: &mut dyn Read) -> Option<GgufHead> {
head.keys.insert(key, val);
}
head.tensors.reserve(tensor_count.min(65_536) as usize);
+ let mut offsets = Vec::with_capacity(tensor_count.min(65_536) as usize);
for _ in 0..tensor_count {
let name = r.string(MAX_TENSOR_NAME)?;
let n_dims = r.u32()?;
@@ -553,10 +559,60 @@ pub fn parse_head(reader: &mut dyn Read) -> Option<GgufHead> {
dims.push(r.u64()?);
}
let ggml_type = r.u32()?;
- let _offset = r.u64()?;
+ offsets.push(r.u64()?);
head.tensors.push(TensorInfo { name, dims, ggml_type });
}
- Some(head)
+ Some((head, offsets))
+}
+
+/// Counts what goes through, so the end of the head is known.
+struct Counted<T> {
+ inner: T,
+ read: u64,
+}
+
+impl<T: Read> Read for Counted<T> {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ let n = self.inner.read(buf)?;
+ self.read += n as u64;
+ Ok(n)
+ }
+}
+
+/// Where one tensor's bytes are in a model file (3.0.9, P11: a neuron's
+/// weights are read straight from the user's own GGUF).
+#[derive(Debug, Clone, PartialEq)]
+pub struct TensorAt {
+ pub info: TensorInfo,
+ pub file: std::path::PathBuf,
+ /// Absolute byte position of the tensor's first block in `file`.
+ pub at: u64,
+}
+
+/// Finds a tensor by name in a model, in whichever part of a split model
+/// holds it. The data section starts after the head, at the file's alignment
+/// (`general.alignment`, 32 when absent).
+pub fn locate_tensor(path: &str, name: &str) -> Option<TensorAt> {
+ let first = std::path::Path::new(path);
+ let mut files = vec![first.to_path_buf()];
+ let head = read_model_head(path)?;
+ let parts = head.split_count();
+ if parts > 1 {
+ files = split_parts(first, parts)?;
+ }
+ for file in files {
+ let mut c = Counted { inner: BufReader::new(File::open(&file).ok()?), read: 0 };
+ let (h, offsets) = parse_head_with_offsets(&mut c)?;
+ let align = match h.keys.get("general.alignment") {
+ Some(Meta::Int(a)) if *a > 0 => *a as u64,
+ _ => 32,
+ };
+ let data = c.read.div_ceil(align) * align;
+ if let Some(i) = h.tensors.iter().position(|t| t.name == name) {
+ return Some(TensorAt { info: h.tensors[i].clone(), file, at: data.checked_add(offsets[i])? });
+ }
+ }
+ None
}
/// The sibling parts of a split model (`name-00001-of-00003.gguf`), in order,
@@ -950,6 +1006,25 @@ mod tests {
assert!(super::parse_head(&mut &raw[..raw.len() - 3]).is_none());
}
+ #[test]
+ fn a_tensor_is_found_where_its_bytes_are() {
+ let dir = fixtures("locate");
+ let p = dir.join("m.gguf");
+ let mut raw = head_with_tensor(None, "blk.3.ffn_down.weight");
+ let head_len = raw.len() as u64;
+ // Data starts at the next multiple of 32 after the head; the offset
+ // in the table is 0.
+ let data = head_len.div_ceil(32) * 32;
+ raw.resize(data as usize, 0);
+ raw.extend_from_slice(b"WEIGHTS");
+ std::fs::write(&p, &raw).unwrap();
+ let t = super::locate_tensor(p.to_str().unwrap(), "blk.3.ffn_down.weight").expect("found");
+ assert_eq!(t.at, data);
+ assert_eq!(t.info.dims, vec![4096, 4096]);
+ assert_eq!(&std::fs::read(&p).unwrap()[t.at as usize..t.at as usize + 7], b"WEIGHTS");
+ assert!(super::locate_tensor(p.to_str().unwrap(), "blk.9.ffn_down.weight").is_none());
+ }
+
#[test]
fn a_split_model_is_read_with_the_tensors_of_every_part() {
let dir = fixtures("split");
diff --git a/src-tauri/src/commands/neuron/mod.rs b/src-tauri/src/commands/neuron/mod.rs
index b586eea5..b7f6d633 100644
--- a/src-tauri/src/commands/neuron/mod.rs
+++ b/src-tauri/src/commands/neuron/mod.rs
@@ -40,6 +40,7 @@ pub mod estimate;
pub mod model;
pub mod presets;
pub mod sae;
+pub mod weights;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
@@ -94,7 +95,7 @@ fn model_dir(root: &Path, model_path: &str) -> PathBuf {
/// 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 == '-')
+ !id.is_empty() && id.len() <= 48 && id.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || (id.starts_with("n-L") && (c == 'L' || c == 'N')))
}
// ── what is active ────────────────────────────────────────────────────────
@@ -199,10 +200,14 @@ fn save_meta(root: &Path, model_path: &str, meta: &VectorMeta) -> Result<(), Str
#[serde(rename_all = "camelCase")]
pub struct Entry {
pub id: String,
- /// −1 … +1, clamped.
+ /// −1 … +1, clamped; a single neuron's dose up to ±`NEURON_MAX_DOSE`.
pub strength: f32,
}
+/// Neuron recipes go past 1 (1.5 is shared as "strong"); N2's recipe code
+/// stops at the same 3.
+pub const NEURON_MAX_DOSE: f32 = 3.0;
+
/// 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.
@@ -211,11 +216,12 @@ pub fn mix(root: &Path, model_path: &str, n_embd: usize, entries: &[Entry]) -> R
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() {
+ if e.strength == 0.0 || !e.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 limit = if meta.kind == "neuron" { NEURON_MAX_DOSE } else { 1.0 };
+ let strength = e.strength.clamp(-limit, limit);
let v = match (&meta.sae, meta.feature) {
(Some(sae_id), Some(f)) => {
let spec = sae::by_id(sae_id).ok_or("Unknown feature set.")?;
@@ -426,39 +432,38 @@ pub fn tool_failure(stderr: &str) -> String {
}
}
-/// 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> {
+/// What one run of the vector tool printed that LU reads: the layer
+/// lengths of a measuring run (patch 0004), parsed, never the raw lines.
+struct ToolRun {
+ norms: BTreeMap<usize, f32>,
+}
+
+/// Runs the vector tool with `args` (and `env`), shows its progress lines
+/// on the job, stops it on cancel, and turns a failure into one sentence.
+fn run_tool(app: &tauri::AppHandle, args: &[std::ffi::OsString], env: &[(&str, &str)]) -> Result<ToolRun, String> {
let binary = generator_binary(app).ok_or("This install of LU is missing its vector tool (lu-llama-cvector-generator). Reinstall LU to bring it back.")?;
- std::fs::create_dir_all(work).map_err(|e| crate::os_error::english(&e))?;
- 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| crate::os_error::english(&e))?;
- std::fs::write(&neg, minus.join("\n") + "\n").map_err(|e| crate::os_error::english(&e))?;
- 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(TOOL_ARGS)
- .stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
+ cmd.args(args).args(TOOL_ARGS).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
+ for (k, v) in env {
+ cmd.env(k, v);
+ }
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 ran = Instant::now();
let mut child = cmd.spawn().map_err(|e| format!("The vector tool did not start: {}", crate::os_error::english(&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 || {
+ let mut norms = BTreeMap::new();
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));
+ } else if let Some((layer, len)) = parse_norm(&line) {
+ norms.insert(layer, len);
}
}
+ norms
});
let status = loop {
if CANCEL.load(Ordering::SeqCst) {
@@ -472,9 +477,9 @@ fn generate(app: &tauri::AppHandle, model_path: &str, plus: &[String], minus: &[
}
std::thread::sleep(std::time::Duration::from_millis(200));
};
- let _ = watcher.join();
+ let norms = watcher.join().unwrap_or_default();
tracing::info!(target: "neuron", pid = id, ?status, "vector tool finished");
- if !status.success() || !out.is_file() {
+ if !status.success() {
let why = stderr.map(|(buf, _)| crate::commands::shell::captured_text(&buf)).unwrap_or_default();
let tail: Vec<&str> = why.lines().rev().take(12).collect::<Vec<_>>().into_iter().rev().collect();
for line in &tail {
@@ -483,8 +488,27 @@ fn generate(app: &tauri::AppHandle, model_path: &str, plus: &[String], minus: &[
return Err(tool_failure(&why));
}
with_job(|j| j.step = j.total);
+ Ok(ToolRun { norms })
+}
+
+/// 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> {
+ std::fs::create_dir_all(work).map_err(|e| crate::os_error::english(&e))?;
+ 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| crate::os_error::english(&e))?;
+ std::fs::write(&neg, minus.join("\n") + "\n").map_err(|e| crate::os_error::english(&e))?;
+ let _ = std::fs::remove_file(&out);
+ let ran = Instant::now();
+ let args: Vec<std::ffi::OsString> = vec!["-m".into(), model_path.into(), "--positive-file".into(), pos.clone().into(), "--negative-file".into(), neg.clone().into(), "-o".into(), out.clone().into()];
+ run_tool(app, &args, &[])?;
+ if !out.is_file() {
+ return Err(tool_failure(""));
+ }
let bytes = std::fs::metadata(model_path).map(|m| m.len()).unwrap_or(0);
- if let (Some(key), Some(speed)) = (estimate::tool_key(&binary), estimate::speed_of_run(ran.elapsed().as_secs_f64(), bytes, plus.len())) {
+ let key = generator_binary(app).and_then(|b| estimate::tool_key(&b));
+ if let (Some(key), Some(speed)) = (key, estimate::speed_of_run(ran.elapsed().as_secs_f64(), bytes, plus.len())) {
estimate::remember(&root().join(SPEED_FILE), &key, speed);
}
let cv = cvec::read(&out)?;
@@ -493,6 +517,86 @@ fn generate(app: &tauri::AppHandle, model_path: &str, plus: &[String], minus: &[
Ok(cv)
}
+// ── single MLP neurons (3.0.9, David 31.10.2026) ──────────────────────────
+//
+// Neuron recipes are shared as `L13N7956-1.0`: block 13, MLP neuron 7956,
+// dose −1. A dose of 1 adds the neuron's write direction (column 7956 of
+// block 13's down projection, made length 1) scaled to the median length of
+// the residual stream after that block. That length is the unit recipes are
+// written in (neuronary / neuron-explorer), so it is measured on the user's
+// own model with a fixed text, once per model, and the slider's +1 is
+// exactly one dose. Nothing from outside is loaded: the direction comes out
+// of the user's GGUF.
+
+/// The text the layer lengths are measured on: plain everyday sentences,
+/// one prompt per line.
+const NORM_TEXT: &[&str] = &[
+ "The river runs past the old mill, where children used to watch the wheel turn on summer afternoons and fish for small silver trout in the shallows.",
+ "To make bread at home you need flour, water, salt and yeast, a warm place for the dough to rise, and a little patience before it goes into the oven.",
+ "The committee met on Tuesday to discuss the budget for next year, and after a long debate the members agreed to spend more on schools and public parks.",
+ "Light from the sun takes about eight minutes to reach the Earth, travelling through the vacuum of space at nearly three hundred thousand kilometres per second.",
+ "She opened the letter slowly, read it twice by the window, and then folded it back into the envelope without saying a word to anyone in the room.",
+ "Most programming languages let you store values in variables, repeat work with loops, and group related steps into functions that can be called again.",
+ "In the mountains the weather changes quickly, so hikers carry warm layers, enough water and a map even when the morning sky looks perfectly clear.",
+ "The museum's new exhibition shows paintings, letters and tools from the eighteenth century, telling the story of a small fishing town on the coast.",
+];
+
+const NORMS_FILE: &str = "layer-norms.json";
+
+/// The id a neuron's slider gets; N2's recipe code builds the same.
+pub fn neuron_id(layer: usize, neuron: u64) -> String {
+ format!("n-L{layer}-N{neuron}")
+}
+
+/// `LU norm <block> <median>` (patch 0004) → (block, median length).
+pub fn parse_norm(line: &str) -> Option<(usize, f32)> {
+ let mut it = line.strip_prefix("LU norm ")?.split_whitespace();
+ let layer = it.next()?.parse().ok()?;
+ let v: f32 = it.next()?.parse().ok()?;
+ (v.is_finite() && v > 0.0).then_some((layer, v))
+}
+
+/// The neuron's write direction as a one-layer control vector of length 1.
+pub fn neuron_vector(column: &[f32], layer: usize, n_embd: usize) -> Result<cvec::ControlVector, String> {
+ if column.len() != n_embd {
+ return Err(format!("The neuron's weights have {} values, the model {n_embd}.", column.len()));
+ }
+ let len = column.iter().map(|x| (*x as f64) * (*x as f64)).sum::<f64>().sqrt();
+ if !(len.is_finite() && len > 0.0) {
+ return Err("This neuron writes nothing (its weights are all zero), so turning it changes nothing.".into());
+ }
+ let mut cv = cvec::ControlVector::new(n_embd);
+ cv.layers.insert(layer, column.iter().map(|x| (*x as f64 / len) as f32).collect());
+ Ok(cv)
+}
+
+/// The median residual length after every block of this model, measured once
+/// and kept beside its vectors.
+fn layer_norms(app: &tauri::AppHandle, model_path: &str, work: &Path) -> Result<BTreeMap<usize, f32>, String> {
+ let file = model_dir(&root(), model_path).join(NORMS_FILE);
+ if let Some(known) = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice::<BTreeMap<usize, f32>>(&b).ok()).filter(|m| !m.is_empty()) {
+ return Ok(known);
+ }
+ free_the_model(app);
+ phase("Measuring the model's layers", NORM_TEXT.len() as u64);
+ std::fs::create_dir_all(work).map_err(|e| crate::os_error::english(&e))?;
+ let text = work.join("norm-text.txt");
+ std::fs::write(&text, NORM_TEXT.join("\n") + "\n").map_err(|e| crate::os_error::english(&e))?;
+ let args: Vec<std::ffi::OsString> = vec!["-m".into(), model_path.into(), "--positive-file".into(), text.clone().into(), "--negative-file".into(), text.clone().into(), "-o".into(), work.join("unused.gguf").into()];
+ let run = run_tool(app, &args, &[("LU_LAYER_NORMS", "1")])?;
+ let norms = run.norms;
+ if norms.is_empty() {
+ return Err("This install's vector tool cannot measure layers yet, which single neurons need. Update LU.".into());
+ }
+ let _ = std::fs::remove_file(&text);
+ if let Some(dir) = file.parent() {
+ let _ = std::fs::create_dir_all(dir);
+ }
+ let _ = std::fs::write(&file, serde_json::to_vec_pretty(&norms).unwrap_or_default());
+ log(format!(" layer lengths measured for {} blocks", norms.len()));
+ Ok(norms)
+}
+
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| crate::os_error::english(&e))
}
@@ -661,6 +765,7 @@ pub async fn neuron_info(app: tauri::AppHandle, model_path: String) -> Result<Va
let measured = generator_binary(&app).and_then(|b| estimate::tool_key(&b)).and_then(|k| estimate::remembered(&root.join(SPEED_FILE), &k));
let bytes = std::fs::metadata(&model_path).map(|m| m.len()).unwrap_or(0);
let (build_estimate, own_estimate) = build_estimates(bytes, facts.template, measured);
+ let n_ff = weights::neurons_per_layer(&model_path);
Ok(json!({
"facts": facts,
"modelKey": model_key(&model_path),
@@ -669,6 +774,8 @@ pub async fn neuron_info(app: tauri::AppHandle, model_path: String) -> Result<Va
"vectors": list_vectors(&root, &model_path),
"sae": sae,
"activeMix": active,
+ "mlpNeurons": n_ff.is_some(),
+ "nFf": n_ff,
"buildEstimate": build_estimate,
"ownEstimate": own_estimate,
}))
@@ -756,9 +863,42 @@ pub fn neuron_feature_add(app: tauri::AppHandle, model_path: String, feature: us
})
}
+#[tauri::command]
+pub fn neuron_mlp_add(app: tauri::AppHandle, model_path: String, layer: usize, neuron: u64) -> Result<Value, String> {
+ let facts = model::facts(&model_path)?;
+ if layer == 0 || layer + 1 >= facts.n_layer {
+ return Err(format!("Single neurons work in layers 1 to {} of this model.", facts.n_layer.saturating_sub(2)));
+ }
+ if generator_binary(&app).is_none() {
+ return Err("This install of LU is missing its vector tool (lu-llama-cvector-generator). Reinstall LU to bring it back.".into());
+ }
+ let id = neuron_id(layer, neuron);
+ start_job("neuron", &format!("Neuron L{layer} N{neuron}"), &model_path.clone(), move || {
+ let root = root();
+ let work = model_dir(&root, &model_path).join("work");
+ phase("Reading the neuron's weights", 1);
+ let (column, _) = weights::neuron_column(&model_path, layer, neuron)?;
+ let cv = neuron_vector(&column, layer, facts.n_embd)?;
+ step(1);
+ cancelled()?;
+ let norms = layer_norms(&app, &model_path, &work)?;
+ let unit = *norms.get(&layer).ok_or_else(|| format!("Layer {layer} was not measured; single neurons work in layers 1 to {}.", facts.n_layer.saturating_sub(2)))?;
+ log(format!(" dose 1 = {unit:.3} (median length after block {layer})"));
+ cvec::write(&vectors_dir(&root, &model_path).join(format!("{id}.gguf")), &cv, &facts.arch, facts.n_layer)?;
+ let meta = VectorMeta {
+ id: id.clone(), kind: "neuron".into(), name: format!("L{layer} N{neuron}"), left: "Less".into(), right: "More".into(),
+ unit, built_at: now_ms(), more: Vec::new(), less: 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_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()) {
+ if !valid_id(&id) || !(id.starts_with("own-") || id.starts_with("f-") || id.starts_with("n-L") || presets::find(&id).is_some()) {
return Err("Unknown slider.".into());
}
let dir = vectors_dir(&root(), &model_path);
@@ -1132,6 +1272,48 @@ mod tests {
assert!(mix(dir.path(), &model, 4, &[e("missing", 0.5)]).is_err());
}
+ // Single neurons (David, 31.10.2026, "Ja, in 3.0.9"): a recipe like
+ // `L13N7956-1.0` is block 13, neuron 7956, dose −1, one dose being the
+ // median residual length after that block.
+ #[test]
+ fn a_neuron_slider_is_its_unit_direction_scaled_by_the_dose() {
+ let cv = neuron_vector(&[3.0, 0.0, 4.0, 0.0], 13, 4).unwrap();
+ assert_eq!(cv.layers.keys().copied().collect::<Vec<_>>(), vec![13], "block 13 is direction.13");
+ assert_eq!(cv.layers[&13], vec![0.6, 0.0, 0.8, 0.0]);
+ assert!(neuron_vector(&[0.0; 4], 13, 4).is_err());
+ assert!(neuron_vector(&[1.0; 3], 13, 4).is_err());
+
+ 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();
+ let id = neuron_id(2, 7956);
+ assert_eq!(id, "n-L2-N7956", "the id N2's recipe code builds");
+ assert!(valid_id(&id));
+ assert!(!valid_id("n-L2-N79/56") && !valid_id("Own-x"));
+ setup_vector(dir.path(), &model, &id, 24.8);
+ let mut meta = list_vectors(dir.path(), &model).pop().unwrap();
+ meta.kind = "neuron".into();
+ save_meta(dir.path(), &model, &meta).unwrap();
+ let e = |s: f32| Entry { id: id.clone(), strength: s };
+ let m = mix(dir.path(), &model, 4, &[e(-1.0)]).unwrap().unwrap();
+ assert!((m.layers[&2][0] + 24.8).abs() < 1e-4, "dose −1 = −p50 along the neuron");
+ // Doses past 1 are recipes' "strong"; they stop at 3, not at 1.
+ let m = mix(dir.path(), &model, 4, &[e(1.5)]).unwrap().unwrap();
+ assert!((m.layers[&2][0] - 1.5 * 24.8).abs() < 1e-3);
+ let m = mix(dir.path(), &model, 4, &[e(9.0)]).unwrap().unwrap();
+ assert!((m.layers[&2][0] - 3.0 * 24.8).abs() < 1e-3);
+ }
+
+ #[test]
+ fn the_tool_s_layer_lengths_are_read() {
+ assert_eq!(parse_norm("LU norm 22 24.8"), Some((22, 24.8)));
+ assert_eq!(parse_norm("LU norm 0 6.9"), Some((0, 6.9)));
+ for bad in ["LU norm x 1", "LU norm 3 nan", "LU norm 4 -1", "LU other", "Evaluating prompt[1/8]"] {
+ assert_eq!(parse_norm(bad), None, "{bad}");
+ }
+ }
+
#[test]
fn the_same_sliders_give_the_same_file() {
let dir = tempfile::tempdir().unwrap();
diff --git a/src-tauri/src/commands/neuron/weights.rs b/src-tauri/src/commands/neuron/weights.rs
new file mode 100644
index 00000000..73879a02
--- /dev/null
+++ b/src-tauri/src/commands/neuron/weights.rs
@@ -0,0 +1,347 @@
+//! One MLP neuron's write direction, read from the user's own GGUF.
+//!
+//! A neuron `n` of block `L` writes into the residual stream along column `n`
+//! of that block's down projection. In a GGUF `blk.L.ffn_down.weight` has
+//! `ne = [n_ff, n_embd]`: one row of `n_ff` values per embedding dimension,
+//! quantized in blocks along the row. Column `n` is element `n` of every row,
+//! so for each of the `n_embd` rows one block is read and dequantized, never
+//! the whole tensor. The formulas follow ggml-quants.c `dequantize_row_*` of
+//! the pinned llama.cpp; the tests check them against gguf-py's
+//! `quants.dequantize` on real files.
+
+use crate::commands::gguf::{locate_tensor, TensorAt};
+use std::io::{Read, Seek, SeekFrom};
+
+fn f16(b: &[u8]) -> f32 {
+ let h = u16::from_le_bytes([b[0], b[1]]);
+ let sign = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
+ let exp = ((h >> 10) & 0x1f) as i32;
+ let man = (h & 0x3ff) as f32;
+ sign * match exp {
+ 0 => man * 2f32.powi(-24),
+ 31 => if man == 0.0 { f32::INFINITY } else { f32::NAN },
+ e => (1.0 + man / 1024.0) * 2f32.powi(e - 15),
+ }
+}
+
+fn scale_min_k4(j: usize, q: &[u8]) -> (f32, f32) {
+ if j < 4 {
+ ((q[j] & 63) as f32, (q[j + 4] & 63) as f32)
+ } else {
+ (((q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4)) as f32, ((q[j + 4] >> 4) | ((q[j] >> 6) << 4)) as f32)
+ }
+}
+
+/// The ggml type names LU can read a neuron from, for the message when a
+/// model uses another one.
+pub const READABLE: &str = "F32, F16, BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q2_K, Q3_K, Q4_K, Q5_K, Q6_K";
+
+/// One block of a ggml type, dequantized. `None` for a type LU does not read.
+pub fn dequantize_block(ggml_type: u32, b: &[u8]) -> Option<Vec<f32>> {
+ let mut y = Vec::new();
+ match ggml_type {
+ 0 => y.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
+ 1 => y.push(f16(b)),
+ 30 => y.push(f32::from_bits((u16::from_le_bytes([b[0], b[1]]) as u32) << 16)),
+ // Q4_0: d, 16 bytes of nibbles; low nibbles are 0..16, high 16..32.
+ 2 => {
+ let d = f16(&b[0..]);
+ let qs = &b[2..18];
+ y.resize(32, 0.0);
+ for j in 0..16 {
+ y[j] = ((qs[j] & 0xF) as i32 - 8) as f32 * d;
+ y[j + 16] = ((qs[j] >> 4) as i32 - 8) as f32 * d;
+ }
+ }
+ 3 => {
+ let (d, m) = (f16(&b[0..]), f16(&b[2..]));
+ let qs = &b[4..20];
+ y.resize(32, 0.0);
+ for j in 0..16 {
+ y[j] = (qs[j] & 0xF) as f32 * d + m;
+ y[j + 16] = (qs[j] >> 4) as f32 * d + m;
+ }
+ }
+ 6 | 7 => {
+ let one = ggml_type == 7;
+ let d = f16(&b[0..]);
+ let (m, rest) = if one { (f16(&b[2..]), &b[4..]) } else { (0.0, &b[2..]) };
+ let qh = u32::from_le_bytes([rest[0], rest[1], rest[2], rest[3]]);
+ let qs = &rest[4..20];
+ y.resize(32, 0.0);
+ for j in 0..16 {
+ let h0 = (((qh >> j) << 4) & 0x10) as u8;
+ let h1 = ((qh >> (j + 12)) & 0x10) as u8;
+ let x0 = ((qs[j] & 0xF) | h0) as i32;
+ let x1 = ((qs[j] >> 4) | h1) as i32;
+ if one {
+ y[j] = x0 as f32 * d + m;
+ y[j + 16] = x1 as f32 * d + m;
+ } else {
+ y[j] = (x0 - 16) as f32 * d;
+ y[j + 16] = (x1 - 16) as f32 * d;
+ }
+ }
+ }
+ 8 => {
+ let d = f16(&b[0..]);
+ y.extend(b[2..34].iter().map(|&q| q as i8 as f32 * d));
+ }
+ // Q2_K: scales[16], qs[64], d, dmin.
+ 10 => {
+ let (sc, qs) = (&b[0..16], &b[16..80]);
+ let (d, min) = (f16(&b[80..]), f16(&b[82..]));
+ let mut is = 0;
+ for n in (0..256).step_by(128) {
+ let q = &qs[n / 4..];
+ let mut shift = 0;
+ for _ in 0..4 {
+ for half in 0..2 {
+ let s = sc[is];
+ is += 1;
+ let (dl, ml) = (d * (s & 0xF) as f32, min * (s >> 4) as f32);
+ for l in 0..16 {
+ y.push(dl * ((q[l + 16 * half] >> shift) & 3) as f32 - ml);
+ }
+ }
+ shift += 2;
+ }
+ }
+ }
+ // Q3_K: hmask[32], qs[64], scales[12], d.
+ 11 => {
+ let (hm, qs, raw) = (&b[0..32], &b[32..96], &b[96..108]);
+ let d = f16(&b[108..]);
+ let a = |i: usize| u32::from_le_bytes([raw[4 * i], raw[4 * i + 1], raw[4 * i + 2], raw[4 * i + 3]]);
+ let (k1, k2) = (0x0303_0303u32, 0x0f0f_0f0fu32);
+ let tmp = a(2);
+ let aux = [
+ (a(0) & k2) | ((tmp & k1) << 4),
+ (a(1) & k2) | (((tmp >> 2) & k1) << 4),
+ ((a(0) >> 4) & k2) | (((tmp >> 4) & k1) << 4),
+ ((a(1) >> 4) & k2) | (((tmp >> 6) & k1) << 4),
+ ];
+ let scales: Vec<i8> = aux.iter().flat_map(|w| w.to_le_bytes()).map(|x| x as i8).collect();
+ let (mut is, mut m) = (0, 1u8);
+ for n in (0..256).step_by(128) {
+ let q = &qs[n / 4..];
+ let mut shift = 0;
+ for _ in 0..4 {
+ for half in 0..2 {
+ let dl = d * (scales[is] as i32 - 32) as f32;
+ is += 1;
+ for l in 0..16 {
+ let k = l + 16 * half;
+ let hi = if hm[k] & m != 0 { 0 } else { 4 };
+ y.push(dl * (((q[k] >> shift) & 3) as i32 - hi) as f32);
+ }
+ }
+ shift += 2;
+ m <<= 1;
+ }
+ }
+ }
+ // Q4_K: d, dmin, scales[12], qs[128].
+ 12 => {
+ let (d, min) = (f16(&b[0..]), f16(&b[2..]));
+ let (sc, qs) = (&b[4..16], &b[16..144]);
+ for (k, j) in (0..256).step_by(64).enumerate() {
+ let q = &qs[j / 2..j / 2 + 32];
+ let (s1, m1) = scale_min_k4(2 * k, sc);
+ let (s2, m2) = scale_min_k4(2 * k + 1, sc);
+ y.extend(q.iter().map(|&x| d * s1 * (x & 0xF) as f32 - min * m1));
+ y.extend(q.iter().map(|&x| d * s2 * (x >> 4) as f32 - min * m2));
+ }
+ }
+ // Q5_K: d, dmin, scales[12], qh[32], qs[128].
+ 13 => {
+ let (d, min) = (f16(&b[0..]), f16(&b[2..]));
+ let (sc, qh, qs) = (&b[4..16], &b[16..48], &b[48..176]);
+ let (mut u1, mut u2) = (1u8, 2u8);
+ for (k, j) in (0..256).step_by(64).enumerate() {
+ let q = &qs[j / 2..j / 2 + 32];
+ let (s1, m1) = scale_min_k4(2 * k, sc);
+ let (s2, m2) = scale_min_k4(2 * k + 1, sc);
+ for l in 0..32 {
+ let h = if qh[l] & u1 != 0 { 16 } else { 0 };
+ y.push(d * s1 * ((q[l] & 0xF) + h) as f32 - min * m1);
+ }
+ for l in 0..32 {
+ let h = if qh[l] & u2 != 0 { 16 } else { 0 };
+ y.push(d * s2 * ((q[l] >> 4) + h) as f32 - min * m2);
+ }
+ u1 <<= 2;
+ u2 <<= 2;
+ }
+ }
+ // Q6_K: ql[128], qh[64], scales[16] (i8), d.
+ 14 => {
+ let (ql, qh, sc) = (&b[0..128], &b[128..192], &b[192..208]);
+ let d = f16(&b[208..]);
+ y.resize(256, 0.0);
+ for half in 0..2 {
+ let (ql, qh, sc, out) = (&ql[64 * half..], &qh[32 * half..], &sc[8 * half..], 128 * half);
+ for l in 0..32 {
+ let is = l / 16;
+ let q1 = ((ql[l] & 0xF) | ((qh[l] & 3) << 4)) as i32 - 32;
+ let q2 = ((ql[l + 32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) as i32 - 32;
+ let q3 = ((ql[l] >> 4) | (((qh[l] >> 4) & 3) << 4)) as i32 - 32;
+ let q4 = ((ql[l + 32] >> 4) | (((qh[l] >> 6) & 3) << 4)) as i32 - 32;
+ y[out + l] = d * sc[is] as i8 as f32 * q1 as f32;
+ y[out + l + 32] = d * sc[is + 2] as i8 as f32 * q2 as f32;
+ y[out + l + 64] = d * sc[is + 4] as i8 as f32 * q3 as f32;
+ y[out + l + 96] = d * sc[is + 6] as i8 as f32 * q4 as f32;
+ }
+ }
+ }
+ _ => return None,
+ }
+ Some(y)
+}
+
+/// Column `col` of a 2-D tensor stored as `ne = [cols, rows]`: element `col`
+/// of every row.
+pub fn read_column(t: &TensorAt, col: u64) -> Result<Vec<f32>, String> {
+ let (cols, rows) = match t.info.dims.as_slice() {
+ [c, r] => (*c, *r),
+ _ => return Err(format!("{} is not a matrix.", t.info.name)),
+ };
+ if col >= cols {
+ return Err(format!("This layer has {cols} neurons, numbered 0 to {}.", cols - 1));
+ }
+ let (per_block, block_bytes) = crate::commands::gguf::ggml_type_block(t.info.ggml_type).ok_or("unknown weight type")?;
+ if cols % per_block != 0 {
+ return Err("The weights of this layer are not stored in whole blocks.".into());
+ }
+ let row_bytes = cols / per_block * block_bytes;
+ let mut f = std::io::BufReader::new(std::fs::File::open(&t.file).map_err(|e| crate::os_error::english(&e))?);
+ let mut block = vec![0u8; block_bytes as usize];
+ let mut out = Vec::with_capacity(rows as usize);
+ for r in 0..rows {
+ let pos = t.at + r * row_bytes + (col / per_block) * block_bytes;
+ f.seek(SeekFrom::Start(pos)).map_err(|e| crate::os_error::english(&e))?;
+ f.read_exact(&mut block).map_err(|e| crate::os_error::english(&e))?;
+ let values = dequantize_block(t.info.ggml_type, &block)
+ .ok_or_else(|| format!("This model stores the layer in a format LU cannot read for single neurons (ggml type {}). It reads {READABLE}.", t.info.ggml_type))?;
+ out.push(values[(col % per_block) as usize]);
+ }
+ Ok(out)
+}
+
+/// Neuron `neuron` of block `layer`: its write direction and the number of
+/// neurons in that block.
+pub fn neuron_column(model_path: &str, layer: usize, neuron: u64) -> Result<(Vec<f32>, u64), String> {
+ let name = format!("blk.{layer}.ffn_down.weight");
+ let t = locate_tensor(model_path, &name).ok_or_else(|| format!("Layer {layer} of this model has no dense MLP (no {name}), so it has no single neurons to turn."))?;
+ let n_ff = t.info.dims.first().copied().unwrap_or(0);
+ Ok((read_column(&t, neuron)?, n_ff))
+}
+
+/// Neurons per block, from the first block's down projection; `None` when
+/// the model has no dense MLP there (a mixture of experts, say).
+pub fn neurons_per_layer(model_path: &str) -> Option<u64> {
+ locate_tensor(model_path, "blk.0.ffn_down.weight").and_then(|t| (t.info.dims.len() == 2).then(|| t.info.dims[0]))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn h(x: f32) -> [u8; 2] {
+ // Exact for the small powers of two the tests use.
+ let bits = x.to_bits();
+ let sign = ((bits >> 16) & 0x8000) as u16;
+ let exp = ((bits >> 23) & 0xff) as i32 - 127 + 15;
+ let man = ((bits >> 13) & 0x3ff) as u16;
+ (if x == 0.0 { 0 } else { sign | ((exp as u16) << 10) | man }).to_le_bytes()
+ }
+
+ #[test]
+ fn halves_read_like_ggml() {
+ assert_eq!(f16(&h(1.0)), 1.0);
+ assert_eq!(f16(&h(-0.5)), -0.5);
+ assert_eq!(f16(&[0x00, 0x3c]), 1.0);
+ assert_eq!(f16(&[0x01, 0x00]), 2f32.powi(-24));
+ }
+
+ #[test]
+ fn q8_0_and_q4_0_blocks_dequantize() {
+ let mut b = h(0.5).to_vec();
+ b.extend((0..32).map(|i| (i as i8 - 16) as u8));
+ let y = dequantize_block(8, &b).unwrap();
+ assert_eq!(y.len(), 32);
+ assert_eq!((y[0], y[16], y[31]), (-8.0, 0.0, 7.5));
+
+ let mut b = h(2.0).to_vec();
+ b.extend((0..16).map(|j| (j as u8) | (15 - j as u8) << 4));
+ let y = dequantize_block(2, &b).unwrap();
+ assert_eq!((y[0], y[15], y[16], y[31]), (-16.0, 14.0, 14.0, -16.0));
+ }
+
+ #[test]
+ fn q4_k_uses_the_six_bit_scales() {
+ // d = 1, dmin = 0.5, scale 2 and min 1 for the first 32, q = 3.
+ let mut b = h(1.0).to_vec();
+ b.extend(h(0.5));
+ let mut sc = [0u8; 12];
+ sc[0] = 2;
+ sc[4] = 1;
+ b.extend(sc);
+ b.extend([0x03u8; 128]);
+ let y = dequantize_block(12, &b).unwrap();
+ assert_eq!(y.len(), 256);
+ assert_eq!(y[0], 2.0 * 3.0 - 0.5);
+ // The next 32 (high nibbles, scale index 1) have scale 0, min 0.
+ assert_eq!(y[32], 0.0);
+ }
+
+ #[test]
+ fn a_type_lu_does_not_read_is_named() {
+ assert!(dequantize_block(16, &[0u8; 66]).is_none());
+ }
+
+ /// Real files against gguf-py (llama.cpp's own Python reader): with
+ /// `LU_COLUMN_CHECK=model.gguf|layer|neuron|out.txt` (or a tensor name for the layer) it writes the column
+ /// LU reads; `scripts/neuron/column-check.py` dequantizes the whole
+ /// tensor with gguf-py and compares. Without the variable it does nothing.
+ #[test]
+ #[ignore = "needs a real model; run by hand with LU_COLUMN_CHECK"]
+ fn a_real_column_for_the_reference_check() {
+ let Ok(spec) = std::env::var("LU_COLUMN_CHECK") else { return };
+ let parts: Vec<&str> = spec.split('|').collect();
+ // A layer number reads a neuron; a tensor name reads that tensor
+ // (to reach types a model only uses outside the down projection).
+ let (col, n_ff) = match parts[1].parse::<usize>() {
+ Ok(layer) => neuron_column(parts[0], layer, parts[2].parse().unwrap()).unwrap(),
+ Err(_) => {
+ let t = locate_tensor(parts[0], parts[1]).unwrap();
+ (read_column(&t, parts[2].parse().unwrap()).unwrap(), t.info.dims[0])
+ }
+ };
+ let text: Vec<String> = col.iter().map(|x| format!("{x:e}")).collect();
+ std::fs::write(parts[3], format!("{n_ff}\n{}\n", text.join("\n"))).unwrap();
+ }
+
+ #[test]
+ fn a_column_is_one_element_of_every_row() {
+ // ne = [64, 3] in Q8_0: two blocks per row, d = 1, q = row*100 + col
+ // (clamped into i8 by staying small).
+ let dir = crate::os_paths::test_dir("neuron-column");
+ let p = dir.join("w.bin");
+ let mut raw = Vec::new();
+ for r in 0..3i32 {
+ for blk in 0..2i32 {
+ raw.extend(h(1.0));
+ raw.extend((0..32).map(|i| (r * 40 + blk * 32 + i - 60) as i8 as u8));
+ }
+ }
+ std::fs::write(&p, &raw).unwrap();
+ let t = TensorAt {
+ info: crate::commands::gguf::TensorInfo { name: "w".into(), dims: vec![64, 3], ggml_type: 8 },
+ file: p.clone(),
+ at: 0,
+ };
+ assert_eq!(read_column(&t, 40).unwrap(), vec![-20.0, 20.0, 60.0]);
+ assert!(read_column(&t, 64).unwrap_err().contains("0 to 63"));
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 26df478c..a96ddd63 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -775,6 +775,8 @@ pub fn run() {
#[cfg(desktop)]
commands::neuron::neuron_feature_add,
#[cfg(desktop)]
+ commands::neuron::neuron_mlp_add,
+ #[cfg(desktop)]
commands::neuron::neuron_delete,
#[cfg(desktop)]
commands::neuron::neuron_sae_download,
diff --git a/src/api/__tests__/build-llama-script.test.ts b/src/api/__tests__/build-llama-script.test.ts
index 2ad634f2..23c2a1d3 100644
--- a/src/api/__tests__/build-llama-script.test.ts
+++ b/src/api/__tests__/build-llama-script.test.ts
@@ -478,6 +478,18 @@ describe('build-llama.sh — the llama.cpp revision is pinned to a commit', { ti
expect(patch).toMatch(/^ {13}\(int\) t\.max_seq_len\);\n(\+ {8}\/\/.*\n)*\+ {8}fflush\(stdout\);$/m)
})
+ // Single neurons (David, 31.10.2026): a dose is the median length of the
+ // residual stream after the neuron's block, which only the model run can
+ // measure. The app reads these lines (neuron/mod.rs parse_norm).
+ it('the repo\'s generator patches measure the layer lengths a neuron dose is counted in', () => {
+ const patch = readFileSync(join(REPO_ROOT, 'scripts', 'llama-patches', '0004-cvector-generator-layer-norms.patch'), 'utf8')
+ expect([...patch.matchAll(/^\+\+\+ b\/(.+)$/gm)].map((m) => m[1])).toEqual(['tools/cvector-generator/cvector-generator.cpp'])
+ expect(patch).toContain('+ const bool lu_norms = getenv("LU_LAYER_NORMS") != nullptr;')
+ // The first token (BOS) is left out, as the shared recipes measure it.
+ expect(patch).toContain('+ for (int64_t r = 1; r < h->ne[1]; r++) {')
+ expect(patch).toContain('+ printf("LU norm %d %.6f\\n", (int) il, v[v.size() / 2]);')
+ })
+
it('hashes a digest of the binary it installed', () => {
const probe = join(tmp('llama-digest-'), 'artifact')
writeFileSync(probe, 'llama-server')
diff --git a/src/api/__tests__/neuron-mlp-add.test.ts b/src/api/__tests__/neuron-mlp-add.test.ts
new file mode 100644
index 00000000..824f19b8
--- /dev/null
+++ b/src/api/__tests__/neuron-mlp-add.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it, vi } from 'vitest'
+
+const call = vi.hoisted(() => vi.fn(async () => ({ started: true })))
+vi.mock('../backend', () => ({ backendCall: call }))
+
+import { neuronMlpAdd } from '../neuron'
+
+// Single neurons (David, 31.10.2026, "Ja, in 3.0.9"): N2's recipe view finds
+// this export and runs it for every `L13N7956±d` line that is not ready yet.
+describe('neuronMlpAdd', () => {
+ it('asks the backend for one neuron of the model as a slider', async () => {
+ await neuronMlpAdd('/m/Qwen3.5-4B-Q8_0.gguf', 13, 7956)
+ expect(call).toHaveBeenCalledWith('neuron_mlp_add', { modelPath: '/m/Qwen3.5-4B-Q8_0.gguf', layer: 13, neuron: 7956 })
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index a45841c1..eee576b8 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -672,6 +672,7 @@ export async function backendCall<T = unknown>(
neuron_info: { path: "/local-api/neuron-info", method: "POST" },
neuron_build: { path: "/local-api/neuron-build", method: "POST" },
neuron_feature_add: { path: "/local-api/neuron-feature-add", method: "POST" },
+ neuron_mlp_add: { path: "/local-api/neuron-mlp-add", method: "POST" },
neuron_delete: { path: "/local-api/neuron-delete", method: "POST" },
neuron_sae_download: { path: "/local-api/neuron-sae-download", method: "POST" },
neuron_sae_search: { path: "/local-api/neuron-sae-search", method: "POST" },
diff --git a/src/api/neuron.ts b/src/api/neuron.ts
index 78717e0f..86ce9563 100644
--- a/src/api/neuron.ts
+++ b/src/api/neuron.ts
@@ -13,7 +13,7 @@ export interface NeuronPreset {
export interface NeuronVector {
id: string
/** preset | own | feature */
- kind: 'preset' | 'own' | 'feature'
+ kind: 'preset' | 'own' | 'feature' | 'neuron'
name: string
left: string
right: string
@@ -46,6 +46,10 @@ export interface NeuronInfo {
vectors: NeuronVector[]
sae: NeuronSae | null
activeMix: string | null
+ /** Single MLP neurons can be turned (a dense MLP in every block). */
+ mlpNeurons?: boolean
+ /** Neurons per block, null without a dense MLP. */
+ nFf?: number | null
/** How long one slider takes on this PC, said before it starts. */
buildEstimate: NeuronEstimate
ownEstimate: NeuronEstimate
@@ -60,7 +64,7 @@ export interface NeuronEstimate {
export interface NeuronJob {
status: 'idle' | 'running' | 'done' | 'failed' | 'cancelled'
- kind: '' | 'build' | 'feature' | 'download'
+ kind: '' | 'build' | 'feature' | 'neuron' | 'download'
title: string
modelPath: string
phaseLabel: string
@@ -108,6 +112,11 @@ export const neuronBuildOwn = (modelPath: string, name: string, more: string[],
export const neuronFeatureAdd = (modelPath: string, feature: number, label?: string) =>
backendCall<{ started: boolean }>('neuron_feature_add', { modelPath, feature, label })
+/** One MLP neuron of the user's own model as a slider (`n-L{layer}-N{neuron}`),
+ * its +1 one dose of a shared recipe. Runs as a job like a build. */
+export const neuronMlpAdd = (modelPath: string, layer: number, neuron: number) =>
+ backendCall<{ started: boolean }>('neuron_mlp_add', { modelPath, layer, neuron })
+
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 })