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(abliterate): downloads show bytes, speed and time left; MMLU on 200 questions, judged against chance
purple16155f6ebb65
diff --git a/src-tauri/resources/abliterate/lu_abliterate.py b/src-tauri/resources/abliterate/lu_abliterate.pyindex 47b8ce27..8ca6b9a3 100644--- a/src-tauri/resources/abliterate/lu_abliterate.py+++ b/src-tauri/resources/abliterate/lu_abliterate.py@@ -462,11 +462,12 @@ def cmd_measure(a):from datasets import load_datasetn = a.n+ mmlu_n = a.mmlu_n or nemit("phase", phase="measure", label=a.label)harmful = load_dataset(JBB[0], "behaviors", split="harmful", revision=JBB[1])benign = load_dataset(JBB[0], "behaviors", split="benign", revision=JBB[1])mmlu = load_dataset(MMLU[0], "all", split="test", revision=MMLU[1])- total = n * 3+ total = n * 2 + mmlu_nstep = 0t0 = time.time()@@ -482,14 +483,17 @@ def cmd_measure(a):step += 1emit("measure", step=step, total=total)- correct = 0- for i in random.Random(0).sample(range(len(mmlu)), n):+ # The same questions in the same order for the original and the copy,+ # each kept as right (1) or wrong (0), so the app can count the answers+ # that changed instead of comparing two noisy totals.+ marks = []+ for i in random.Random(0).sample(range(len(mmlu)), mmlu_n):r = mmlu[i]q = r["question"] + "\n" + "\n".join(f"{l}. {c}" for l, c in zip("ABCD", r["choices"]))q += "\nAnswer with the letter only."out = chat(a.port, q, 8)m = re.search(r"\b([ABCD])\b", out.strip().upper())- correct += bool(m) and "ABCD".index(m.group(1)) == r["answer"]+ marks.append("1" if m and "ABCD".index(m.group(1)) == r["answer"] else "0")step += 1emit("measure", step=step, total=total)@@ -497,8 +501,10 @@ def cmd_measure(a):"label": a.label,"refusals": refused,"falseAlarms": false_alarms,- "mmlu": correct,+ "mmlu": marks.count("1"),"n": n,+ "mmluN": mmlu_n,+ "mmluMarks": "".join(marks),"seconds": round(time.time() - t0),}Path(a.out).write_text(json.dumps(result, indent=2))@@ -533,6 +539,7 @@ def main():e.add_argument("--out", required=True)e.add_argument("--label", required=True)e.add_argument("--n", type=int, default=50)+ e.add_argument("--mmlu-n", type=int, default=0)a = p.parse_args(){"download": cmd_download, "search": cmd_search, "merge": cmd_merge, "measure": cmd_measure}[a.cmd](a)diff --git a/src-tauri/src/commands/abliterate/mod.rs b/src-tauri/src/commands/abliterate/mod.rsindex 216c8002..13dbc7ae 100644--- a/src-tauri/src/commands/abliterate/mod.rs+++ b/src-tauri/src/commands/abliterate/mod.rs@@ -16,7 +16,9 @@//! 2. download: the safetensors of the repo at the commit the dialog showed.//! 3. check before: the ORIGINAL GGUF in a llama-server of its own, through//! the same short check as at the end (refusals on 50 JailbreakBench-//! prompts, false alarms on 50 harmless ones, 50 MMLU questions).+//! prompts, false alarms on 50 harmless ones, 200 MMLU questions, each+//! answer kept as right or wrong so the two runs compare question by+//! question).//! 4. search: Heretic's trials, without its menus (`lu_abliterate.py search`).//! A stopped run carries on from Heretic's checkpoint next time.//! 5. merge: the adapter into the original weights, shard by shard.@@ -66,8 +68,13 @@ const LLAMA_ZIP_SHA256: &str = "f18fc09e7a53fb277b6d7725d5c13f3bb9927acaaa8b6e42const REQUIREMENTS: &str = include_str!("../../../resources/abliterate/requirements.txt");const CONSTRAINTS: &str = include_str!("../../../resources/abliterate/constraints.txt");-/// Prompts per part of the check (refusals, false alarms, MMLU).+/// Prompts per refusal part of the check (refused, harmless refused).+/// JailbreakBench has 100 of each; the search never sees them.const CHECK_N: u32 = 50;+/// MMLU questions in the check. 50 left a loss of three questions inside+/// chance (3.0.8 on the box: 22 → 21 of 50), so a real loss and noise read+/// the same; 200 cost the box about a minute more per check.+const MMLU_N: u32 = 200;const LOG_LINES: usize = 160;// ── Paths ─────────────────────────────────────────────────────────────────@@ -140,6 +147,13 @@ pub struct Check {pub false_alarms: u32,pub mmlu: u32,pub n: u32,+ /// MMLU questions asked; older records asked `n`.+ #[serde(default)]+ pub mmlu_n: Option<u32>,+ /// One character per MMLU question, `1` right and `0` wrong, in the+ /// same order for both runs, so a loss can be told from chance.+ #[serde(default)]+ pub mmlu_marks: Option<String>,}/// What a finished run leaves behind, in `runs/<id>.json`.@@ -194,6 +208,10 @@ pub struct RunState {pub started_at: u64,pub elapsed_secs: u64,pub eta_secs: Option<u64>,+ /// The step counts bytes (a download): `step` of `total` bytes.+ pub bytes: bool,+ /// Bytes per second over the last seconds of a download.+ pub rate_bps: Option<u64>,pub logs: VecDeque<String>,pub error: Option<String>,pub result: Option<RunRecord>,@@ -205,6 +223,68 @@ pub struct RunState {started: Option<Instant>,#[serde(skip)]search_started: Option<(Instant, u32)>,+ #[serde(skip)]+ meter: ByteMeter,+ /// pip is on a file large enough to show (see `pip_line`).+ #[serde(skip)]+ pip_big: bool,+}++/// Speed and time left of a download from its last few seconds.+#[derive(Debug, Clone, Default)]+struct ByteMeter {+ samples: VecDeque<(Instant, u64)>,+}++impl ByteMeter {+ const WINDOW: Duration = Duration::from_secs(10);++ /// Take a reading; `(bytes per second, seconds left)` once there are+ /// a little over one second of readings. A count that goes back (a new+ /// file) starts over.+ fn sample(&mut self, at: Instant, done: u64, total: u64) -> (Option<u64>, Option<u64>) {+ if self.samples.back().is_some_and(|&(_, d)| done < d) {+ self.samples.clear();+ }+ self.samples.push_back((at, done));+ while self.samples.len() > 2 && self.samples.front().is_some_and(|&(t, _)| at.duration_since(t) > Self::WINDOW) {+ self.samples.pop_front();+ }+ let &(t0, d0) = self.samples.front().expect("just pushed");+ let secs = at.duration_since(t0).as_secs_f64();+ if secs < 1.2 {+ return (None, None);+ }+ let rate = (done - d0) as f64 / secs;+ if rate < 1.0 {+ return (Some(0), None);+ }+ let left = (total > done).then(|| ((total - done) as f64 / rate).ceil() as u64);+ (Some(rate as u64), left.or(Some(0)).filter(|_| total > 0))+ }+}++/// A download's progress: bytes done of total, with speed and time left.+fn set_bytes(r: &mut RunState, done: u64, total: u64) {+ if !r.bytes {+ r.meter = ByteMeter::default();+ }+ r.bytes = true;+ r.step = done;+ r.total = total;+ let (rate, left) = r.meter.sample(Instant::now(), done, total);+ r.rate_bps = rate;+ r.eta_secs = left;+}++/// Back to a step without a byte count (the bar shows no share).+fn clear_bytes(r: &mut RunState) {+ r.bytes = false;+ r.rate_bps = None;+ r.eta_secs = None;+ r.step = 0;+ r.total = 0;+ r.meter = ByteMeter::default();}static RUN: LazyLock<Mutex<RunState>> = LazyLock::new(|| Mutex::new(RunState { status: "idle".into(), ..Default::default() }));@@ -235,9 +315,8 @@ fn set_phase(phase: &str, label: &str) {with_run(|r| {r.phase = phase.to_string();r.phase_label = label.to_string();- r.step = 0;- r.total = 0;- r.eta_secs = None;+ clear_bytes(r);+ r.pip_big = false;});}@@ -856,7 +935,7 @@ fn run_job(app: &tauri::AppHandle, job: &Job) -> Result<RunRecord, String> {// 1. the original weightslet source_dir = job.work.join("source");set_phase("download", "Downloading the original weights");- with_run(|r| r.total = job.estimate.download_bytes);+ with_run(|r| set_bytes(r, 0, job.estimate.download_bytes));{let dir = source_dir.clone();let mut cmd = python(&py, job);@@ -869,18 +948,26 @@ fn run_job(app: &tauri::AppHandle, job: &Job) -> Result<RunRecord, String> {let result = run_python(cmd, "download", |ev| {if ev.get("event").and_then(|e| e.as_str()) == Some("bytes") {let done = ev.get("done").and_then(|v| v.as_u64()).unwrap_or(0);- with_run(|r| r.step = r.step.max(done));+ with_run(|r| {+ let (done, total) = (r.step.max(done), r.total);+ set_bytes(r, done, total)+ });}});watcher.store(false, Ordering::SeqCst);result?;- with_run(|r| r.step = r.total);+ with_run(|r| {+ let total = r.total;+ set_bytes(r, total, total)+ });}check_cancel()?;// 2. the original, checkedlet before_json = job.work.join("check-before.json");- if !before_json.is_file() {+ // A check from an older LU asked fewer MMLU questions and would not+ // compare with the copy's.+ if !check_is_current(read_json::<Check>(&before_json).as_ref()) {set_phase("check_before", "Checking the original");check_gguf(app, &py, job, &job.source, &before_json, "original")?;}@@ -1038,6 +1125,12 @@ fn run_job(app: &tauri::AppHandle, job: &Job) -> Result<RunRecord, String> {Ok(record)}+/// A saved check of the original counts only when it asked the questions+/// the copy will be asked, with each answer kept.+fn check_is_current(c: Option<&Check>) -> bool {+ c.is_some_and(|c| c.mmlu_n == Some(MMLU_N) && c.mmlu_marks.as_ref().is_some_and(|m| m.len() == MMLU_N as usize))+}+fn check_cancel() -> Result<(), String> {if cancelled() { Err(CANCELLED.into()) } else { Ok(()) }}@@ -1194,21 +1287,15 @@ fn keep_line(tail: &Arc<Mutex<VecDeque<String>>>, line: String) {}// Progress bars redraw themselves many times a second; the log keeps// the lines that say something.- let bar = line.contains('█') || line.contains("it/s]") || line.contains("s/it]");+ let bar = line.contains('█') || line.contains("it/s]") || line.contains("s/it]") || pip_progress(&line).is_some();if !bar {log(line.clone());}- // pip shows no progress outside a terminal, and the CUDA build of- // PyTorch is 2 GB: on the box the phase read "Installing PyTorch" for- // twenty minutes with nothing moving. Say at least how big it is.- if let Some(size) = big_download(&line) {- with_run(|r| {- if r.phase == "setup" {- let base = r.phase_label.split(" (").next().unwrap_or_default().to_string();- r.phase_label = format!("{base} ({size} download, this takes a while)");- }- });- }+ with_run(|r| {+ if r.phase == "setup" {+ pip_line(r, &line);+ }+ });if let Ok(mut t) = tail.lock() {t.push_back(line);while t.len() > 40 {@@ -1217,22 +1304,55 @@ fn keep_line(tail: &Arc<Mutex<VecDeque<String>>>, line: String) {}}-/// "2.0 GB" for pip's "Downloading <file> (1990.6 MB)" when the file is-/// 100 MB or more, else None.-fn big_download(line: &str) -> Option<String> {+/// pip's own words into the setup step. The CUDA build of PyTorch is 2 GB:+/// on the box the step read "Installing PyTorch" for 26 minutes with the bar+/// empty. Now a file of 20 MB or more shows its bytes, speed and time left+/// under the step's name; smaller ones pass in seconds and leave the bar as+/// it is, so it does not flicker.+fn pip_line(r: &mut RunState, line: &str) {+ let base = r.phase_label.split(": ").next().unwrap_or_default().to_string();+ if let Some((file, mb)) = pip_download(line) {+ r.pip_big = mb >= 20.0;+ if r.pip_big {+ clear_bytes(r);+ r.phase_label = format!("{base}: downloading {file}");+ }+ } else if let Some((done, total)) = pip_progress(line) {+ if r.pip_big && total > 0 {+ set_bytes(r, done, total);+ }+ } else if line.starts_with("Installing collected packages") {+ r.pip_big = false;+ clear_bytes(r);+ r.phase_label = format!("{base}: unpacking");+ }+}++/// pip's `--progress-bar raw` line: "Progress 1048576 of 1990600000".+fn pip_progress(line: &str) -> Option<(u64, u64)> {+ let (done, total) = line.trim().strip_prefix("Progress ")?.split_once(" of ")?;+ Some((done.parse().ok()?, total.parse().ok()?))+}++/// `("torch 2.14.1+cu130", 1990.6)` for pip's "Downloading <url or file>+/// (1990.6 MB)". Files without a size, or in kB, are None.+fn pip_download(line: &str) -> Option<(String, f64)> {let rest = line.trim_start().strip_prefix("Downloading ")?;- let inner = rest.rsplit_once(" (")?.1.strip_suffix(')')?;- let (num, unit) = inner.split_once(' ')?;+ let (what, inner) = rest.rsplit_once(" (")?;+ let (num, unit) = inner.strip_suffix(')')?.split_once(' ')?;let n: f64 = num.parse().ok()?;let mb = match unit {"MB" => n,"GB" => n * 1000.0,_ => return None,};- if mb < 100.0 {- return None;- }- Some(if mb >= 1000.0 { format!("{:.1} GB", mb / 1000.0) } else { format!("{mb:.0} MB") })+ let file = what.rsplit('/').next().unwrap_or(what).replace("%2B", "+").replace("%2b", "+");+ let mut parts = file.split('-');+ let name = match (parts.next(), parts.next()) {+ (Some(n), Some(v)) if file.ends_with(".whl") => format!("{n} {v}"),+ _ => file.clone(),+ };+ Some((name, mb))}/// The sentence for a failed step: a known cause in plain words, else the@@ -1261,7 +1381,12 @@ fn watch_size(dir: PathBuf) -> Arc<AtomicBool> {std::thread::spawn(move || {while flag.load(Ordering::SeqCst) {let size = dir_size(&dir);- with_run(|r| r.step = r.step.max(size));+ with_run(|r| {+ if r.phase == "download" && size > r.step {+ let total = r.total;+ set_bytes(r, size, total)+ }+ });std::thread::sleep(Duration::from_millis(800));}});@@ -1283,11 +1408,11 @@ fn dir_size(p: &Path) -> u64 {fn check_gguf(app: &tauri::AppHandle, py: &Path, job: &Job, model: &Path, out: &Path, label: &str) -> Result<(), String> {let port = free_port().ok_or("No free local port for the check.")?;let mut server = crate::commands::engine::spawn_private_server(app, &model.to_string_lossy(), port, 4096)?;- with_run(|r| r.total = (CHECK_N * 3) as u64);+ with_run(|r| r.total = (CHECK_N * 2 + MMLU_N) as u64);let mut cmd = python(py, job);cmd.env("LU_ENGINE_BEARER", crate::commands::engine_key::bearer());cmd.arg(&job.script)- .args(["measure", "--port", &port.to_string(), "--label", label, "--n", &CHECK_N.to_string(), "--out"])+ .args(["measure", "--port", &port.to_string(), "--label", label, "--n", &CHECK_N.to_string(), "--mmlu-n", &MMLU_N.to_string(), "--out"]).arg(out);let result = run_python(cmd, "check", |ev| {if ev.get("event").and_then(|e| e.as_str()) == Some("measure") {@@ -1315,10 +1440,7 @@ impl crate::private_python::Progress for RunProgress {CANCEL.clone()}fn set_download(&self, done: u64, total: u64, _speed: u64) {- with_run(|r| {- r.step = done;- r.total = total;- });+ with_run(|r| set_bytes(r, done, total));}}@@ -1346,7 +1468,9 @@ fn ensure_env(job: &Job) -> Result<PathBuf, String> {let pip = |extra: &[String]| {let mut cmd = crate::python::python_command(&vpy);cmd.env_remove("PYTHONHOME").env_remove("PYTHONPATH");- cmd.args(["-m", "pip", "install", "--disable-pip-version-check", "--no-warn-script-location", "--progress-bar", "off"]);+ // "raw" writes "Progress <done> of <total>" per file even into a+ // pipe (pip 24.1 and later; LU's Python 3.12.15 brings 25.x).+ cmd.args(["-m", "pip", "install", "--disable-pip-version-check", "--no-warn-script-location", "--progress-bar", "raw"]);cmd.args(extra);cmd};@@ -1413,10 +1537,7 @@ fn ensure_converter() -> Result<(), String> {break;}bytes.extend_from_slice(&buf[..n]);- with_run(|r| {- r.step = bytes.len() as u64;- r.total = LLAMA_ZIP_BYTES;- });+ with_run(|r| set_bytes(r, bytes.len() as u64, LLAMA_ZIP_BYTES));if bytes.len() as u64 > LLAMA_ZIP_BYTES {return Err("The converter archive is larger than expected; nothing was unpacked.".into());}@@ -1509,13 +1630,65 @@ mod tests {}#[test]- fn a_big_pip_download_is_named_with_its_size() {+ fn pip_download_lines_are_read() {let line = "Downloading https://download-r2.pytorch.org/whl/cu130/torch-2.14.1%2Bcu130-cp312-cp312-win_amd64.whl (1990.6 MB)";- assert_eq!(big_download(line).as_deref(), Some("2.0 GB"));- assert_eq!(big_download(" Downloading numpy-2.5.4-cp312-cp312-win_amd64.whl (12.6 MB)"), None);- assert_eq!(big_download(" Downloading mpmath-1.3.0-py3-none-any.whl.metadata (8.6 kB)"), None);- assert_eq!(big_download("Downloading x.whl (250.0 MB)").as_deref(), Some("250 MB"));- assert_eq!(big_download("Collecting torch"), None);+ assert_eq!(pip_download(line), Some(("torch 2.14.1+cu130".to_string(), 1990.6)));+ assert_eq!(pip_download(" Downloading numpy-2.5.4-cp312-cp312-win_amd64.whl (12.6 MB)").map(|d| d.1), Some(12.6));+ assert_eq!(pip_download(" Downloading mpmath-1.3.0-py3-none-any.whl.metadata (8.6 kB)"), None);+ assert_eq!(pip_download("Downloading x.whl (2.1 GB)").map(|d| d.1), Some(2100.0));+ assert_eq!(pip_download("Collecting torch"), None);+ assert_eq!(pip_progress("Progress 1048576 of 1990600000"), Some((1_048_576, 1_990_600_000)));+ assert_eq!(pip_progress("Progress of the night"), None);+ }++ /// The box, 3.0.8: "Installing PyTorch", an empty bar, 26 minutes.+ #[test]+ fn the_pytorch_download_shows_its_bytes_in_the_setup_step() {+ let mut r = RunState { phase: "setup".into(), phase_label: "Installing PyTorch".into(), ..Default::default() };+ pip_line(&mut r, "Collecting torch");+ pip_line(&mut r, " Downloading https://download-r2.pytorch.org/whl/cu130/torch-2.14.1%2Bcu130-cp312-cp312-win_amd64.whl (1990.6 MB)");+ assert_eq!(r.phase_label, "Installing PyTorch: downloading torch 2.14.1+cu130");+ pip_line(&mut r, "Progress 0 of 1990600000");+ pip_line(&mut r, "Progress 995300000 of 1990600000");+ assert!(r.bytes);+ assert_eq!((r.step, r.total), (995_300_000, 1_990_600_000));+ // a small file afterwards leaves the bar alone+ pip_line(&mut r, " Downloading sympy-1.14.0-py3-none-any.whl (6.3 MB)");+ pip_line(&mut r, "Progress 100 of 6300000");+ assert_eq!(r.step, 995_300_000);+ pip_line(&mut r, "Installing collected packages: mpmath, torch");+ assert_eq!(r.phase_label, "Installing PyTorch: unpacking");+ assert!(!r.bytes);+ assert_eq!(r.total, 0);+ }++ #[test]+ fn a_check_of_the_original_from_3_0_8_is_measured_again() {+ let old: Check = serde_json::from_str(r#"{"refusals":39,"falseAlarms":13,"mmlu":22,"n":50}"#).unwrap();+ assert!(!check_is_current(Some(&old)));+ assert!(!check_is_current(None));+ let new = Check { mmlu_n: Some(MMLU_N), mmlu_marks: Some("1".repeat(MMLU_N as usize)), ..old };+ assert!(check_is_current(Some(&new)));+ }++ #[test]+ fn the_byte_meter_gives_speed_and_time_left() {+ let t = Instant::now();+ let mut m = ByteMeter::default();+ assert_eq!(m.sample(t, 0, 1_000_000_000), (None, None));+ let (rate, left) = m.sample(t + Duration::from_secs(2), 20_000_000, 1_000_000_000);+ assert_eq!(rate, Some(10_000_000));+ assert_eq!(left, Some(98));+ // the window forgets a stall long ago+ m.sample(t + Duration::from_secs(30), 300_000_000, 1_000_000_000);+ let (rate, _) = m.sample(t + Duration::from_secs(32), 320_000_000, 1_000_000_000);+ assert_eq!(rate, Some(10_000_000));+ // a new file starts over+ assert_eq!(m.sample(t + Duration::from_secs(33), 5, 100), (None, None));+ // finished+ let mut m = ByteMeter::default();+ m.sample(t, 0, 100);+ assert_eq!(m.sample(t + Duration::from_secs(2), 100, 100), (Some(50), Some(0)));}#[test]diff --git a/src-tauri/src/commands/abliterate/plan.rs b/src-tauri/src/commands/abliterate/plan.rsindex b436220f..2d2d41cf 100644--- a/src-tauri/src/commands/abliterate/plan.rs+++ b/src-tauri/src/commands/abliterate/plan.rs@@ -431,8 +431,8 @@ pub fn estimate(input: &EstimateInput<'_>) -> Estimate {let per_trial = (secs_per_trial_per_b(device.kind, quantization) * p_b).max(min_secs_per_trial(device.kind));let search = per_trial * input.trials as f64;// Loading, the refusal directions, the shard merge, conversion and the- // two checks of 150 short prompts each.- let fixed = 180.0 + 60.0 * p_b + 2.0 * (60.0 + 30.0 * p_b);+ // two checks of 100 short prompts and 200 one-letter MMLU answers each.+ let fixed = 180.0 + 60.0 * p_b + 2.0 * (90.0 + 45.0 * p_b);let minutes = (search + fixed) / 60.0;let minutes_low = (minutes * 0.7).ceil().max(5.0) as u64;let minutes_high = (minutes * 1.8).ceil().max(minutes_low as f64 + 5.0) as u64;diff --git a/src/api/__tests__/abliterate.test.ts b/src/api/__tests__/abliterate.test.tsindex 452b9538..3bd4b888 100644--- a/src/api/__tests__/abliterate.test.ts+++ b/src/api/__tests__/abliterate.test.ts@@ -8,7 +8,7 @@import { describe, it, expect, vi } from 'vitest'import { readFileSync } from 'node:fs'import { resolve } from 'node:path'-import { gb, minutesRange, phaseShare, roughDuration } from '../abliterate'+import { downloadLine, gb, minutesRange, mmluVerdict, phaseShare, roughDuration, sizeText } from '../abliterate'vi.mock('../backend', () => ({ backendCall: vi.fn(), isTauri: () => false }))@@ -75,3 +75,48 @@ describe('the local render tools check the prompt themselves', () => {}})})++describe('a download as it moves (3.0.9)', () => {+ it('names bytes of total, share, speed and time left in one line', () => {+ expect(sizeText(740e6)).toBe('740 MB')+ expect(sizeText(1_990_600_000)).toBe('1.99 GB')+ expect(downloadLine({ step: 740e6, total: 1_990_600_000, rateBps: 4_200_000, etaSecs: 298 }))+ .toBe('740 MB of 1.99 GB · 37% · 4.2 MB/s · about 5 min left')+ // the first second: no speed measured yet+ expect(downloadLine({ step: 0, total: 988_097_824, rateBps: null, etaSecs: null })).toBe('0 MB of 988 MB · 0%')+ expect(downloadLine({ step: 900e6, total: 988e6, rateBps: 800_000, etaSecs: 40 })).toBe('900 MB of 988 MB · 91% · 800 kB/s · 40 s left')+ })+})++describe('the knowledge check, read honestly (3.0.9)', () => {+ const marks = (right: number, n: number) => '1'.repeat(right) + '0'.repeat(n - right)+ it('3.0.8 had no marks: a small change is reported, not judged', () => {+ const v = mmluVerdict({ refusals: 39, falseAlarms: 13, mmlu: 22, n: 50 }, { refusals: 3, falseAlarms: 2, mmlu: 21, n: 50 })+ expect(v.reading).toBe('chance')+ expect(v.text).toBe('-1 of 50 questions; too few to tell a loss from chance')+ })+ it('counts the answers that changed and calls a small net change chance', () => {+ // 90 right before; the copy loses 6 of them and gains 3 others+ const before = { refusals: 0, falseAlarms: 0, mmlu: 90, n: 50, mmluN: 200, mmluMarks: marks(90, 200) }+ const a = before.mmluMarks.split('')+ for (let i = 0; i < 6; i++) a[i] = '0'+ for (let i = 90; i < 93; i++) a[i] = '1'+ const after = { ...before, mmlu: 87, mmluMarks: a.join('') }+ const v = mmluVerdict(before, after)+ expect([v.worse, v.better, v.delta]).toEqual([6, 3, -3])+ expect(v.reading).toBe('chance')+ expect(v.text).toBe('6 answers turned wrong, 3 answers turned right (-3 of 200): within chance')+ })+ it('a loss larger than chance is called a loss, in points', () => {+ const before = { refusals: 0, falseAlarms: 0, mmlu: 100, n: 50, mmluN: 200, mmluMarks: marks(100, 200) }+ const a = before.mmluMarks.split('')+ for (let i = 0; i < 20; i++) a[i] = '0'+ const v = mmluVerdict(before, { ...before, mmlu: 80, mmluMarks: a.join('') })+ expect(v.reading).toBe('loss')+ expect(v.text).toContain('a real loss of 10.0 points')+ })+ it('identical answers say so', () => {+ const c = { refusals: 0, falseAlarms: 0, mmlu: 88, n: 50, mmluN: 200, mmluMarks: marks(88, 200) }+ expect(mmluVerdict(c, c).text).toBe('All 200 answers the same as the original')+ })+})diff --git a/src/api/abliterate.ts b/src/api/abliterate.tsindex e024f36a..120878e5 100644--- a/src/api/abliterate.ts+++ b/src/api/abliterate.ts@@ -74,6 +74,10 @@ export interface Check {falseAlarms: numbermmlu: numbern: number+ /** MMLU questions asked; records before 3.0.9 asked `n`. */+ mmluN?: number | null+ /** '1' right, '0' wrong per question, same order in both checks. */+ mmluMarks?: string | null}export interface RunRecord {@@ -119,6 +123,9 @@ export interface RunStatus {startedAt: numberelapsedSecs: numberetaSecs: number | null+ /** step and total count bytes (a download). */+ bytes?: boolean+ rateBps?: number | nulllogs: string[]error: string | nullresult: RunRecord | null@@ -197,3 +204,76 @@ export function gb(bytes: number | null | undefined): string {if (v < 0.1) return `${Math.max(1, Math.round(bytes / 1e6))} MB`return v < 10 ? `${v.toFixed(1)} GB` : `${Math.round(v)} GB`}++/** "740 MB", "1.24 GB": a download as it moves. */+export function sizeText(bytes: number): string {+ if (bytes < 1e9) return `${Math.round(bytes / 1e6)} MB`+ return bytes < 10e9 ? `${(bytes / 1e9).toFixed(2)} GB` : `${(bytes / 1e9).toFixed(1)} GB`+}++/** "740 MB of 1.99 GB · 37% · 4.2 MB/s · about 5 min left", the line under+ * the bar while a run downloads. Speed and time come once Rust has a few+ * seconds to measure. */+export function downloadLine(s: Pick<RunStatus, 'step' | 'total' | 'rateBps' | 'etaSecs'>): string {+ const parts = [`${sizeText(s.step)} of ${sizeText(s.total)}`]+ const share = phaseShare(s)+ if (share != null) parts.push(`${Math.floor(share * 100)}%`)+ if (s.rateBps != null) parts.push(s.rateBps >= 1e6 ? `${(s.rateBps / 1e6).toFixed(1)} MB/s` : `${Math.round(s.rateBps / 1e3)} kB/s`)+ if (s.etaSecs != null && s.step < s.total) {+ parts.push(s.etaSecs < 60 ? `${Math.max(1, s.etaSecs)} s left` : `about ${roughDuration(s.etaSecs)} left`)+ }+ return parts.join(' · ')+}++export interface MmluVerdict {+ /** Right in the copy minus right in the original. */+ delta: number+ /** Answers that went from right to wrong and the other way, or null when+ * a record has no marks (before 3.0.9). */+ worse: number | null+ better: number | null+ /** 'loss' and 'gain' only when the change is larger than chance explains. */+ reading: 'same' | 'chance' | 'loss' | 'gain'+ text: string+}++/** The knowledge check, read honestly. Both checks ask the same questions,+ * so only the answers that changed carry information: with b turned wrong+ * and c turned right, chance alone gives a net change of about ±2·√(b+c)+ * (McNemar). Without marks, two totals of the same questions can only be+ * reported, not judged. */+export function mmluVerdict(before: Check, after: Check): MmluVerdict {+ const n = after.mmluN ?? after.n+ const delta = after.mmlu - before.mmlu+ const signed = delta > 0 ? `+${delta}` : `${delta}`+ const a = before.mmluMarks+ const b = after.mmluMarks+ if (!a || !b || a.length !== b.length) {+ const text = delta === 0+ ? `Same score on ${n} questions`+ : `${signed} of ${n} questions; too few to tell a loss from chance`+ return { delta, worse: null, better: null, reading: delta === 0 ? 'same' : 'chance', text }+ }+ let worse = 0+ let better = 0+ for (let i = 0; i < a.length; i++) {+ if (a[i] === '1' && b[i] === '0') worse+++ else if (a[i] === '0' && b[i] === '1') better+++ }+ const changed = worse + better+ const answers = (k: number) => `${k} answer${k === 1 ? '' : 's'}`+ if (changed === 0) {+ return { delta, worse, better, reading: 'same', text: `All ${n} answers the same as the original` }+ }+ const noise = 2 * Math.sqrt(changed)+ const reading = Math.abs(delta) <= noise ? 'chance' : delta < 0 ? 'loss' : 'gain'+ const verdict = reading === 'chance'+ ? 'within chance'+ : reading === 'loss'+ ? `a real loss of ${((-delta / n) * 100).toFixed(1)} points`+ : `a real gain of ${((delta / n) * 100).toFixed(1)} points`+ return {+ delta, worse, better, reading,+ text: `${answers(worse)} turned wrong, ${answers(better)} turned right (${signed} of ${n}): ${verdict}`,+ }+}diff --git a/src/components/models/ModelManager.tsx b/src/components/models/ModelManager.tsxindex 7dc04f42..7a997b51 100644--- a/src/components/models/ModelManager.tsx+++ b/src/components/models/ModelManager.tsx@@ -13,6 +13,7 @@ import { useProviderStore } from '../../stores/providerStore'import { ModelCard } from './ModelCard'import { RemoveRefusalsDialog } from './RemoveRefusalsDialog'import { useAbliterateStore } from '../../stores/abliterateStore'+import { downloadLine } from '../../api/abliterate'import { prefixModelName } from '../../api/providers/model-name'import { PullModelDialog } from './PullModelDialog'import { DiscoverModels } from './DiscoverModels'@@ -396,7 +397,8 @@ export function ModelManager() {// One quiet line above the list, not the empty-state block:// the list stays where it was while the run goes on.<p data-testid="remove-refusals-strip" className="t-body text-gray-500 dark:text-gray-400 mb-2">- Removing refusals from {ablStatus.modelName}: {ablStatus.phaseLabel || 'starting'}.{' '}+ Removing refusals from {ablStatus.modelName}: {ablStatus.phaseLabel || 'starting'}+ {ablStatus.bytes && ablStatus.total > 0 && ` (${downloadLine(ablStatus)})`}.{' '}<button type="button" className="underline hover:text-gray-900 dark:hover:text-white" onClick={() => openRemoveRefusals(ablStatus.sourcePath)}>Open</button></p>)}diff --git a/src/components/models/RemoveRefusalsDialog.tsx b/src/components/models/RemoveRefusalsDialog.tsxindex 2f78c322..52610b4d 100644--- a/src/components/models/RemoveRefusalsDialog.tsx+++ b/src/components/models/RemoveRefusalsDialog.tsx@@ -7,7 +7,7 @@ import { HINWEIS_TEXT } from '../../lib/hinweis'import { isWindows, openExternal } from '../../api/backend'import {abliterateCancel, abliterateDismiss, abliteratePlan, abliterateStart, abliterateTrashCopy,- gb, minutesRange, phaseShare, roughDuration,+ downloadLine, gb, minutesRange, mmluVerdict, phaseShare, roughDuration,type Check, type Mode, type Plan, type RunRecord, type RunStatus,} from '../../api/abliterate'import { useAbliterateStore } from '../../stores/abliterateStore'@@ -390,11 +390,21 @@ function RunView({ run, onClose, onUse, onModelsChanged }: { run: RunStatus } &style={{ width: share == null ? '0%' : `${Math.round(share * 100)}%` }}/></div>- <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>- {stepText(run)}- {run.elapsedSecs > 0 && ` · running for ${roughDuration(run.elapsedSecs)}`}- {run.etaSecs != null && ` · about ${roughDuration(run.etaSecs)} left`}- </p>+ {run.bytes && run.total > 0 ? (+ // A download says what it has, how fast and how long, on the+ // face of the window: 3.0.8 showed an empty bar and "running for+ // 26 minutes" while PyTorch came down.+ <>+ <p className="t-body font-mono text-gray-800 dark:text-gray-100" data-testid="remove-refusals-download">{downloadLine(run)}</p>+ {run.elapsedSecs > 0 && <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>Running for {roughDuration(run.elapsedSecs)}</p>}+ </>+ ) : (+ <p className={`t-micro ${HINWEIS_TEXT.ruhig}`}>+ {stepText(run)}+ {run.elapsedSecs > 0 && `${stepText(run) ? ' · ' : ''}running for ${roughDuration(run.elapsedSecs)}`}+ {run.etaSecs != null && ` · about ${roughDuration(run.etaSecs)} left`}+ </p>+ )}{run.best && (<p className="t-body text-gray-800 dark:text-gray-100" data-testid="remove-refusals-best">Best so far: trial {run.best.trial}, {run.best.refusals}@@ -491,7 +501,7 @@ function RunView({ run, onClose, onUse, onModelsChanged }: { run: RunStatus } &function stepText(run: RunStatus): string {if (!run.total) return ''- if (run.phase === 'download' || run.phase === 'setup') return `${gb(run.step)} of ${gb(run.total)}`+ if (run.bytes || run.phase === 'download' || run.phase === 'setup') return `${gb(run.step)} of ${gb(run.total)}`if (run.phase === 'trials') return `${run.step} of ${run.total} trials`if (run.phase === 'check_before' || run.phase === 'check_after') return `${run.step} of ${run.total} questions`if (run.phase === 'merge') return `part ${run.step} of ${run.total}`@@ -525,7 +535,9 @@ function ResultTable({ r }: { r: RunRecord }) {<td className="py-0.5 text-right font-mono text-gray-900 dark:text-white">{b}</td></tr>)- const of = (c: Check | null, k: keyof Check) => (c ? `${c[k]} of ${c.n}` : '–')+ const of = (c: Check | null, k: 'refusals' | 'falseAlarms') => (c ? `${c[k]} of ${c.n}` : '–')+ const mmlu = (c: Check | null) => (c ? `${c.mmlu} of ${c.mmluN ?? c.n}` : '–')+ const verdict = r.before && r.after ? mmluVerdict(r.before, r.after) : nullreturn (<table className="w-full t-body" data-testid="remove-refusals-result"><thead>@@ -538,7 +550,7 @@ function ResultTable({ r }: { r: RunRecord }) {<tbody>{row('Refused requests', of(r.before, 'refusals'), of(r.after, 'refusals'), 'JailbreakBench, prompts the search never saw')}{row('Refused harmless requests', of(r.before, 'falseAlarms'), of(r.after, 'falseAlarms'))}- {row('Knowledge check', of(r.before, 'mmlu'), of(r.after, 'mmlu'), 'MMLU questions answered right')}+ {row('Knowledge check', mmlu(r.before), mmlu(r.after), verdict ? `MMLU questions answered right. ${verdict.text}` : 'MMLU questions answered right')}{row('Refusals in the search',r.searchRefusalsBefore != null ? `${r.searchRefusalsBefore} of ${r.searchPrompts ?? '?'}` : '–',diff --git a/src/components/models/__tests__/remove-refusals-dialog.test.tsx b/src/components/models/__tests__/remove-refusals-dialog.test.tsxindex 3ec78798..521603eb 100644--- a/src/components/models/__tests__/remove-refusals-dialog.test.tsx+++ b/src/components/models/__tests__/remove-refusals-dialog.test.tsx@@ -184,6 +184,35 @@ describe('during and after', () => {expect(await screen.findByText(/Stopped/)).toBeTruthy()})+ it('a download shows bytes of total, share, speed and time left on the face of the window (3.0.9)', async () => {+ openFor()+ useAbliterateStore.setState({ status: status({+ phase: 'setup', phaseLabel: 'Installing PyTorch: downloading torch 2.14.1+cu130', step: 740e6, total: 1_990_600_000,+ bytes: true, rateBps: 4_200_000, etaSecs: 298, best: null, elapsedSecs: 1560,+ }) })+ const line = await screen.findByTestId('remove-refusals-download')+ expect(line.textContent).toBe('740 MB of 1.99 GB · 37% · 4.2 MB/s · about 5 min left')+ expect(screen.getByText('Installing PyTorch: downloading torch 2.14.1+cu130')).toBeTruthy()+ expect(screen.getByText('Running for 26 min')).toBeTruthy()+ // the bar has its share, not 0 % as in 3.0.8+ const bar = screen.getByTestId('remove-refusals-running').querySelector('.bg-lu-accent') as HTMLElement+ expect(bar.style.width).toBe('37%')+ })++ it('the knowledge check names the answers that changed and whether that is chance (3.0.9)', async () => {+ const m = (s: string) => s.padEnd(200, '0')+ const rec = {+ ...RECORD,+ before: { refusals: 41, falseAlarms: 6, mmlu: 3, n: 50, mmluN: 200, mmluMarks: m('111') },+ after: { refusals: 7, falseAlarms: 2, mmlu: 2, n: 50, mmluN: 200, mmluMarks: m('011') },+ }+ openFor()+ useAbliterateStore.setState({ status: status({ status: 'done', result: rec }) })+ const table = await screen.findByTestId('remove-refusals-result')+ expect(table.textContent).toContain('3 of 200')+ expect(table.textContent).toContain('1 answer turned wrong, 0 answers turned right (-1 of 200): within chance')+ })+it('the result card compares original and copy, and Use loads the copy', async () => {api.abliterateDismiss.mockResolvedValue(status({ status: 'idle', sourcePath: '' }))const { onUse, onModelsChanged } = openFor()